From 6dd080d60c81bae21d8a29eed6a6369ef498c4ef Mon Sep 17 00:00:00 2001
From: Ivica Ico Bukvic <ico@vt.edu>
Date: Wed, 15 Dec 2010 15:51:00 -0500
Subject: [PATCH] Pd-0.42.5-extended-l2ork-dev-20101215.tar.bz2

---
 doc/1.manual/1.introduction.txt               |    7 +-
 doc/1.manual/x1.htm                           |    2 +-
 doc/1.manual/x2.htm                           |    2 +-
 doc/1.manual/x5.htm                           |   27 +-
 doc/3.audio.examples/E07.evenodd.pd           |    6 +-
 doc/3.audio.examples/E10.complex.FM.pd        |    2 +-
 doc/3.audio.examples/H04.filter.sweep.pd      |   26 +-
 doc/3.audio.examples/H05.filter.floyd.pd      |   45 +-
 doc/3.audio.examples/I07.phase.vocoder.pd     |   92 +-
 doc/3.audio.examples/J01.even.odd.pd          |    2 +-
 doc/3.audio.examples/output~.pd               |   66 +
 doc/4.data.structures/07.sequencer.pd         |   18 +-
 doc/4.data.structures/output~.pd              |   66 +
 doc/5.reference/about.pd                      |  423 -
 doc/5.reference/help-intro.pd                 |    4 +-
 doc/5.reference/import-help.pd                |   19 -
 doc/5.reference/readsf~-help.pd               |   26 +-
 doc/6.externs/makefile                        |    2 +-
 doc/7.stuff/tools/testtone.pd                 |    2 +-
 extra/bonk~/bonk~-help.pd                     |  209 -
 extra/bonk~/bonk~.c                           | 1479 ---
 extra/bonk~/makefile                          |    4 -
 extra/bonk~/templates.txt                     |    4 -
 extra/choice/choice.pd_linux                  |  Bin 0 -> 9536 bytes
 extra/expr~/LICENSE.txt                       |  341 -
 extra/expr~/README.txt                        |   97 -
 extra/expr~/fts_to_pd.h                       |   41 -
 extra/expr~/makefile                          |  191 -
 extra/expr~/vexp.c                            | 2142 -----
 extra/expr~/vexp.h                            |  244 -
 extra/expr~/vexp_fun.c                        | 1315 ---
 extra/expr~/vexp_if.c                         | 1225 ---
 extra/fiddle~/fiddle~-help.pd                 |  142 -
 extra/fiddle~/fiddle~.c                       | 1845 ----
 extra/fiddle~/makefile                        |    4 -
 extra/loop~/loop~-help.pd                     |   74 -
 extra/loop~/loop~.c                           |  164 -
 extra/loop~/makefile                          |    4 -
 extra/loop~/test-loop~.pd                     |   58 -
 extra/lrshift~/lrshift~-help.pd               |   33 -
 extra/lrshift~/lrshift~.c                     |   76 -
 extra/lrshift~/makefile                       |    4 -
 extra/makefile                                |    4 +-
 extra/output~-help.pd                         |   11 -
 extra/output~.pd                              |  124 -
 extra/pd~/makefile                            |   15 -
 extra/pd~/notes.txt                           |    8 -
 extra/pd~/pdsched.c                           |   85 -
 extra/pd~/pd~-help.pd                         |   75 -
 extra/pd~/pd~-subprocess.pd                   |   60 -
 extra/pd~/pd~.c                               |  765 --
 extra/pd~/z.pd                                |   15 -
 extra/pique/pique.c                           |    3 +-
 extra/pique/pique.pd_linux                    |  Bin 0 -> 9552 bytes
 extra/sigmund~/makefile                       |    4 -
 extra/sigmund~/sigmund~-help.pd               |  194 -
 extra/sigmund~/sigmund~.c                     | 1651 ----
 extra/stdout/stdout.pd_linux                  |  Bin 0 -> 5424 bytes
 portaudio/include/pa_asio.h                   |   16 +-
 portaudio/include/pa_jack.h                   |    3 +-
 portaudio/include/pa_linux_alsa.h             |   10 +-
 portaudio/include/pa_mac_core.h               |    5 -
 portaudio/include/pa_win_ds.h                 |  101 -
 portaudio/include/pa_win_wasapi.h             |  391 -
 portaudio/include/pa_win_waveformat.h         |  199 -
 portaudio/include/pa_win_wmme.h               |   24 +-
 portaudio/include/portaudio.h                 |    6 +-
 portaudio/src/common/pa_allocation.h          |    8 +-
 portaudio/src/common/pa_converters.c          |   66 +-
 portaudio/src/common/pa_debugprint.c          |   61 +-
 portaudio/src/common/pa_dither.c              |   29 +-
 portaudio/src/common/pa_dither.h              |   18 +-
 portaudio/src/common/pa_endianness.h          |   30 +-
 portaudio/src/common/pa_front.c               |   31 +-
 portaudio/src/common/pa_hostapi.h             |   16 +-
 portaudio/src/common/pa_memorybarrier.h       |  127 -
 portaudio/src/common/pa_process.c             |  197 +-
 portaudio/src/common/pa_process.h             |    6 +-
 portaudio/src/common/pa_ringbuffer.c          |  184 +-
 portaudio/src/common/pa_ringbuffer.h          |  117 +-
 portaudio/src/common/pa_skeleton.c            |    8 +-
 portaudio/src/common/pa_stream.c              |   10 +-
 portaudio/src/common/pa_stream.h              |    8 +-
 portaudio/src/common/pa_trace.c               |    4 +-
 portaudio/src/common/pa_trace.h               |   32 +-
 portaudio/src/common/pa_util.h                |    7 +-
 portaudio/src/hostapi/alsa/pa_linux_alsa.c    |  623 +-
 .../hostapi/asio/iasiothiscallresolver.cpp    |   31 +-
 .../src/hostapi/asio/iasiothiscallresolver.h  |    2 +-
 portaudio/src/hostapi/asio/pa_asio.cpp        | 1544 +---
 portaudio/src/hostapi/coreaudio/notes.txt     |   22 +-
 portaudio/src/hostapi/coreaudio/pa_mac_core.c |  449 +-
 .../hostapi/coreaudio/pa_mac_core_blocking.c  |   88 +-
 .../hostapi/coreaudio/pa_mac_core_blocking.h  |    9 +-
 .../hostapi/coreaudio/pa_mac_core_internal.h  |   20 +-
 .../hostapi/coreaudio/pa_mac_core_utilities.c |  272 +-
 .../hostapi/coreaudio/pa_mac_core_utilities.h |   43 +-
 portaudio/src/hostapi/dsound/pa_win_ds.c      | 2864 ------
 .../src/hostapi/dsound/pa_win_ds_dynlink.c    |  224 -
 .../src/hostapi/dsound/pa_win_ds_dynlink.h    |  106 -
 portaudio/src/hostapi/jack/pa_jack.c          |   25 +-
 portaudio/src/hostapi/oss/pa_unix_oss.c       |  178 +-
 .../wasapi/mingw-include/AudioSessionTypes.h  |   94 -
 .../FunctionDiscoveryKeys_devpkey.h           |  186 -
 .../wasapi/mingw-include/audioclient.h        | 1177 ---
 .../wasapi/mingw-include/devicetopology.h     | 3275 -------
 .../wasapi/mingw-include/endpointvolume.h     |  620 --
 .../mingw-include/functiondiscoverykeys.h     |  255 -
 .../src/hostapi/wasapi/mingw-include/ks.h     | 3666 --------
 .../src/hostapi/wasapi/mingw-include/ksguid.h |   28 -
 .../hostapi/wasapi/mingw-include/ksmedia.h    | 4551 ----------
 .../hostapi/wasapi/mingw-include/ksproxy.h    |  639 --
 .../hostapi/wasapi/mingw-include/ksuuids.h    |  159 -
 .../wasapi/mingw-include/mmdeviceapi.h        |  929 --
 .../hostapi/wasapi/mingw-include/propidl.h    | 1275 ---
 .../hostapi/wasapi/mingw-include/propkey.h    | 4274 ---------
 .../hostapi/wasapi/mingw-include/propkeydef.h |   26 -
 .../hostapi/wasapi/mingw-include/propsys.h    | 3605 --------
 .../src/hostapi/wasapi/mingw-include/rpcsal.h |  113 -
 .../src/hostapi/wasapi/mingw-include/sal.h    |  252 -
 .../hostapi/wasapi/mingw-include/sdkddkver.h  |  225 -
 .../hostapi/wasapi/mingw-include/shtypes.h    |  468 -
 .../wasapi/mingw-include/structuredquery.h    | 2478 -----
 portaudio/src/hostapi/wasapi/pa_win_wasapi.c  | 4457 ---------
 portaudio/src/hostapi/wasapi/readme.txt       |   25 -
 portaudio/src/hostapi/wdmks/pa_win_wdmks.c    | 3304 -------
 portaudio/src/hostapi/wdmks/readme.txt        |   82 -
 portaudio/src/hostapi/wmme/pa_win_wmme.c      |  627 +-
 portaudio/src/os/unix/pa_unix_hostapis.c      |   29 +-
 portaudio/src/os/unix/pa_unix_util.c          |   66 +-
 portaudio/src/os/win/pa_win_hostapis.c        |   14 +-
 portaudio/src/os/win/pa_win_util.c            |   10 +-
 portaudio/src/os/win/pa_win_waveformat.c      |  154 -
 portaudio/src/os/win/pa_win_wdmks_utils.c     |  297 -
 portaudio/src/os/win/pa_win_wdmks_utils.h     |   65 -
 .../src/os/win/pa_x86_plain_converters.c      |    4 +-
 portmidi/CHANGELOG.txt                        |   10 -
 portmidi/README.txt                           |   15 +-
 portmidi/license.txt                          |    4 +-
 portmidi/pm_common/pminternal.h               |   16 +-
 portmidi/pm_common/pmutil.c                   |   62 +-
 portmidi/pm_common/pmutil.h                   |    3 -
 portmidi/pm_common/portmidi.c                 | 2308 ++---
 portmidi/pm_common/portmidi.h                 |  268 +-
 portmidi/pm_linux/README_LINUX.txt            |   18 -
 portmidi/pm_linux/pmlinuxalsa.c               |    2 +
 portmidi/pm_mac/finddefault.c                 |   55 -
 portmidi/pm_mac/pmmac.c                       |   25 +-
 portmidi/pm_mac/pmmacosxcm.c                  |   36 +-
 portmidi/pm_mac/pmmacosxcm.h                  |    4 +-
 portmidi/pm_mac/readbinaryplist.c             | 1079 ---
 portmidi/pm_mac/readbinaryplist.h             |   88 -
 portmidi/pm_win/README_WIN.txt                |  148 +-
 portmidi/pm_win/pmwin.c                       |  101 +-
 portmidi/pm_win/pmwinmm.c                     |  126 +-
 portmidi/porttime/porttime.h                  |   46 +-
 portmidi/porttime/ptlinux.c                   |    8 +-
 portmidi/porttime/ptmacosx_cf.c               |    5 -
 portmidi/porttime/ptmacosx_mach.c             |    6 -
 portmidi/porttime/ptwinmm.c                   |   11 +-
 src/aclocal.m4                                |   14 +
 src/config.h                                  |  226 +
 src/configure                                 | 7980 +++++++++++++++++
 src/configure.in                              |    4 +-
 src/d_delay.c                                 |   30 +-
 src/d_math.c                                  |    2 -
 src/d_ugen.c                                  |    5 -
 src/g_all_guis.c                              |   15 +-
 src/g_all_guis.h                              |   53 +-
 src/g_array.c                                 |   27 +-
 src/g_bang.c                                  |  404 +-
 src/g_canvas.c                                |   59 +-
 src/g_canvas.h                                |   18 +-
 src/g_editor.c                                |  919 +-
 src/g_graph.c                                 |   41 +-
 src/g_hdial.c                                 |  416 +-
 src/g_hslider.c                               |  377 +-
 src/g_magicglass.c                            |  413 +
 src/g_magicglass.h                            |   19 +
 src/g_mycanvas.c                              |  274 +-
 src/g_numbox.c                                |  534 +-
 src/g_rtext.c                                 |   51 +-
 src/g_scalar.c                                |    1 +
 src/g_text.c                                  |  322 +-
 src/g_toggle.c                                |  400 +-
 src/g_vdial.c                                 |  409 +-
 src/g_vslider.c                               |  388 +-
 src/g_vumeter.c                               |  644 +-
 src/helpbrowser.tcl                           |   23 +-
 src/m_binbuf.c                                |   44 +-
 src/m_obj.c                                   |    8 +-
 src/m_pd.h                                    |   10 +-
 src/m_sched.c                                 |    3 -
 src/makefile                                  |  311 +
 src/makefile.dependencies                     | 1115 +++
 src/makefile.in                               |   21 +-
 src/makefile.mingw                            |   14 +-
 src/makefile.nt                               |  175 +
 src/pd.tk                                     | 3944 +++++---
 src/s_audio.c                                 |   20 +-
 src/s_audio_alsa.c                            |    4 +-
 src/s_audio_jack.c                            |   18 +-
 src/s_audio_jack_old.c                        |  434 +
 src/s_audio_old.c                             |  912 ++
 src/s_file.c                                  |   23 +-
 src/s_inter.c                                 |   19 +-
 src/s_main.c                                  |   14 +-
 src/s_print.c                                 |    1 -
 src/t_tkcmd.c                                 |    2 +-
 src/x_arithmetic.c                            |    2 -
 src/x_gui.c                                   |   16 +
 src/x_interface.c                             |    1 -
 tcl/AppMain.tcl                               |   26 +
 tcl/apple_events.tcl                          |   53 +
 tcl/dialog_array.tcl                          |  328 +
 tcl/dialog_audio.tcl                          |  298 +
 tcl/dialog_canvas.tcl                         |  213 +
 tcl/dialog_find.tcl                           |  117 +
 tcl/dialog_font.tcl                           |  133 +
 tcl/dialog_gatom.tcl                          |  166 +
 tcl/dialog_iemgui.tcl                         |  772 ++
 tcl/dialog_midi.tcl                           |  344 +
 tcl/opt_parser.tcl                            |   78 +
 tcl/pd-gui.tcl                                |  503 ++
 tcl/pd_bindings.tcl                           |  263 +
 tcl/pd_connect.tcl                            |   92 +
 tcl/pd_menucommands.tcl                       |  219 +
 tcl/pd_menus.tcl                              |  473 +
 tcl/pdtk_array.tcl                            |  346 +
 tcl/pdtk_canvas.tcl                           |  169 +
 tcl/pdtk_text.tcl                             |   20 +
 tcl/pdwindow.tcl                              |   53 +
 tcl/pkgIndex.tcl                              |   28 +
 tcl/pkg_mkIndex.tcl                           |    9 +
 tcl/wheredoesthisgo.tcl                       |   97 +
 235 files changed, 26779 insertions(+), 62834 deletions(-)
 create mode 100644 doc/3.audio.examples/output~.pd
 create mode 100644 doc/4.data.structures/output~.pd
 delete mode 100644 doc/5.reference/about.pd
 delete mode 100644 doc/5.reference/import-help.pd
 delete mode 100644 extra/bonk~/bonk~-help.pd
 delete mode 100644 extra/bonk~/bonk~.c
 delete mode 100644 extra/bonk~/makefile
 delete mode 100644 extra/bonk~/templates.txt
 create mode 100755 extra/choice/choice.pd_linux
 delete mode 100644 extra/expr~/LICENSE.txt
 delete mode 100644 extra/expr~/README.txt
 delete mode 100644 extra/expr~/fts_to_pd.h
 delete mode 100644 extra/expr~/makefile
 delete mode 100644 extra/expr~/vexp.c
 delete mode 100644 extra/expr~/vexp.h
 delete mode 100644 extra/expr~/vexp_fun.c
 delete mode 100644 extra/expr~/vexp_if.c
 delete mode 100644 extra/fiddle~/fiddle~-help.pd
 delete mode 100644 extra/fiddle~/fiddle~.c
 delete mode 100644 extra/fiddle~/makefile
 delete mode 100644 extra/loop~/loop~-help.pd
 delete mode 100644 extra/loop~/loop~.c
 delete mode 100644 extra/loop~/makefile
 delete mode 100644 extra/loop~/test-loop~.pd
 delete mode 100644 extra/lrshift~/lrshift~-help.pd
 delete mode 100644 extra/lrshift~/lrshift~.c
 delete mode 100644 extra/lrshift~/makefile
 delete mode 100644 extra/output~-help.pd
 delete mode 100644 extra/output~.pd
 delete mode 100644 extra/pd~/makefile
 delete mode 100644 extra/pd~/notes.txt
 delete mode 100644 extra/pd~/pdsched.c
 delete mode 100644 extra/pd~/pd~-help.pd
 delete mode 100644 extra/pd~/pd~-subprocess.pd
 delete mode 100644 extra/pd~/pd~.c
 delete mode 100644 extra/pd~/z.pd
 create mode 100755 extra/pique/pique.pd_linux
 delete mode 100644 extra/sigmund~/makefile
 delete mode 100644 extra/sigmund~/sigmund~-help.pd
 delete mode 100644 extra/sigmund~/sigmund~.c
 create mode 100755 extra/stdout/stdout.pd_linux
 delete mode 100644 portaudio/include/pa_win_ds.h
 delete mode 100644 portaudio/include/pa_win_wasapi.h
 delete mode 100644 portaudio/include/pa_win_waveformat.h
 delete mode 100644 portaudio/src/common/pa_memorybarrier.h
 delete mode 100644 portaudio/src/hostapi/dsound/pa_win_ds.c
 delete mode 100644 portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c
 delete mode 100644 portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/AudioSessionTypes.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/FunctionDiscoveryKeys_devpkey.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/audioclient.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/devicetopology.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/endpointvolume.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/functiondiscoverykeys.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/ks.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/ksguid.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/ksproxy.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/ksuuids.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/mmdeviceapi.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/propidl.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/propkey.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/propkeydef.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/propsys.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/rpcsal.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/sal.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/sdkddkver.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/shtypes.h
 delete mode 100644 portaudio/src/hostapi/wasapi/mingw-include/structuredquery.h
 delete mode 100644 portaudio/src/hostapi/wasapi/pa_win_wasapi.c
 delete mode 100644 portaudio/src/hostapi/wasapi/readme.txt
 delete mode 100644 portaudio/src/hostapi/wdmks/pa_win_wdmks.c
 delete mode 100644 portaudio/src/hostapi/wdmks/readme.txt
 delete mode 100644 portaudio/src/os/win/pa_win_waveformat.c
 delete mode 100644 portaudio/src/os/win/pa_win_wdmks_utils.c
 delete mode 100644 portaudio/src/os/win/pa_win_wdmks_utils.h
 delete mode 100644 portmidi/pm_mac/finddefault.c
 delete mode 100644 portmidi/pm_mac/readbinaryplist.c
 delete mode 100644 portmidi/pm_mac/readbinaryplist.h
 create mode 100644 src/aclocal.m4
 create mode 100644 src/config.h
 create mode 100755 src/configure
 create mode 100644 src/g_magicglass.c
 create mode 100644 src/g_magicglass.h
 create mode 100644 src/makefile
 create mode 100644 src/makefile.dependencies
 create mode 100644 src/makefile.nt
 create mode 100644 src/s_audio_jack_old.c
 create mode 100644 src/s_audio_old.c
 create mode 100644 tcl/AppMain.tcl
 create mode 100644 tcl/apple_events.tcl
 create mode 100644 tcl/dialog_array.tcl
 create mode 100644 tcl/dialog_audio.tcl
 create mode 100644 tcl/dialog_canvas.tcl
 create mode 100644 tcl/dialog_find.tcl
 create mode 100644 tcl/dialog_font.tcl
 create mode 100644 tcl/dialog_gatom.tcl
 create mode 100644 tcl/dialog_iemgui.tcl
 create mode 100644 tcl/dialog_midi.tcl
 create mode 100644 tcl/opt_parser.tcl
 create mode 100644 tcl/pd-gui.tcl
 create mode 100644 tcl/pd_bindings.tcl
 create mode 100644 tcl/pd_connect.tcl
 create mode 100644 tcl/pd_menucommands.tcl
 create mode 100644 tcl/pd_menus.tcl
 create mode 100644 tcl/pdtk_array.tcl
 create mode 100644 tcl/pdtk_canvas.tcl
 create mode 100644 tcl/pdtk_text.tcl
 create mode 100644 tcl/pdwindow.tcl
 create mode 100644 tcl/pkgIndex.tcl
 create mode 100755 tcl/pkg_mkIndex.tcl
 create mode 100644 tcl/wheredoesthisgo.tcl

diff --git a/doc/1.manual/1.introduction.txt b/doc/1.manual/1.introduction.txt
index f92097029..e38caafce 100644
--- a/doc/1.manual/1.introduction.txt
+++ b/doc/1.manual/1.introduction.txt
@@ -2,12 +2,17 @@ PD_VERSION
 
 A real-time graphical programming environment for live interactive
 computer music, Pd works on SGI machines, Microsoft Windows,
-Linux, and Max OSX.
+Linux, and Mac OSX.
 
 Pd is copyrighted, but is free for you to use for any reasonable purpose.
 See the file:
      PD_BASEDIR/LICENSE.txt
 
+L2Ork iteration offers rewrite of many of PD's core routines for the
+purpose of improving editor functionality and stability. It is
+distributed under the same license as base PD. For additional info see:
+    http://l2ork.music.vt.edu/main/
+
 Reference documentation for Pd lives in:
     file:PD_BASEDIR/doc/1.manual/index.htm
 or:
diff --git a/doc/1.manual/x1.htm b/doc/1.manual/x1.htm
index f1f884d1d..00fa7da13 100644
--- a/doc/1.manual/x1.htm
+++ b/doc/1.manual/x1.htm
@@ -73,7 +73,7 @@ To get started writing your own C extensions, refer to chapter 4 of this manual.
 <P> There is a new Pd community web site,
 <a href="http://www.pure-data.info/"> pure-data.info</a>, which aims to be the
 central resource for Pd, from documentation and
-downloads; to forums, member pages, a patch exchange.
+downloads; to forums, member pages, and a patch exchange.
 
 <P> There is a growing number of Pd-related projects hosted at 
 <A HREF="http://pure-data.sf.net">SourceForge</A>.  This is open to all Pd
diff --git a/doc/1.manual/x2.htm b/doc/1.manual/x2.htm
index 9879078eb..05b4d84b0 100644
--- a/doc/1.manual/x2.htm
+++ b/doc/1.manual/x2.htm
@@ -110,7 +110,7 @@ In this case the object will be the kind that carries out addition,
 and the "13" initializes the amount to add.
 
 <P> Atoms are either numbers or <I>
-symbols </I> like "+".  Anything that is not a valid number os considered a
+symbols </I> like "+".  Anything that is not a valid number is considered a
 symbol.   Valid numbers may or may not have a decimal point (for instance, 12,
 15.6, -.456), or may be
 written in exponential notation (such as "4.5e6", which means "4.5 multiplied
diff --git a/doc/1.manual/x5.htm b/doc/1.manual/x5.htm
index 671d967d9..c07d48ddd 100644
--- a/doc/1.manual/x5.htm
+++ b/doc/1.manual/x5.htm
@@ -20,7 +20,32 @@
 
 <H3> <A name="s2"> 5.1. release notes </A> </H3>
 
-<P> ------------------ 0.42.1 ---------------------------
+<P> ------------------ 0.42-5 ---------------------------
+
+<P> broken abs~ and log~ fixed
+
+<P> pd~ -ninsig 0 hang fixed
+
+<P> testtone updated and 16ch version added
+
+<P> lrshift~ bug fix
+
+<P> 32 channel limit removed for portaudio (ASIO/Windows and Mac)
+
+<P> ------------------ 0.42-4 ---------------------------
+
+<P> added -noautopatch startup argument to defeat auto-connecting to
+new objects (some folks like it and others hate it)
+
+<P> gfxstub bug fix
+
+<P> fixed crash on deleting "s" objects with no args
+
+<P> re-fixed seteuid(0 problem
+
+<P> fixed crash on "find $1" (still not useful though)
+
+<P> ------------------ 0.42.1-3 ---------------------------
 
 <P> Bug fix on Windows(cancelling window close deactivated window).
 
diff --git a/doc/3.audio.examples/E07.evenodd.pd b/doc/3.audio.examples/E07.evenodd.pd
index 9715e1ea5..e6d3851e0 100644
--- a/doc/3.audio.examples/E07.evenodd.pd
+++ b/doc/3.audio.examples/E07.evenodd.pd
@@ -38,11 +38,11 @@
 #X text 299 152 <--transpose;
 #N canvas 0 0 538 208 make-table 0;
 #X obj 38 71 loadbang;
-#X text 16 11 This patch loads a sequence of pitches into array1. The
+#X text 16 11 This patch loads a sequence of pitches into E07. The
 values are floating-point \, so we could use microtones (60.5 \, for
 example) if we wish.;
-#X msg 38 99 \; array1 0 55 56 57 55 57 61 55 61 63 57 63 \; array1
-yticks 36 12 1 \; array1 ylabel 12 36 48 60 72 84 96;
+#X msg 38 99 \; E07 0 55 56 57 55 57 61 55 61 63 57 63 \; E07
+yticks 36 12 1 \; E07 ylabel 12 36 48 60 72 84 96;
 #X connect 0 0 2 0;
 #X restore 527 195 pd make-table;
 #X obj 176 50 sel 0;
diff --git a/doc/3.audio.examples/E10.complex.FM.pd b/doc/3.audio.examples/E10.complex.FM.pd
index 094d68ed6..fbd6ce990 100644
--- a/doc/3.audio.examples/E10.complex.FM.pd
+++ b/doc/3.audio.examples/E10.complex.FM.pd
@@ -43,7 +43,7 @@ frequency for showing spectra: the 16th bin in a 4096-point spectrum
 #X text 273 232 toggle to graph repeatedly;
 #X text 262 212 bang to graph once;
 #X obj 16 494 t b f;
-#X obj 19 295 tabwrite~ E10-signal;
+#X obj 19 295 tabwrite~ E10-spectrum;
 #X obj 208 295 tabwrite~ E10-spectrum;
 #X text 72 536 set carrier multiplier and modulation multipliers after
 fundamental;
diff --git a/doc/3.audio.examples/H04.filter.sweep.pd b/doc/3.audio.examples/H04.filter.sweep.pd
index e4f3cf091..1675e9a65 100644
--- a/doc/3.audio.examples/H04.filter.sweep.pd
+++ b/doc/3.audio.examples/H04.filter.sweep.pd
@@ -1,4 +1,4 @@
-#N canvas 360 15 553 524 12;
+#N canvas 360 22 557 528 12;
 #X floatatom 44 146 5 0 150 0 - #0-pitch -;
 #X text 126 9 SWEEPING FILTERS;
 #X obj 44 193 phasor~;
@@ -43,6 +43,30 @@ sweep speeds.;
 "vcf~" instead of "bp~". The vcf~ module takes an audio signal to set
 center frequency. (Q is still set by messages though.) Vcf is computationally
 somewhat more expensive than bp~.;
+#N canvas 0 22 612 404 conversion-tables 0;
+#N canvas 0 22 450 300 graph2 0;
+#X array mtof 130 float 1;
+#A 0 8.1758 8.66196 9.17702 9.72272 10.3009 10.9134 11.5623 12.2499
+12.9783 13.75 14.5676 15.4339 16.3516 17.3239 18.354 19.4454 20.6017
+21.8268 23.1247 24.4997 25.9565 27.5 29.1352 30.8677 32.7032 34.6478
+36.7081 38.8909 41.2034 43.6535 46.2493 48.9994 51.9131 55 58.2705
+61.7354 65.4064 69.2957 73.4162 77.7817 82.4069 87.3071 92.4986 97.9989
+103.826 110 116.541 123.471 130.813 138.591 146.832 155.563 164.814
+174.614 184.997 195.998 207.652 220 233.082 246.942 261.626 277.183
+293.665 311.127 329.628 349.228 369.994 391.995 415.305 440 466.164
+493.883 523.251 554.365 587.33 622.254 659.255 698.456 739.989 783.991
+830.609 880 932.328 987.767 1046.5 1108.73 1174.66 1244.51 1318.51
+1396.91 1479.98 1567.98 1661.22 1760 1864.66 1975.53 2093 2217.46 2349.32
+2489.02 2637.02 2793.83 2959.96 3135.96 3322.44 3520 3729.31 3951.07
+4186.01 4434.92 4698.64 4978.03 5274.04 5587.65 5919.91 6271.93 6644.88
+7040 7458.62 7902.13 8372.02 8869.84 9397.27 9956.06 10548.1 11175.3
+11839.8 12543.9 13289.8 14080;
+#X coords 0 12000 130 0 200 100 1;
+#X restore 309 225 graph;
+#X text 319 333 ------ 130 samples ------;
+#X text 518 318 0;
+#X text 520 218 12000;
+#X restore 168 463 pd conversion-tables;
 #X connect 0 0 21 0;
 #X connect 2 0 8 0;
 #X connect 3 0 9 0;
diff --git a/doc/3.audio.examples/H05.filter.floyd.pd b/doc/3.audio.examples/H05.filter.floyd.pd
index 2187f05d2..401b56289 100644
--- a/doc/3.audio.examples/H05.filter.floyd.pd
+++ b/doc/3.audio.examples/H05.filter.floyd.pd
@@ -1,30 +1,31 @@
-#N canvas 708 41 555 646 12;
-#N canvas 0 0 600 392 conversion-tables 0;
-#N canvas 0 0 450 300 graph1 0;
+#N canvas 288 109 559 650 12;
+#N canvas 0 22 604 396 conversion-tables 0;
+#N canvas 0 22 450 300 graph1 0;
 #X array dbtorms 123 float 1;
 #A 0 0 0 1.25893e-05 1.41254e-05 1.58489e-05 1.77828e-05 1.99526e-05
 2.23872e-05 2.51189e-05 2.81838e-05 3.16228e-05 3.54813e-05 3.98107e-05
 4.46684e-05 5.01187e-05 5.62341e-05 6.30957e-05 7.07946e-05 7.94328e-05
-8.91251e-05 1e-04 0.000112202 0.000125893 0.000141254 0.000158489 0.000177828
-0.000199526 0.000223872 0.000251189 0.000281838 0.000316228 0.000354813
-0.000398107 0.000446684 0.000501187 0.000562341 0.000630957 0.000707946
-0.000794328 0.000891251 0.001 0.00112202 0.00125893 0.00141254 0.00158489
-0.00177828 0.00199526 0.00223872 0.00251189 0.00281838 0.00316228 0.00354813
-0.00398107 0.00446684 0.00501187 0.00562341 0.00630957 0.00707946 0.00794328
-0.00891251 0.01 0.0112202 0.0125893 0.0141254 0.0158489 0.0177828 0.0199526
-0.0223872 0.0251189 0.0281838 0.0316228 0.0354813 0.0398107 0.0446684
-0.0501187 0.0562341 0.0630957 0.0707946 0.0794328 0.0891251 0.1 0.112202
-0.125893 0.141254 0.158489 0.177828 0.199526 0.223872 0.251189 0.281838
-0.316228 0.354813 0.398107 0.446684 0.501187 0.562341 0.630957 0.707946
-0.794328 0.891251 1 1.12202 1.25893 1.41254 1.58489 1.77828 1.99526
-2.23872 2.51189 2.81838 3.16228 3.54813 3.98107 4.46684 5.01187 5.62341
-6.30957 7.07946 7.94328 8.91251 10 11.2202 12.5893;
+8.91251e-05 0.0001 0.000112202 0.000125893 0.000141254 0.000158489
+0.000177828 0.000199526 0.000223872 0.000251189 0.000281838 0.000316228
+0.000354813 0.000398107 0.000446684 0.000501187 0.000562341 0.000630957
+0.000707946 0.000794328 0.000891251 0.001 0.00112202 0.00125893 0.00141254
+0.00158489 0.00177828 0.00199526 0.00223872 0.00251189 0.00281838 0.00316228
+0.00354813 0.00398107 0.00446684 0.00501187 0.00562341 0.00630957 0.00707946
+0.00794328 0.00891251 0.01 0.0112202 0.0125893 0.0141254 0.0158489
+0.0177828 0.0199526 0.0223872 0.0251189 0.0281838 0.0316228 0.0354813
+0.0398107 0.0446684 0.0501187 0.0562341 0.0630957 0.0707946 0.0794328
+0.0891251 0.1 0.112202 0.125893 0.141254 0.158489 0.177828 0.199526
+0.223872 0.251189 0.281838 0.316228 0.354813 0.398107 0.446684 0.501187
+0.562341 0.630957 0.707946 0.794328 0.891251 1 1.12202 1.25893 1.41254
+1.58489 1.77828 1.99526 2.23872 2.51189 2.81838 3.16228 3.54813 3.98107
+4.46684 5.01187 5.62341 6.30957 7.07946 7.94328 8.91251 10 11.2202
+12.5893;
 #X coords 0 10 123 0 200 100 1;
 #X restore 302 48 graph;
 #X text 504 141 0;
 #X text 506 41 10;
 #X text 321 151 ------ 123 samples ------;
-#N canvas 0 0 450 300 graph2 0;
+#N canvas 0 22 450 300 graph2 0;
 #X array mtof 130 float 1;
 #A 0 8.1758 8.66196 9.17702 9.72272 10.3009 10.9134 11.5623 12.2499
 12.9783 13.75 14.5676 15.4339 16.3516 17.3239 18.354 19.4454 20.6017
@@ -65,7 +66,7 @@
 #X obj 55 145 + 1;
 #X obj 22 217 mtof;
 #X obj 55 169 mod 8;
-#N canvas 0 0 450 300 graph1 0;
+#N canvas 0 22 450 300 graph1 0;
 #X array \$0-array1 8 float 2;
 #X coords 0 96 8 36 200 100 1;
 #X restore 340 144 graph;
@@ -74,9 +75,9 @@
 #X text 107 147 sequencer for;
 #X text 122 164 8 note loop;
 #X obj 16 576 output~;
-#X obj 22 104 tgl 15 0 empty \$1-metro empty 0 -6 0 8 -262144 -1 -1
-1 1;
-#N canvas 876 177 375 255 startup 0;
+#X obj 22 104 tgl 15 0 empty \$0-metro empty 0 -6 0 8 -262144 -1 -1
+0 1;
+#N canvas 876 177 379 259 startup 0;
 #X obj 22 24 loadbang;
 #X obj 22 48 bng 15 250 50 0 empty empty empty 0 -6 0 8 -262144 -1
 -1;
diff --git a/doc/3.audio.examples/I07.phase.vocoder.pd b/doc/3.audio.examples/I07.phase.vocoder.pd
index 950174368..735b8cd2e 100644
--- a/doc/3.audio.examples/I07.phase.vocoder.pd
+++ b/doc/3.audio.examples/I07.phase.vocoder.pd
@@ -1,8 +1,8 @@
-#N canvas 164 25 744 599 12;
+#N canvas 425 33 744 599 12;
 #X floatatom 494 315 5 0 0 0 - transpo-set -;
 #X floatatom 167 383 3 0 0 0 - speed-set -;
 #X floatatom 55 385 7 0 0 0 - location-set -;
-#N canvas 199 40 821 693 fft-analysis 0;
+#N canvas 90 42 821 693 fft-analysis 0;
 #X obj 51 477 *~;
 #X obj 18 477 *~;
 #X obj 18 499 -~;
@@ -39,7 +39,7 @@ bang;
 #X obj 97 425 q8_rsqrt~;
 #N canvas 139 105 1006 799 read-windows 0;
 #X obj 18 693 *~;
-#X obj 364 448 r window-size;
+#X obj 340 448 r window-size;
 #X obj 156 300 f;
 #X obj 102 91 r window-size;
 #X obj 102 139 /;
@@ -60,14 +60,14 @@ bang;
 #X text 188 394 reading location (samples);
 #X obj 51 597 / 4;
 #X obj 288 245 * 0.01;
-#X floatatom 364 498 7 0 0 0 - - -;
-#X obj 364 474 *;
-#X obj 502 347 r transpo;
-#X obj 502 369 * 0.01;
-#X obj 504 390 + 69;
-#X obj 505 411 mtof;
-#X obj 505 433 / 440;
-#X obj 399 474 t b f;
+#X floatatom 340 498 7 0 0 0 - - -;
+#X obj 340 474 *;
+#X obj 499 365 r transpo;
+#X obj 499 387 * 0.01;
+#X obj 501 408 + 69;
+#X obj 502 429 mtof;
+#X obj 502 451 / 440;
+#X obj 375 474 t b f;
 #X obj 19 719 outlet~;
 #X obj 195 720 outlet~;
 #X obj 218 664 tabreceive~ \$0-hann;
@@ -77,7 +77,7 @@ bang;
 #X obj 768 508 r speed;
 #X msg 768 532 set \$1;
 #X obj 768 557 s speed-set;
-#X text 432 498 stretched window size (samples);
+#X text 411 498 stretched window size (samples);
 #X obj 877 507 r transpo;
 #X msg 877 533 set \$1;
 #X obj 877 558 s transpo-set;
@@ -123,8 +123,8 @@ by "location". If "speed" is nonzero \, "location" automatically precesses.
 #X obj 845 684 r auto;
 #X obj 730 685 r no-detune;
 #X msg 730 707 \; detune 0;
-#X text 321 280 loop to precess the location according;
-#X text 320 296 to the "speed" parameter.;
+#X text 326 275 loop to precess the location according;
+#X text 325 291 to the "speed" parameter.;
 #X text 611 31 if location changes \, update number box;
 #X text 610 50 in main window via "location-set" \, but;
 #X text 613 69 taking care to limit frequency of updates.;
@@ -136,14 +136,6 @@ by "location". If "speed" is nonzero \, "location" automatically precesses.
 #X text 496 527 "rewind" control takes us;
 #X text 499 545 to a location depending on;
 #X text 499 564 stretched window size.;
-#X obj 593 457 t b f;
-#X obj 617 395 samplerate~;
-#X obj 593 348 r \$0-insamprate;
-#X obj 593 418 /;
-#X obj 505 455 * 1;
-#X text 494 312 desired transposition and sample;
-#X text 494 329 rate correction for soundfile;
-#X obj 593 370 t f b;
 #X connect 0 0 30 0;
 #X connect 1 0 23 0;
 #X connect 2 0 11 0;
@@ -179,7 +171,7 @@ by "location". If "speed" is nonzero \, "location" automatically precesses.
 #X connect 25 0 26 0;
 #X connect 26 0 27 0;
 #X connect 27 0 28 0;
-#X connect 28 0 99 0;
+#X connect 28 0 29 0;
 #X connect 29 0 23 0;
 #X connect 29 1 23 1;
 #X connect 32 0 5 1;
@@ -224,14 +216,6 @@ by "location". If "speed" is nonzero \, "location" automatically precesses.
 #X connect 77 0 75 0;
 #X connect 79 0 78 0;
 #X connect 80 0 81 0;
-#X connect 95 0 99 0;
-#X connect 95 1 99 1;
-#X connect 96 0 98 1;
-#X connect 97 0 102 0;
-#X connect 98 0 95 0;
-#X connect 99 0 29 0;
-#X connect 102 0 98 0;
-#X connect 102 1 96 0;
 #X restore 109 133 pd read-windows;
 #X obj 137 543 tabsend~ prev-imag;
 #X obj 136 567 tabsend~ prev-real;
@@ -363,11 +347,11 @@ shifts the signal to the left or right depending on its argument.)
 #X connect 54 0 21 0;
 #X restore 55 480 pd fft-analysis;
 #N canvas 260 23 647 768 phase-tables 0;
-#N canvas 0 0 450 300 (subpatch) 0;
+#N canvas 0 0 450 300 graph2 0;
 #X array prev-imag 4096 float 0;
 #X coords 0 1000 4096 -1000 400 300 1;
 #X restore 169 326 graph;
-#N canvas 0 0 450 300 (subpatch) 0;
+#N canvas 0 0 450 300 graph3 0;
 #X array prev-real 4096 float 0;
 #X coords 0 500 4096 -500 400 300 1;
 #X restore 170 17 graph;
@@ -378,9 +362,9 @@ shifts the signal to the left or right depending on its argument.)
 #X text 389 359 normal;
 #X obj 56 517 output~;
 #N canvas 0 110 565 454 hann-window 0;
-#N canvas 0 0 450 300 (subpatch) 0;
-#X array \$0-hann 4096 float 0;
-#X coords 0 1 4095 0 300 100 1;
+#N canvas 0 0 450 300 graph1 0;
+#X array \$0-hann 1024 float 0;
+#X coords 0 1 1023 0 300 100 1;
 #X restore 82 311 graph;
 #X obj 378 165 osc~;
 #X obj 378 190 *~ -0.5;
@@ -428,9 +412,9 @@ and window-msec (analysis window size in seconds and msec).;
 #X connect 19 1 18 0;
 #X restore 440 528 pd hann-window;
 #N canvas 388 86 694 447 insample 0;
-#N canvas 0 0 450 300 (subpatch) 0;
-#X array \$0-sample 82301 float 0;
-#X coords 0 1 82300 -1 400 150 1;
+#N canvas 0 0 450 300 graph1 0;
+#X array \$0-sample 160161 float 0;
+#X coords 0 1 160160 -1 400 150 1;
 #X restore 281 135 graph;
 #X obj 28 133 r read-sample;
 #X obj 28 184 unpack s f;
@@ -449,12 +433,12 @@ and window-msec (analysis window size in seconds and msec).;
 #X obj 28 381 * 1000;
 #X obj 28 404 s \$0-samp-msec;
 #X obj 66 357 r \$0-insamprate;
-#X obj 37 68 hip~ 5;
-#X obj 37 44 adc~ 1;
+#X obj 29 70 hip~ 5;
+#X obj 29 46 adc~ 1;
 #X obj 29 9 inlet;
-#X obj 99 44 samplerate~;
+#X obj 91 46 samplerate~;
 #X obj 29 93 tabwrite~ \$0-sample;
-#X obj 99 68 s \$0-insamprate;
+#X obj 91 70 s \$0-insamprate;
 #X msg 285 383 \; read-sample ../sound/voice.wav;
 #X obj 276 20 inlet;
 #X obj 276 42 openpanel;
@@ -479,7 +463,7 @@ and window-msec (analysis window size in seconds and msec).;
 #X connect 18 0 22 0;
 #X connect 19 0 18 0;
 #X connect 20 0 21 0;
-#X connect 20 0 22 0;
+#X connect 20 0 19 0;
 #X connect 21 0 23 0;
 #X connect 25 0 26 0;
 #X connect 26 0 27 0;
@@ -501,6 +485,7 @@ and window-msec (analysis window size in seconds and msec).;
 #X obj 262 408 s rewind;
 #X msg 345 336 200;
 #X msg 345 358 100;
+#X msg 345 380 20;
 #X text 386 335 contract;
 #X text 390 380 expand;
 #X obj 493 407 s lock;
@@ -542,7 +527,6 @@ to see the workings.;
 #X obj 535 460 bng 15 250 50 0 empty empty empty 0 -6 0 8 -262144 -1
 -1;
 #X text 466 458 file ->;
-#X msg 345 380 20;
 #X connect 0 0 5 0;
 #X connect 1 0 21 0;
 #X connect 2 0 20 0;
@@ -552,13 +536,13 @@ to see the workings.;
 #X connect 14 0 16 0;
 #X connect 15 0 16 0;
 #X connect 17 0 11 0;
-#X connect 19 0 28 0;
+#X connect 19 0 29 0;
 #X connect 22 0 23 0;
-#X connect 24 0 48 0;
-#X connect 25 0 48 0;
-#X connect 38 0 42 0;
-#X connect 39 0 42 0;
-#X connect 40 0 42 0;
-#X connect 41 0 42 0;
-#X connect 52 0 11 1;
-#X connect 54 0 48 0;
+#X connect 24 0 49 0;
+#X connect 25 0 49 0;
+#X connect 26 0 49 0;
+#X connect 39 0 43 0;
+#X connect 40 0 43 0;
+#X connect 41 0 43 0;
+#X connect 42 0 43 0;
+#X connect 53 0 11 1;
diff --git a/doc/3.audio.examples/J01.even.odd.pd b/doc/3.audio.examples/J01.even.odd.pd
index 71c9fdf56..18603bb3a 100644
--- a/doc/3.audio.examples/J01.even.odd.pd
+++ b/doc/3.audio.examples/J01.even.odd.pd
@@ -40,7 +40,7 @@ and heard. (Listen to the two outputs separately \, then together.)
 #X text 95 350 output level;
 #X text 100 308 for difference;
 #X text 157 77 <-- click to graph;
-#X msg 148 97 \; pd DSP 1;
+#X msg 148 97 \; pd dsp 1;
 #X obj 138 247 tabwrite~ \$0-difference;
 #X obj 138 270 tabwrite~ \$0-sum;
 #X obj 138 138 tabwrite~ \$0-phasor;
diff --git a/doc/3.audio.examples/output~.pd b/doc/3.audio.examples/output~.pd
new file mode 100644
index 000000000..81ad3b7fe
--- /dev/null
+++ b/doc/3.audio.examples/output~.pd
@@ -0,0 +1,66 @@
+#N canvas 0 0 615 578 12;
+#X obj 353 490 t b;
+#X obj 353 437 f;
+#X obj 353 515 f;
+#X msg 467 514 0;
+#X obj 353 467 moses 1;
+#X obj 467 486 t b f;
+#X obj 433 447 moses 1;
+#X obj 29 97 dbtorms;
+#X obj 85 170 inlet~;
+#X msg 299 310 \; pd dsp 1;
+#X obj 29 170 line~;
+#X obj 64 242 *~;
+#X obj 64 272 dac~;
+#X obj 29 127 pack 0 50;
+#X text 121 146 audio in;
+#X text 138 464 test if less than 1 -->;
+#X text 104 491 if true convert to bang -->;
+#X text 100 96 <-- convert from dB to linear units;
+#X floatatom 323 219 3 0 100 0 dB - -;
+#X obj 350 240 bng 15 250 50 0 empty empty mute -38 7 0 12 -262144
+-1 -1;
+#X text 118 126 <-- make a ramp to avoid clicks or zipper noise;
+#X obj 148 170 inlet~;
+#X obj 154 241 *~;
+#X text 373 378 MUTE logic:;
+#X obj 323 174 r \$0-master-lvl;
+#X obj 353 541 s \$0-master-lvl;
+#X obj 323 279 s \$0-master-out;
+#X obj 29 71 r \$0-master-out;
+#X obj 433 418 r \$0-master-out;
+#X text 60 10 Level control abstraction \, used in many of the Pd example
+patches. The "level" and "mute" controls show up on the parent \, calling
+patch.;
+#X text 66 517 previous nonzero master-lvl -->;
+#X text 138 421 recall previous;
+#X text 138 439 value of master-lvl -->;
+#X text 39 319 automatically start DSP -->;
+#X obj 85 192 hip~ 3;
+#X obj 147 192 hip~ 3;
+#X connect 0 0 2 0;
+#X connect 1 0 4 0;
+#X connect 2 0 25 0;
+#X connect 3 0 25 0;
+#X connect 4 0 0 0;
+#X connect 4 1 5 0;
+#X connect 5 0 3 0;
+#X connect 6 1 2 1;
+#X connect 7 0 13 0;
+#X connect 8 0 34 0;
+#X connect 10 0 22 0;
+#X connect 10 0 11 0;
+#X connect 11 0 12 0;
+#X connect 13 0 10 0;
+#X connect 18 0 9 0;
+#X connect 18 0 26 0;
+#X connect 19 0 1 0;
+#X connect 21 0 35 0;
+#X connect 22 0 12 1;
+#X connect 24 0 18 0;
+#X connect 27 0 7 0;
+#X connect 28 0 1 1;
+#X connect 28 0 6 0;
+#X connect 34 0 11 1;
+#X connect 35 0 22 1;
+#X coords 0 0 1 1 65 55 1 300 200;
diff --git a/doc/4.data.structures/07.sequencer.pd b/doc/4.data.structures/07.sequencer.pd
index 7bf97b39c..eb323520f 100644
--- a/doc/4.data.structures/07.sequencer.pd
+++ b/doc/4.data.structures/07.sequencer.pd
@@ -85,25 +85,25 @@ array pitch template-pitch array amp template-amp;
 #X floatatom 269 464 0 0 0 0 - - -;
 #X msg 55 484 start;
 #X msg 106 484 stop;
-#N canvas 137 388 559 411 data 0;
-#X scalar template-toplevel 3 86 900 \; 0 0 12 \; 10 0 12 \; \; 0 0
-0 \; 10 0 2.5 \; 11 0 0 \; \;;
-#X scalar template-toplevel 14 80 990 \; 0 0 12 \; 10 0 12 \; \; 0
+#N canvas 258 114 425 363 data 1;
+#X scalar template-toplevel 22 86 900 \; 0 0 12 \; 10 0 12 \; \; 0
+0 0 \; 10 0 2.5 \; 11 0 0 \; \;;
+#X scalar template-toplevel 33 80 990 \; 0 0 12 \; 10 0 12 \; \; 0
 0 2.5 \; 10 0 2.5 \; 11 0 0 \; \;;
-#X scalar template-toplevel 38 43.25 90 \; 0 65 12 \; 100 10 0 \; 100
+#X scalar template-toplevel 57 43.25 90 \; 0 65 12 \; 100 10 0 \; 100
 10 12 \; 230 50 0 \; 230 10 3 \; 240 60 0 \; 240 25 10 \; 250 60 0
 \; 250 37 10 \; 260 65 0.5 \; 285 65 0.5 \; \; 1 0 2 \; 103 0 1 \;
 195 0 2 \; 220 0 0.75 \; 225 0 1.25 \; 248 0 2.5 \; 251 0 2.25 \; 255
 0 0 \; 256 0 1.5 \; 260 0 0 \; 261 0 2 \; 265 0 0 \; 266 0 2.5 \; 270
 0 0 \; 271 0 3 \; 275 0 0 \; \;;
-#X scalar template-toplevel 64 80 900 \; 0 5 0.25 \; 60 5 0.25 \; \;
+#X scalar template-toplevel 83 80 900 \; 0 5 0.25 \; 60 5 0.25 \; \;
 0 0 0 \; 28 -0.25 3.5 \; 58 -0.25 0 \; \;;
-#X scalar template-toplevel 142 105 900 \; 0 0 12 \; 70 -20 12 \; \;
+#X scalar template-toplevel 161 105 900 \; 0 0 12 \; 70 -20 12 \; \;
 0 0 0 \; 10 0 2.5 \; 20 0 0 \; 30 0 0 \; 40 0 2.5 \; 50 0 0 \; 60 0
 2.5 \; 70 0 0 \; \;;
-#X scalar template-toplevel 319 63.5 909 \; 0 0 12 \; 50 0 12 \; \;
+#X scalar template-toplevel 338 63.5 909 \; 0 0 12 \; 50 0 12 \; \;
 0 0 4 \; 10 0 2.5 \; 50 0 0 \; \;;
-#X coords 0 102.75 1 102.5 0 0 0;
+#X coords 0 90.75 1 90.5 0 0 0;
 #X restore 55 364 pd data;
 #N canvas 82 467 332 145 stuff 0;
 #X msg 1 101 \; pd-data write xx.txt;
diff --git a/doc/4.data.structures/output~.pd b/doc/4.data.structures/output~.pd
new file mode 100644
index 000000000..07fb59f8b
--- /dev/null
+++ b/doc/4.data.structures/output~.pd
@@ -0,0 +1,66 @@
+#N canvas 0 0 757 616 12;
+#X obj 516 522 t b;
+#X obj 516 469 f;
+#X obj 516 547 f;
+#X msg 630 546 0;
+#X obj 516 499 moses 1;
+#X obj 630 518 t b f;
+#X obj 596 479 moses 1;
+#X obj 29 97 dbtorms;
+#X obj 85 170 inlet~;
+#X msg 278 300 \; pd dsp 1;
+#X obj 29 170 line~;
+#X obj 64 242 *~;
+#X obj 64 272 dac~;
+#X obj 29 127 pack 0 50;
+#X text 121 146 audio in;
+#X text 301 496 test if less than 1 -->;
+#X text 267 523 if true convert to bang -->;
+#X text 100 96 <-- convert from dB to linear units;
+#X floatatom 278 221 3 0 100 0 dB - -;
+#X obj 516 449 bng 15 250 50 0 empty empty mute -38 7 0 12 -262144
+-1 -1;
+#X text 118 126 <-- make a ramp to avoid clicks or zipper noise;
+#X obj 148 170 inlet~;
+#X obj 154 241 *~;
+#X text 502 399 MUTE logic:;
+#X obj 278 193 r \$0-master-lvl;
+#X obj 516 573 s \$0-master-lvl;
+#X obj 293 247 s \$0-master-out;
+#X obj 29 71 r \$0-master-out;
+#X obj 596 450 r \$0-master-out;
+#X text 60 10 Level control abstraction \, used in many of the Pd example
+patches. The "level" and "mute" controls show up on the parent \, calling
+patch.;
+#X text 229 549 previous nonzero master-lvl -->;
+#X text 301 453 recall previous;
+#X text 301 471 value of master-lvl -->;
+#X text 16 310 automatically start DSP -->;
+#X obj 85 192 hip~ 3;
+#X obj 147 192 hip~ 3;
+#X connect 0 0 2 0;
+#X connect 1 0 4 0;
+#X connect 2 0 25 0;
+#X connect 3 0 25 0;
+#X connect 4 0 0 0;
+#X connect 4 1 5 0;
+#X connect 5 0 3 0;
+#X connect 6 1 2 1;
+#X connect 7 0 13 0;
+#X connect 8 0 34 0;
+#X connect 10 0 22 0;
+#X connect 10 0 11 0;
+#X connect 11 0 12 0;
+#X connect 13 0 10 0;
+#X connect 18 0 9 0;
+#X connect 18 0 26 0;
+#X connect 19 0 1 0;
+#X connect 21 0 35 0;
+#X connect 22 0 12 1;
+#X connect 24 0 18 0;
+#X connect 27 0 7 0;
+#X connect 28 0 1 1;
+#X connect 28 0 6 0;
+#X connect 34 0 11 1;
+#X connect 35 0 22 1;
+#X coords 0 0 1 1 65 55 1;
diff --git a/doc/5.reference/about.pd b/doc/5.reference/about.pd
deleted file mode 100644
index 2a053b3ef..000000000
--- a/doc/5.reference/about.pd
+++ /dev/null
@@ -1,423 +0,0 @@
-#N canvas 40 40 426 466 10;
-#X obj 16 439 bng 15 150 50 0 \$0-credits-bng \$0-credits-bng empty
-20 7 0 12 -262144 -66577 -262144;
-#N canvas 0 22 450 300 \$0-gop 0;
-#X coords 0 0 20 320 20 320 2 0 0;
-#X restore 9 118 pd \$0-gop;
-#X obj 10 10 bng 25 250 50 0 empty \$0-nothing-at-all empty 17 7 0
-10 -2882 -1 -1;
-#X obj 35 211 pddp/pddplink ../manuals/Pd/License.html -text License.html
-;
-#X text 35 237 Reference documentation for Pd is available in html
-format:;
-#X obj 35 261 pddp/pddplink ../1.manual/index.htm -text Local copy
-of Pd Manual;
-#X obj 35 281 pddp/pddplink http://www.crca.ucsd.edu/~msp/Pd_documentation/index.htm
--text http://www.crca.ucsd.edu/~msp/Pd_documentation/index.htm;
-#X text 35 307 Much more documentation and other resources can be found
-at:;
-#X obj 35 327 pddp/pddplink http://www.puredata.info;
-#X obj 35 377 pddp/pddplink http://iem.kug.ac.at/mailinglists/pd-list/
-;
-#X text 35 357 The Pd mailing list archive can be found at:;
-#X text 35 397 Many more useful links are listed in the HTML documentation
-\, section 1.2.;
-#X obj 115 131 pddp/print;
-#N canvas 146 26 531 400 (subpatch) 0;
-#X obj 340 153 hcs/version;
-#X obj 313 101 loadbang;
-#X obj 313 126 t b b;
-#X obj 313 262 hcs/tcl_version;
-#X obj 313 306 print Tcl Version;
-#X msg 340 175 \$1.\$2.\$3-\$4;
-#X obj 340 202 print Pd Version;
-#N canvas 469 100 450 300 \$0-spark 0;
-#X obj 35 46 struct \$0-spark float x float y float coefx float coefy
-float active float c;
-#X obj 48 104 drawpolygon c 1 0 0 1 0 1 1 0 0 0 1;
-#X restore 197 41 pd \$0-spark;
-#N canvas 0 22 450 300 \$0-sparks 0;
-#X obj 40 77 plot a 0 0 0 0 0;
-#X obj 40 40 struct \$0-sparks float x float y array a \$0-spark;
-#X restore 197 68 pd \$0-sparks;
-#N canvas 494 145 450 300 \$0-line 0;
-#X text 274 228 <- hide GOP rectangle;
-#X obj 104 149 drawpolygon 333 1 10 a 10 b;
-#X obj 87 79 struct \$0-line float a float b;
-#X obj 4 229 drawpolygon 999 1 0 0 20 0 20 320 0 320 0 0;
-#X restore 197 14 pd \$0-line;
-#X obj 447 345 outlet;
-#N canvas 509 85 419 460 \$0-logo 0;
-#X obj 22 19 struct \$0-logo;
-#X text 35 418 hide gop-border;
-#X obj 55 393 filledpolygon 999 999 1 0 0 112 0 112 72 0 72 0 0;
-#X text 6 125 P;
-#X obj 29 114 drawcurve 0 5 10 15 10 45 10 45 5 45 21 45 12 45 12 45
-12 15 12 15 5 15 10 19 10 19 12 15 12 15 26 15 33 24 27 34 13 34 13
-34 14 34 14 32 26 32 29 24 25 16 14 17;
-#X obj 32 225 drawpolygon 0 6 63 25 63 13 55 13 64 13 64 45 71 45;
-#X obj 49 340 drawpolygon 777 2 6 71 111 71 111 6;
-#X obj 47 291 drawpolygon 555 2 2 67 107 67 107 2;
-#X obj 49 314 drawpolygon 666 2 4 69 109 69 109 4;
-#X text 7 200 D;
-#X text 1 315 shadow;
-#X obj 22 59 drawpolygon 0 2 105 59 85 59 85 65 20 65 20 59 0 59 0
-6 20 6 20 0 85 0 85 6 105 6 105 0 0 0 0 65 105 65 105 0;
-#X obj 36 183 filledpolygon 0 0 25 52 35 53 35 53 36 52 36 52 35;
-#X obj 34 203 filledpolygon 999 999 13 53 35 54 35 54 36 53 36 53 35
-;
-#X restore 57 103 pd \$0-logo;
-#X msg 205 188 scalar \$1-logo;
-#X obj 205 163 f \$0;
-#X obj 205 213 s pd-\$0-logo-gop;
-#N canvas 284 86 198 93 \$0-logo-gop 0;
-#X coords 0 0 112 72 112 72 2 0 0;
-#X restore 10 10 pd \$0-logo-gop;
-#X obj 15 348 outlet;
-#X obj 8 103 inlet;
-#N canvas 490 84 450 300 \$0-circle 0;
-#X obj 113 80 struct \$0-circle float x float y float c float c1;
-#X obj 113 107 filledpolygon 0 c1 13 0 0 1 0 1 1 0 1;
-#X obj 113 137 filledpolygon 0 c 11 0 0 1 0 1 1 0 1;
-#X restore 197 97 pd \$0-circle;
-#X obj 97 322 bng 20 250 50 0 empty empty Click_before_saving... 25
-7 0 10 -262144 -1 -1;
-#N canvas 0 22 398 312 clear 0;
-#X obj 68 37 inlet;
-#X obj 68 85 t b b b;
-#X msg 107 110 clear;
-#X obj 87 183 s \$0-br;
-#X msg 87 161 stop;
-#X msg 68 215 label \, color 0 2 0 \, label_pos 20 7;
-#X obj 68 239 s \$0-credits-bng;
-#X obj 107 136 s pd-\$0-gop;
-#X obj 186 136 s pd-\$0-logo-gop;
-#X connect 0 0 1 0;
-#X connect 1 0 5 0;
-#X connect 1 1 4 0;
-#X connect 1 2 2 0;
-#X connect 2 0 7 0;
-#X connect 2 0 8 0;
-#X connect 4 0 3 0;
-#X connect 5 0 6 0;
-#X restore 97 348 pd clear;
-#N canvas 280 28 514 563 credits-animation 0;
-#X obj 279 255 pointer;
-#N canvas 0 26 450 658 burn 0;
-#X obj 157 8 inlet;
-#X obj 46 8 inlet;
-#X obj 46 143 f;
-#X obj 80 143 + 1;
-#X obj 46 116 until;
-#X obj 46 62 t a b;
-#X obj 96 116 0;
-#X obj 46 299 +;
-#X obj 83 299 +;
-#X obj 46 196 t a a;
-#X obj 235 243 sel 0;
-#N canvas 0 22 450 300 spigot 0;
-#X obj 65 31 inlet;
-#X obj 135 31 inlet;
-#X obj 225 31 inlet;
-#X obj 54 103 spigot;
-#X obj 124 103 spigot;
-#X obj 54 141 outlet;
-#X obj 134 141 outlet;
-#X connect 0 0 3 0;
-#X connect 1 0 4 0;
-#X connect 2 0 4 1;
-#X connect 2 0 3 1;
-#X connect 3 0 5 0;
-#X connect 4 0 6 0;
-#X restore 46 326 pd spigot;
-#X obj 235 293 random 100;
-#X obj 235 317 moses 20;
-#X msg 235 339 1;
-#X obj 235 267 t b b;
-#X msg 277 266 0;
-#X floatatom 91 8 5 0 0 0 - - -;
-#X obj 46 413 t a a;
-#X obj 73 467 sel 0;
-#X obj 73 553 * 6.28319;
-#X obj 73 533 / 360;
-#X obj 73 597 sin;
-#X obj 100 597 cos;
-#X obj 73 575 t a a b;
-#X msg 46 89 10;
-#X obj 46 373 expr if (abs($f1)>$f3 || abs($f2)>$f3 \, 0 \, $f1) \;
-if (abs($f1)>$f3 || abs($f2)>$f3 \, 0 \, $f2);
-#X floatatom 344 338 5 0 0 0 - - -;
-#X obj 73 489 random 180;
-#X obj 73 511 - 90;
-#X obj 151 488 random 360;
-#X obj 163 600 random 50;
-#X obj 325 283 loadbang;
-#X msg 325 310 12;
-#X obj 46 217 get \$0-spark x coefx y coefy active;
-#X obj 46 441 set \$0-spark x y active;
-#X obj 73 622 set \$0-spark coefx coefy c;
-#X obj 46 170 element \$0-sparks a;
-#X obj 46 35 metro 30;
-#X connect 0 0 37 1;
-#X connect 1 0 38 0;
-#X connect 2 0 3 0;
-#X connect 2 0 37 0;
-#X connect 3 0 2 1;
-#X connect 4 0 2 0;
-#X connect 5 0 25 0;
-#X connect 5 1 6 0;
-#X connect 6 0 2 1;
-#X connect 7 0 11 0;
-#X connect 8 0 11 1;
-#X connect 9 0 34 0;
-#X connect 9 1 35 3;
-#X connect 9 1 36 3;
-#X connect 10 0 15 0;
-#X connect 10 1 11 2;
-#X connect 11 0 26 0;
-#X connect 11 1 26 1;
-#X connect 12 0 13 0;
-#X connect 13 0 14 0;
-#X connect 14 0 11 2;
-#X connect 14 0 35 2;
-#X connect 15 0 12 0;
-#X connect 15 1 16 0;
-#X connect 16 0 11 2;
-#X connect 17 0 38 1;
-#X connect 18 0 35 0;
-#X connect 18 1 19 0;
-#X connect 19 0 28 0;
-#X connect 19 0 30 0;
-#X connect 20 0 24 0;
-#X connect 21 0 20 0;
-#X connect 22 0 36 0;
-#X connect 23 0 36 1;
-#X connect 24 0 22 0;
-#X connect 24 1 23 0;
-#X connect 24 2 31 0;
-#X connect 25 0 4 0;
-#X connect 26 0 18 0;
-#X connect 26 1 35 1;
-#X connect 27 0 26 2;
-#X connect 28 0 29 0;
-#X connect 30 0 21 0;
-#X connect 31 0 36 2;
-#X connect 32 0 33 0;
-#X connect 33 0 26 2;
-#X connect 34 0 7 0;
-#X connect 34 1 7 1;
-#X connect 34 2 8 0;
-#X connect 34 3 8 1;
-#X connect 34 4 10 0;
-#X connect 37 0 9 0;
-#X connect 38 0 5 0;
-#X restore 170 331 pd burn;
-#X obj 140 94 f \$0;
-#X obj 140 138 pointer;
-#X msg 140 116 traverse pd-\$1-gop \, bang;
-#X obj 279 207 f \$0;
-#X msg 279 229 traverse pd-\$1-gop \, bang;
-#X msg 279 280 10 0 \$1;
-#X obj 95 283 0;
-#X obj 40 463 s \$0-credits-bng;
-#X msg 279 359 10 \$1;
-#X obj 65 259 del 6001;
-#X msg 99 322 500;
-#X obj 140 10 loadbang;
-#X obj 279 384 setsize \$0-sparks a;
-#X obj 128 384 set \$0-sparks y;
-#X obj 140 183 append \$0-line a b;
-#X obj 65 411 set \$0-line a;
-#X obj 279 304 append \$0-sparks x y;
-#X obj 128 357 line 0 40;
-#X obj 65 122 inlet;
-#X msg 128 259 0 \, 320 6000;
-#X msg 65 322 320;
-#N canvas 60 65 683 470 credits-loop 0;
-#X msg 11 399 label_pos \$1 7;
-#X obj 11 426 s \$0-credits-bng;
-#X obj 11 344 * 500;
-#X obj 297 37 loadbang;
-#X obj 91 161 list;
-#X obj 197 192 list length;
-#X obj 130 205 f;
-#X obj 130 230 + 1;
-#X obj 182 219 mod;
-#X msg 130 257 set label \, adddollar \$1;
-#X obj 91 183 t b a b;
-#X msg 297 64 list Miller_Puckette Jamie_Tittle Gerard_van_Dongen Hans-Christoph_Steiner
IOhannes_m_zmölnig Dave_Sabine Yves_Degoyon Thomas_Musil Thomas_Grill
Tim_Blechmann Mark_Danks Joseph_Sarlo Martin_Peach Cyrille_Henry Thomas_O_Fredericks
Bryan_Jurish Nicolas_Montgermont Alexandre_Quessy B.Bogart Winfried_Ritsch dmotd
lluís_gómez_i_bigordà Chris_McCormick chunlee David_Merrill Mathieu_Bouchard
Tom_Schouten Ed_Kelly Frank_Barknecht Franz_Zotter Günter_Geiger Georg_Holzmann
carmen_rocco Vibeke_Sorensen Rand_Steiger jasch Jonathan_Wilkes João_Pais
Krzysztof_Czaja Luke_Iannini mescalinum Michael_McGonagle Davide_Morelli
Sergi_Lario_Loyo Olaf_Matthes David_Plans_Casal Jamie_Bullock Rich_E
Russell_Bryant Ben_Saylor Fernando_Lopez-Lezcano Adam_Lindsay Karl_MacMillan
Toshinori_Ohkouchi Harry_Castle Christian_Feldbauer Kerry_Hagan Trevor_Johnson
Gerda_Strobl John_Harrison Paloma_Oliveira Alexandre_Castonguay Alexandre_Porres
-Andrew_Brouse Marc_Fournel Darsha_Hewitt Kyd_Campbell;
#X obj 11 371 + 20;
-#X obj 11 288 line;
-#X obj 91 7 r \$0-credits-bng;
-#X obj 91 34 route bang;
-#X obj 91 56 t b b;
-#X msg 11 148 0;
-#X obj 91 135 del 900;
-#X obj 18 195 del 200;
-#X msg 18 221 0 \, 1 800;
-#X msg 27 254 1 \, 0 2250;
-#X obj 11 317 pow 3;
-#X obj 279 355 del 2200;
-#X obj 91 332 del 3500;
-#N canvas 294 26 449 469 drip-animation 0;
-#X obj 192 139 f \$0;
-#X obj 192 187 pointer;
-#X msg 192 164 traverse pd-\$1-gop \, bang;
-#X obj 50 156 line;
-#X obj 31 23 inlet;
-#X obj 255 89 0;
-#X obj 192 111 t b b;
-#X obj 192 89 spigot 1;
-#X obj 50 181 pow 2.5;
-#X msg 50 129 0 \, 1 1250;
-#X obj 50 211 expr $f1*320;
-#X obj 31 101 del 1251;
-#X obj 31 45 t b b b;
-#X obj 172 426 s \$0-credits-bng;
-#X obj 109 258 random 999;
-#X msg 172 407 color 0 \$1 2;
-#X obj 192 258 append \$0-circle x y;
-#X msg 192 233 15 10 \$1;
-#X obj 173 387 expr -65536 * $i1 - 256 * $i2 - $i3 - 1;
-#X obj 173 325 expr min(int($f1/100)%10 \, 8)/8*255 \; min(int($f1/10)%10
-\, 8)/8*255 \; min($f1%10 \, 8)/8*255;
-#X obj 31 325 set \$0-circle y c c1;
-#X msg 109 298 0;
-#X msg 31 258 50 999 999;
-#X connect 0 0 2 0;
-#X connect 1 0 17 0;
-#X connect 2 0 1 0;
-#X connect 3 0 8 0;
-#X connect 4 0 12 0;
-#X connect 5 0 7 1;
-#X connect 6 0 0 0;
-#X connect 6 1 5 0;
-#X connect 7 0 6 0;
-#X connect 8 0 10 0;
-#X connect 9 0 3 0;
-#X connect 10 0 20 0;
-#X connect 11 0 22 0;
-#X connect 12 0 11 0;
-#X connect 12 1 9 0;
-#X connect 12 2 7 0;
-#X connect 12 2 14 0;
-#X connect 14 0 19 0;
-#X connect 14 0 20 1;
-#X connect 14 0 21 0;
-#X connect 15 0 13 0;
-#X connect 16 0 20 3;
-#X connect 17 0 16 0;
-#X connect 18 0 15 0;
-#X connect 19 0 18 0;
-#X connect 19 1 18 1;
-#X connect 19 2 18 2;
-#X connect 21 0 20 2;
-#X connect 22 0 20 0;
-#X restore 279 382 pd drip-animation;
-#X msg 118 81 stop;
-#X obj 118 103 s \$0-br;
-#X obj 151 332 r \$0-br;
-#X obj 148 135 r \$0-br;
-#X msg 110 287 label \$40;
-#X connect 0 0 1 0;
-#X connect 2 0 12 0;
-#X connect 3 0 11 0;
-#X connect 4 0 10 0;
-#X connect 5 0 8 1;
-#X connect 6 0 7 0;
-#X connect 7 0 8 0;
-#X connect 7 0 9 0;
-#X connect 8 0 6 1;
-#X connect 9 0 30 0;
-#X connect 10 0 21 0;
-#X connect 10 0 24 0;
-#X connect 10 1 30 0;
-#X connect 10 2 6 0;
-#X connect 11 0 4 1;
-#X connect 11 0 5 0;
-#X connect 12 0 0 0;
-#X connect 13 0 22 0;
-#X connect 14 0 15 0;
-#X connect 15 0 16 0;
-#X connect 16 0 17 0;
-#X connect 16 0 18 0;
-#X connect 16 0 19 0;
-#X connect 16 1 26 0;
-#X connect 17 0 13 0;
-#X connect 18 0 4 0;
-#X connect 18 0 23 0;
-#X connect 19 0 20 0;
-#X connect 20 0 13 0;
-#X connect 21 0 13 0;
-#X connect 22 0 2 0;
-#X connect 23 0 25 0;
-#X connect 24 0 1 0;
-#X connect 26 0 27 0;
-#X connect 28 0 24 0;
-#X connect 29 0 18 0;
-#X connect 30 0 1 0;
-#X restore 40 496 pd credits-loop;
-#X msg 40 441 label_pos 20 7 \, label Credits! \, color 0 2 2 \, bang
-;
-#X obj 140 37 t b b;
-#X obj 170 306 tgl 15 0 empty empty empty 17 7 0 10 -262144 -1 -1 0
-320;
-#X msg 140 160 1 319 \$1;
-#X connect 0 0 7 0;
-#X connect 2 0 4 0;
-#X connect 3 0 27 0;
-#X connect 4 0 3 0;
-#X connect 5 0 6 0;
-#X connect 6 0 0 0;
-#X connect 7 0 18 0;
-#X connect 8 0 26 0;
-#X connect 10 0 14 0;
-#X connect 11 0 8 0;
-#X connect 11 0 24 0;
-#X connect 11 0 22 0;
-#X connect 11 0 12 0;
-#X connect 12 0 15 0;
-#X connect 13 0 25 0;
-#X connect 16 0 17 1;
-#X connect 18 0 1 1;
-#X connect 18 0 15 1;
-#X connect 18 0 10 0;
-#X connect 19 0 15 0;
-#X connect 19 0 17 0;
-#X connect 20 0 11 0;
-#X connect 20 0 21 0;
-#X connect 21 0 19 0;
-#X connect 21 0 26 0;
-#X connect 22 0 17 0;
-#X connect 24 0 9 0;
-#X connect 25 0 2 0;
-#X connect 25 1 5 0;
-#X connect 26 0 1 0;
-#X connect 27 0 16 0;
-#X restore 8 267 pd credits-animation;
-#X msg 313 284 \$1.\$2.\$3;
-#X connect 0 0 5 0;
-#X connect 1 0 13 0;
-#X connect 1 0 2 0;
-#X connect 2 0 3 0;
-#X connect 2 1 0 0;
-#X connect 3 0 22 0;
-#X connect 5 0 6 0;
-#X connect 5 0 10 0;
-#X connect 12 0 14 0;
-#X connect 13 0 12 0;
-#X connect 17 0 21 0;
-#X connect 19 0 20 0;
-#X connect 22 0 4 0;
-#X coords 0 -1 1 1 112 72 2 10 10;
-#X restore 10 46 pd;
-#X text 9 31 |;
-#X text 131 48 A real-time graphical programming environment;
-#X text 131 65 for live interactive computer music \, Pd works;
-#X text 131 82 on SGI machines \, Microsoft Windows \, Linux \,;
-#X text 131 99 and Mac OSX.;
-#X text 36 165 Pd is copyrighted but is free for you to use for any
-reasonable purpose under the GNU GPL version 3 . Follow the link for
-more details about the license:;
-#X connect 2 0 13 0;
-#X connect 13 1 12 0;
diff --git a/doc/5.reference/help-intro.pd b/doc/5.reference/help-intro.pd
index cfaffddfd..1315f27c5 100644
--- a/doc/5.reference/help-intro.pd
+++ b/doc/5.reference/help-intro.pd
@@ -291,9 +291,9 @@
 #X obj 18 4338 append;
 #X text 118 4338 - add an element to a list;
 #X obj 18 4368 sublist;
-#X text 14 4449 scalar;
+#X obj 14 4449 scalar;
 #X text 104 4448 - draw a scalar on parent;
-#X text 15 4479 [scope~];
+#X obj 15 4479 scope~;
 #X text 115 4479 (use tabwrite~ now);
 #X obj 15 4509 namecanvas;
 #X obj 15 4539 template;
diff --git a/doc/5.reference/import-help.pd b/doc/5.reference/import-help.pd
deleted file mode 100644
index 8e62f3040..000000000
--- a/doc/5.reference/import-help.pd
+++ /dev/null
@@ -1,19 +0,0 @@
-#N canvas 121 22 423 338 10;
-#X declare -lib ext13 -lib memento -lib rradical;
-#X msg 21 102 bang;
-#X obj 21 150 import ext13 memento rradical;
-#X symbolatom 32 176 0 0 0 0 - - -;
-#X obj 21 202 print;
-#X text 68 101 get next item in list of loaded libs;
-#X text 80 125 start at the top of the list again;
-#X text 29 239 Sending bangs to [import] makes it output the loaded
-libraries one at a time.;
-#X msg 33 126 rewind;
-#X text 18 22 [import] loads libraries from the patch. On Pd 0.40.
-or greater \, it loads the library into the patch's local namespace.
-On older versions \, it loads the libraries into the global namespace.
-;
-#X connect 0 0 1 0;
-#X connect 1 0 2 0;
-#X connect 1 0 3 0;
-#X connect 7 0 1 0;
diff --git a/doc/5.reference/readsf~-help.pd b/doc/5.reference/readsf~-help.pd
index a8634fb3f..29c90988b 100644
--- a/doc/5.reference/readsf~-help.pd
+++ b/doc/5.reference/readsf~-help.pd
@@ -1,11 +1,11 @@
-#N canvas 340 118 785 483 12;
-#X msg 606 63 \; pd dsp 1;
-#X msg 99 240 1;
-#X msg 99 261 0;
+#N canvas 113 157 888 480 12;
+#X msg 561 8 \; pd dsp 1;
+#X msg 39 240 1;
+#X msg 39 261 0;
 #X obj 516 359 print didit;
 #X obj 139 361 env~ 16384;
 #X floatatom 139 380 0 0 0 0 - - -;
-#X msg 100 283 print;
+#X msg 40 283 print;
 #X obj 20 393 dac~;
 #X obj 233 360 env~ 16384;
 #X floatatom 233 379 0 0 0 0 - - -;
@@ -35,14 +35,12 @@ send a "1" to start playback. A "0" stops it.;
 automatically \, although only 2- 3- and 4- byte samples are accepted
 (4 bytes implies floating point and is not available in aiff format.)
 ;
-#X obj 116 442 soundfiler;
-#X text 24 442 see also:;
-#X msg 39 239 start;
-#X msg 39 262 stop;
-#X text 577 440 Updated for version 0.42-4;
-#X text 144 238 starts playback;
-#X text 144 260 stops it;
-#X obj 216 442 writesf~;
+#X text 647 450 Updated for version 0.37;
+#X obj 116 452 soundfiler;
+#X text 24 452 see also:;
+#X obj 216 452 readsf~;
+#X text 94 238 1 starts playback;
+#X text 97 261 0 stops it;
 #X connect 1 0 10 0;
 #X connect 2 0 10 0;
 #X connect 4 0 5 0;
@@ -63,5 +61,3 @@ automatically \, although only 2- 3- and 4- byte samples are accepted
 #X connect 16 0 7 1;
 #X connect 17 0 7 0;
 #X connect 19 0 10 0;
-#X connect 28 0 10 0;
-#X connect 29 0 10 0;
diff --git a/doc/6.externs/makefile b/doc/6.externs/makefile
index 8a5657fea..5f78fb1d3 100644
--- a/doc/6.externs/makefile
+++ b/doc/6.externs/makefile
@@ -61,7 +61,7 @@ LINUXINCLUDE =  -I../../src
 
 .c.pd_linux:
 	cc $(LINUXCFLAGS) $(LINUXINCLUDE) -o $*.o -c $*.c
-	ld -export_dynamic  -shared -o $*.pd_linux $*.o -lc -lm
+	ld -shared -o $*.pd_linux $*.o -lc -lm
 	strip --strip-unneeded $*.pd_linux
 	rm $*.o
 
diff --git a/doc/7.stuff/tools/testtone.pd b/doc/7.stuff/tools/testtone.pd
index 072ee6d89..45d60e24f 100644
--- a/doc/7.stuff/tools/testtone.pd
+++ b/doc/7.stuff/tools/testtone.pd
@@ -1,4 +1,4 @@
-#N canvas 283 503 494 364 12;
+#N canvas 337 61 494 364 12;
 #X floatatom 72 273 3 0 0 0 - - -;
 #X obj 27 221 notein;
 #X obj 27 247 stripnote;
diff --git a/extra/bonk~/bonk~-help.pd b/extra/bonk~/bonk~-help.pd
deleted file mode 100644
index e52b7c506..000000000
--- a/extra/bonk~/bonk~-help.pd
+++ /dev/null
@@ -1,209 +0,0 @@
-#N canvas 43 123 1054 583 12;
-#X obj 382 492 spigot;
-#X msg 484 293 bang;
-#X obj 483 454 bonk~;
-#X msg 483 357 print;
-#X obj 435 428 adc~;
-#X msg 637 506 \; pd dsp 1;
-#X obj 300 492 spigot;
-#N canvas 366 126 604 404 synth 0;
-#X obj 112 24 r bonk-cooked;
-#X obj 112 49 unpack;
-#X obj 112 99 * 12;
-#X obj 112 124 div 7;
-#X obj 112 74 + 1;
-#X obj 112 174 mtof;
-#X obj 112 224 osc~;
-#X obj 112 249 cos~;
-#X obj 112 149 + 47;
-#X obj 209 247 line~;
-#X obj 209 272 *~;
-#X obj 209 297 lop~ 500;
-#X obj 112 274 *~;
-#X obj 103 361 dac~;
-#X obj 253 165 dbtorms;
-#X obj 253 115 * 0.5;
-#X obj 253 140 + 50;
-#X obj 211 189 f;
-#X msg 173 159 bang;
-#X obj 258 83 inlet;
-#X obj 111 307 hip~ 5;
-#X msg 34 24 0 60;
-#X obj 112 199 sig~;
-#X msg 209 222 \$1 \, 0 200;
-#X connect 0 0 1 0;
-#X connect 1 0 4 0;
-#X connect 2 0 3 0;
-#X connect 3 0 8 0;
-#X connect 4 0 2 0;
-#X connect 5 0 18 0;
-#X connect 5 0 22 0;
-#X connect 6 0 7 0;
-#X connect 7 0 12 0;
-#X connect 8 0 5 0;
-#X connect 9 0 10 0;
-#X connect 9 0 10 1;
-#X connect 10 0 11 0;
-#X connect 11 0 12 1;
-#X connect 12 0 20 0;
-#X connect 14 0 17 1;
-#X connect 15 0 16 0;
-#X connect 16 0 14 0;
-#X connect 17 0 23 0;
-#X connect 18 0 17 0;
-#X connect 19 0 15 0;
-#X connect 20 0 13 1;
-#X connect 20 0 13 0;
-#X connect 21 0 1 0;
-#X connect 22 0 6 0;
-#X connect 23 0 9 0;
-#X restore 869 523 pd synth;
-#X floatatom 869 500 0 0 0 0 - - -;
-#X msg 869 470 0;
-#X msg 900 470 90;
-#X text 625 472 click here;
-#X text 626 485 to start DSP;
-#X text 5 285 In this patch \, after starting DSP \, you can print
-out the raw or cooked output using the two "spigots" or listen to a
-synthesizer output by raising its volume.;
-#X text 770 469 output volume;
-#X text 784 487 (0-100);
-#X msg 483 138 mask 4 0.7;
-#X text 578 120 Describes how energy in each frequency band masks later
-energy in the band. Here the masking is total for 4 analysis periods
-and then drops by 0.7 each period.;
-#X text 528 286 Poll the current spectrum via "raw" outlet \, You can
-set a very high threshold if you don't want attacks mixed in.;
-#X msg 483 331 debug 0;
-#X text 561 331 turn debugging on or off.;
-#X obj 349 493 tgl 15 0 empty empty empty 0 -6 0 8 -262144 -1 -1 0
-1;
-#X obj 431 493 tgl 15 0 empty empty empty 0 -6 0 8 -262144 -1 -1 0
-1;
-#X obj 382 522 print cooked;
-#X obj 300 522 print raw;
-#X text 162 491 enable printout:;
-#X text 560 202 Minimum "velocity" to output (quieter notes are ignored.)
-;
-#X obj 485 481 s bonk-cooked;
-#X text 8 145 Bonk's two outputs are the raw spectrum of the attack
-(provided as a list of 11 numbers giving the signal "loudness" in the
-11 frequency bands used) \, and the "cooked" output which gives only
-an instrument number (counting up from zero) and a "velocity". This
-"velocity" is the sum of the square roots of the amplitudes of the
-bands \, normalized so that 100 is an attack of amplitude of about
-1 The instrument number is significant only if Bonk has a "template
-set" in memory.;
-#X text 580 35 Set low and high thresholds. Signal growth must exceed
-the high one and then fall to the low one to make an attack. The unit
-is the sum of the proportional growth in the 11 filter bands. Proportional
-growth is essentially the logarithmic time derivative.;
-#X msg 483 384 print 1;
-#X text 551 386 print out filterbank settings;
-#X text 9 33 The Bonk object takes an audio signal input and looks
-for "attacks" defined as sharp changes in the spectral envelope of
-the incoming sound. Optionally \, and less reliably \, you can have
-Bonk check the attack against a collection of stored templates to try
-to guess which of two or more instruments was hit. Bonk is described
-theoretically in the 1998 ICMC proceedings \, reprinted on crca.ucsd.edu/~msp
-.;
-#N canvas 723 241 701 719 creation-arguments 0;
-#X text 228 14 creation arguments for bonk~;
-#X text 70 272 -npts 256;
-#X text 44 244 default value:;
-#X text 70 308 -hop 128;
-#X text 70 342 -nfilters 11;
-#X text 68 380 -halftones 6;
-#X text 76 514 -overlap 1;
-#X text 79 567 -firstbin 1;
-#X text 71 454 -minbandwidth 1.5;
-#X text 122 147 All frequency parameters are specified in 'bins'. One
-bin is the sample rate divided by the window size. The minimum possible
-bandwidth is 1.5 bins. Higher bandwidths give numerically more robust
-outputs.;
-#X text 43 229 Arguments and;
-#X text 212 270 window size in points;
-#X text 210 306 analysis period ("hop size") in points;
-#X text 212 340 number of filters to use;
-#X text 212 379 desired bandwidth of filters in halftones \, effective
-in the exponentially spaced region. (At lower center frequencies the
-bandwidth is supported by the "minbandwidth" parameter below).;
-#X text 212 511 overlap factor between filters. If 1 \, the filters
-are spaced to line up at their half-power points. Other values specify
-more or fewer filters proportionally.;
-#X text 121 49 bonk~ uses a filterbank whose center frequencies are
-spaced equally at low frequencies and proportionally at high ones -
-i.e. \, they increase linearly \, then exponentially. They are determined
-by the filters' bandwidths and overlap. The bandwidths are specified
-proportionally to frequency but bounded below by a specified minimum.
-;
-#X text 210 455 minimum bandwidth in bins. If the bandwidth specified
-by "halftones" is smaller than this \, this value is used. This must
-be at least 1.5.;
-#X text 212 567 center frequency \, in bins \, of the lowest filter.
-The others are computed from this.;
-#X restore 147 414 pd creation-arguments;
-#N canvas 660 173 579 589 templates 0;
-#X msg 76 197 learn 0;
-#X msg 76 227 forget;
-#X msg 76 257 write templates.txt;
-#X msg 76 287 read templates.txt;
-#X msg 76 107 debounce 0;
-#X msg 76 137 learn 10;
-#X obj 62 431 outlet;
-#X text 155 133 Forget all templates and start learning new ones. The
-argument gives the number of times you will hit each instrument (10
-recommended.) Turn on the output volume above for audible feedback
-as you train Bonk. "Learn 0" exits learn mode.;
-#X text 155 217 Forget the last template. In Learn mode \, use "forget"
-to erase and record over a template.;
-#X text 220 253 Write templates to a file in text-editable format.
-;
-#X text 221 283 Read templates from a file.;
-#X text 157 104 Minimum time (msec) between attacks in learn mode;
-#X connect 0 0 6 0;
-#X connect 1 0 6 0;
-#X connect 2 0 6 0;
-#X connect 3 0 6 0;
-#X connect 4 0 6 0;
-#X connect 5 0 6 0;
-#X restore 500 421 pd templates;
-#X msg 483 68 thresh 2.5 5;
-#X msg 483 173 attack-frames 1;
-#X text 608 174 number of frames over which to measure growth;
-#X text 605 422 more messages for managing templates;
-#X msg 483 201 minvel 7;
-#X msg 483 228 spew 0;
-#X text 550 230 Turn spew mode on/off;
-#X msg 483 255 useloudness 0;
-#X text 597 254 experimental: use alternative loudness units;
-#X text 212 9 BONK~ - attack detection and spectral envelope measurement
-;
-#X text 734 552 Updated for Pd version 0.42;
-#X text 5 344 By default bonk's analysis is carried out on a 256-point
-window (6 msec at 44.1 kHz) and the analysis period is 128 samples.
-These and other parameters may be overridden using creation arguments
-as shown in the subpatch below:;
-#X text 552 356 Print out settings and templates.;
-#X connect 0 0 23 0;
-#X connect 1 0 2 0;
-#X connect 2 0 6 0;
-#X connect 2 1 0 0;
-#X connect 2 1 27 0;
-#X connect 3 0 2 0;
-#X connect 4 0 2 0;
-#X connect 6 0 24 0;
-#X connect 8 0 7 0;
-#X connect 9 0 8 0;
-#X connect 10 0 8 0;
-#X connect 16 0 2 0;
-#X connect 19 0 2 0;
-#X connect 21 0 6 1;
-#X connect 22 0 0 1;
-#X connect 30 0 2 0;
-#X connect 34 0 2 0;
-#X connect 35 0 2 0;
-#X connect 36 0 2 0;
-#X connect 39 0 2 0;
-#X connect 40 0 2 0;
-#X connect 42 0 2 0;
diff --git a/extra/bonk~/bonk~.c b/extra/bonk~/bonk~.c
deleted file mode 100644
index dfd5a66d6..000000000
--- a/extra/bonk~/bonk~.c
+++ /dev/null
@@ -1,1479 +0,0 @@
-/*
- ###########################################################################
- # bonk~ - a Max/MSP external
- # by miller puckette and ted apel
- # http://crca.ucsd.edu/~msp/
- # Max/MSP port by barry threw
- # http://www.barrythrew.com
- # me@barrythrew.com
- # San Francisco, CA
- # (c) 2008
- # for Kesumo - http://www.kesumo.com
- ###########################################################################
- // bonk~ detects attacks in an audio signal
- ###########################################################################
- This software is copyrighted by Miller Puckette and others.  The following
- terms (the "Standard Improved BSD License") apply to all files associated with
- the software unless explicitly disclaimed in individual files:
- 
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are
- met:
- 
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above  
- copyright notice, this list of conditions and the following 
- disclaimer in the documentation and/or other materials provided
- with the distribution.
- 3. The name of the author may not be used to endorse or promote
- products derived from this software without specific prior 
- written permission.
- 
- THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR
- 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.
- */
-
-/*
-dolist:
-decay and other times in msec 
-*/
-
-#include <math.h>
-#include <stdio.h>
-#include <string.h>
-
-#ifdef _MSC_VER
-#pragma warning (disable: 4305 4244)
-#endif
- 
-#ifdef MSP
-#include "ext.h"
-#include "z_dsp.h"
-#include "math.h"
-#include "ext_support.h"
-#include "ext_proto.h"
-#include "ext_obex.h"
-
-typedef double t_floatarg;      /* from m_pd.h */
-#define flog log
-#define fexp exp
-#define fsqrt sqrt
-#define t_resizebytes(a, b, c) t_resizebytes((char *)(a), (b), (c))
-
-void *bonk_class;
-#define getbytes t_getbytes
-#define freebytes t_freebytes
-#endif /* MSP */
-
-#ifdef PD
-#include "m_pd.h"
-static t_class *bonk_class;
-#endif
-
-#ifndef _MSC_VER
-# ifdef __MINGW32__
-/* alloca is in malloc.h in MinGW */
-#  include <malloc.h>
-# else
-#  include <alloca.h>
-# endif
-#endif
-
-/* ------------------------ bonk~ ----------------------------- */
-
-#define DEFNPOINTS 256
-#define MAXCHANNELS 8
-#define MINPOINTS 64
-#define DEFPERIOD 128
-#define DEFNFILTERS 11
-#define DEFHALFTONES 6
-#define DEFOVERLAP 1
-#define DEFFIRSTBIN 1
-#define DEFMINBANDWIDTH 1.5
-#define DEFHITHRESH 5
-#define DEFLOTHRESH 2.5
-#define DEFMASKTIME 4
-#define DEFMASKDECAY 0.7
-#define DEFDEBOUNCEDECAY 0
-#define DEFMINVEL 7
-#define DEFATTACKBINS 1
-#define MAXATTACKWAIT 4
-
-typedef struct _filterkernel
-{
-    int k_filterpoints;
-    int k_hoppoints;
-    int k_skippoints;
-    int k_nhops;
-    float k_centerfreq;          /* center frequency, bins */
-    float k_bandwidth;           /* bandwidth, bins */
-    float *k_stuff;
-} t_filterkernel;
-
-typedef struct _filterbank
-{
-    int b_nfilters;             /* number of filters in bank */
-    int b_npoints;              /* input vector size */
-    float b_halftones;          /* filter bandwidth in halftones */
-    float b_overlap;            /* overlap; default 1 for 1/2-power pts */
-    float b_firstbin;           /* freq of first filter in bins, default 1 */
-    float b_minbandwidth;       /* minimum bandwidth, default 1.5 */
-    t_filterkernel *b_vec;      /* filter kernels */
-    int b_refcount;             /* number of bonk~ objects using this */
-    struct _filterbank *b_next; /* next in linked list */
-} t_filterbank;
-
-#if 0   /* this is the design for 1.0: */
-static t_filterkernel bonk_filterkernels[] =
-    {{256, 2, .01562}, {256, 4, .01562}, {256, 6, .01562}, {180, 6, .02222},
-    {128, 6, .01803}, {90, 6, .02222}, {64, 6, .02362}, {46, 6, .02773},
-    {32, 6, .03227}, {22, 6, .03932}, {16, 6, .04489}};
-#endif
-
-#if 0
-    /* here's the 1.1 rev: */
-static t_filterkernel bonk_filterkernels[] =
-    {{256, 1, .01562, 0}, {256, 3, .01562, 0}, {256, 5, .01562, 0},
-    {212, 6, .01886, 0}, {150, 6, .01885, 0}, {106, 6, .02179, 0},
-    {76, 6, .0236, 0}, {54, 6, .02634, 0}, {38, 6, .03047, 0},
-    {26, 6, .03667, 0}, {18, 6, .04458, 0}};
-
-#define NFILTERS \
-    ((int)(sizeof(bonk_filterkernels) / sizeof(bonk_filterkernels[0])))
-
-#endif
-
-#if 0
-    /* and 1.2 */
-#define NFILTERS 11
-static t_filterkernel bonk_filterkernels[NFILTERS];
-#endif
-
-   /* and 1.3 */
-#define MAXNFILTERS 50
-#define MASKHIST 8
-
-static t_filterbank *bonk_filterbanklist;
-
-typedef struct _hist
-{
-    float h_power;
-    float h_before;
-    float h_outpower;
-    int h_countup;
-    float h_mask[MASKHIST];
-} t_hist;
-
-typedef struct template
-{
-    float t_amp[MAXNFILTERS];
-} t_template;
-
-typedef struct _insig
-{
-    t_hist g_hist[MAXNFILTERS];    /* history for each filter */
-#ifdef PD
-    t_outlet *g_outlet;         /* outlet for raw data */
-#endif
-#ifdef MSP
-    void *g_outlet;             /* outlet for raw data */
-#endif
-    float *g_inbuf;             /* buffered input samples */
-    t_float *g_invec;           /* new input samples */
-} t_insig;
-
-typedef struct _bonk
-{
-#ifdef PD
-    t_object x_obj;
-    t_outlet *x_cookedout;
-    t_clock *x_clock;
-#endif /* PD */
-#ifdef MSP
-    t_pxobject x_obj;
-    void *obex;
-    void *x_cookedout;
-    void *x_clock;
-#endif /* MSP */
-    /* parameters */
-    int x_npoints;          /* number of points in input buffer */
-    int x_period;           /* number of input samples between analyses */
-    int x_nfilters;         /* number of filters requested */
-    float x_halftones;      /* nominal halftones between filters */
-    float x_overlap;
-    float x_firstbin;
-    float x_minbandwidth;
-    float x_hithresh;       /* threshold for total growth to trigger */
-    float x_lothresh;       /* threshold for total growth to re-arm */
-    float x_minvel;         /* minimum velocity we output */
-    float x_maskdecay;
-    int x_masktime;
-    int x_useloudness;      /* use loudness spectra instead of power */
-    float x_debouncedecay;
-    float x_debouncevel;
-    double x_learndebounce; /* debounce time (in "learn" mode only) */
-    int x_attackbins;       /* number of bins to wait for attack */
-
-    t_filterbank *x_filterbank;
-    t_hist x_hist[MAXNFILTERS];
-    t_template *x_template;
-    t_insig *x_insig;                   
-    int x_ninsig;
-    int x_ntemplate;
-    int x_infill;
-    int x_countdown;
-    int x_willattack;
-    int x_attacked;
-    int x_debug;
-    int x_learn;
-    int x_learncount;           /* countup for "learn" mode */
-    int x_spew;                 /* if true, always generate output! */
-    int x_maskphase;            /* phase, 0 to MASKHIST-1, for mask history */
-    float x_sr;                 /* current sample rate in Hz. */
-    int x_hit;                  /* next "tick" called because of a hit, not a poll */
-} t_bonk;
-
-#ifdef MSP
-static void *bonk_new(t_symbol *s, long ac, t_atom *av);
-static void bonk_tick(t_bonk *x);
-static void bonk_doit(t_bonk *x);
-static t_int *bonk_perform(t_int *w);
-static void bonk_dsp(t_bonk *x, t_signal **sp);
-void bonk_assist(t_bonk *x, void *b, long m, long a, char *s);
-static void bonk_free(t_bonk *x);
-void bonk_setup(void);
-int main();
-
-static void bonk_thresh(t_bonk *x, t_floatarg f1, t_floatarg f2);
-static void bonk_print(t_bonk *x, t_floatarg f);
-static void bonk_bang(t_bonk *x);
-
-static void bonk_write(t_bonk *x, t_symbol *s);
-static void bonk_read(t_bonk *x, t_symbol *s);
-
-void bonk_minvel_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_lothresh_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_hithresh_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_masktime_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_maskdecay_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_debouncedecay_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_debug_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_spew_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_useloudness_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_attackbins_set(t_bonk *x, void *attr, long ac, t_atom *av);
-void bonk_learn_set(t_bonk *x, void *attr, long ac, t_atom *av);
-
-float qrsqrt(float f);
-double clock_getsystime();
-double clock_gettimesince(double prevsystime);
-char *strcpy(char *s1, const char *s2);
-#endif
-
-static void bonk_tick(t_bonk *x);
-
-#define HALFWIDTH 0.75  /* half peak bandwidth at half power point in bins */
-#define SLIDE 0.25    /* relative slide between filter subwindows */
-
-static t_filterbank *bonk_newfilterbank(int npoints, int nfilters,
-    float halftones, float overlap, float firstbin, float minbandwidth)
-{
-    int i, j;
-    float cf, bw, h, relspace;
-    t_filterbank *b = (t_filterbank *)getbytes(sizeof(*b));
-    b->b_npoints = npoints;
-    b->b_nfilters = nfilters;
-    b->b_halftones = halftones;
-    b->b_overlap = overlap;
-    b->b_firstbin = firstbin;
-    b->b_minbandwidth = minbandwidth;
-    b->b_refcount = 0;
-    b->b_next = bonk_filterbanklist;
-    bonk_filterbanklist = b;
-    b->b_vec = (t_filterkernel *)getbytes(nfilters * sizeof(*b->b_vec));
-    
-    h = exp((log(2.)/12.)*halftones);  /* specced interval between filters */
-    relspace = (h - 1)/(h + 1);        /* nominal spacing-per-f for fbank */
-    
-    if (minbandwidth < 2*HALFWIDTH)
-        minbandwidth = 2*HALFWIDTH;
-    if (firstbin < minbandwidth/(2*HALFWIDTH))
-        firstbin = minbandwidth/(2*HALFWIDTH);
-    cf = firstbin;
-    bw = cf * relspace * overlap;
-    if (bw < (0.5*minbandwidth))
-        bw = (0.5*minbandwidth);
-    for (i = 0; i < nfilters; i++)
-    {
-        float *fp, newcf, newbw;
-        float normalizer = 0;
-        int filterpoints, skippoints, hoppoints, nhops;
-        
-        filterpoints = npoints * HALFWIDTH/bw;
-        if (cf > npoints/2)
-        {
-            post("bonk~: only using %d filters (ran past Nyquist)", i+1);
-            break;
-        }
-        if (filterpoints < 4)
-        {
-            post("bonk~: only using %d filters (kernels got too short)", i+1);
-            break;
-        }
-        else if (filterpoints > npoints)
-            filterpoints = npoints;
-        
-        hoppoints = SLIDE * npoints * HALFWIDTH/bw;
-        
-        nhops = 1. + (npoints-filterpoints)/(float)hoppoints;
-        skippoints = 0.5 * (npoints-filterpoints - (nhops-1) * hoppoints);
-        
-        b->b_vec[i].k_stuff =
-            (float *)getbytes(2 * sizeof(float) * filterpoints);
-        b->b_vec[i].k_filterpoints = filterpoints;
-        b->b_vec[i].k_nhops = nhops;
-        b->b_vec[i].k_hoppoints = hoppoints;
-        b->b_vec[i].k_skippoints = skippoints;
-        b->b_vec[i].k_centerfreq = cf;
-        b->b_vec[i].k_bandwidth = bw;
-        
-        for (fp = b->b_vec[i].k_stuff, j = 0; j < filterpoints; j++, fp+= 2)
-        {
-            float phase = j * cf * (2*3.14159/ npoints);
-            float wphase = j * (2*3.14159 / filterpoints);
-            float window = sin(0.5*wphase);
-            fp[0] = window * cos(phase);
-            fp[1] = window * sin(phase);
-            normalizer += window;
-        }
-        normalizer = 1/(normalizer * sqrt(nhops));
-        for (fp = b->b_vec[i].k_stuff, j = 0;
-             j < filterpoints; j++, fp+= 2)
-            fp[0] *= normalizer, fp[1] *= normalizer;
-#if 0
-        post("i %d  cf %.2f  bw %.2f  nhops %d, hop %d, skip %d, npoints %d",
-             i, cf, bw, nhops, hoppoints, skippoints, filterpoints);
-#endif
-        newcf = (cf + bw/overlap)/(1 - relspace);
-        newbw = newcf * overlap * relspace;
-        if (newbw < 0.5*minbandwidth)
-        {
-            newbw = 0.5*minbandwidth;
-            newcf = cf + minbandwidth / overlap;
-        }
-        cf = newcf;
-        bw = newbw;
-    }
-    for (; i < nfilters; i++)
-        b->b_vec[i].k_stuff = 0, b->b_vec[i].k_filterpoints = 0;
-    return (b);
-}
-
-static void bonk_freefilterbank(t_filterbank *b)
-{
-    t_filterbank *b2, *b3;
-    int i;
-    if (bonk_filterbanklist == b)
-        bonk_filterbanklist = b->b_next;
-    else for (b2 = bonk_filterbanklist; b3 = b2->b_next; b2 = b3)
-        if (b3 == b)
-    {
-        b2->b_next = b3->b_next;
-        break;
-    }
-    for (i = 0; i < b->b_nfilters; i++)
-        if (b->b_vec[i].k_stuff)
-            freebytes(b->b_vec[i].k_stuff,
-                b->b_vec[i].k_filterpoints * sizeof(float));
-    freebytes(b, sizeof(*b));
-}
-
-static void bonk_donew(t_bonk *x, int npoints, int period, int nsig, 
-    int nfilters, float halftones, float overlap, float firstbin,
-    float minbandwidth, float samplerate)
-{
-    int i, j;
-    t_hist *h;
-    float *fp;
-    t_insig *g;
-    t_filterbank *fb;
-    for (j = 0, g = x->x_insig; j < nsig; j++, g++)
-    {
-        for (i = 0, h = g->g_hist; i--; h++)
-        {
-            h->h_power = h->h_before = 0, h->h_countup = 0;
-            for (j = 0; j < MASKHIST; j++)
-                h->h_mask[j] = 0;
-        }
-            /* we ought to check for failure to allocate memory here */
-        g->g_inbuf = (float *)getbytes(npoints * sizeof(float));
-        for (i = npoints, fp = g->g_inbuf; i--; fp++) *fp = 0;
-    }
-    if (!period) period = npoints/2;
-    x->x_npoints = npoints;
-    x->x_period = period;
-    x->x_ninsig = nsig;
-    x->x_nfilters = nfilters;
-    x->x_halftones = halftones;
-    x->x_template = (t_template *)getbytes(0);
-    x->x_ntemplate = 0;
-    x->x_infill = 0;
-    x->x_countdown = 0;
-    x->x_willattack = 0;
-    x->x_attacked = 0;
-    x->x_maskphase = 0;
-    x->x_debug = 0;
-    x->x_hithresh = DEFHITHRESH;
-    x->x_lothresh = DEFLOTHRESH;
-    x->x_masktime = DEFMASKTIME;
-    x->x_maskdecay = DEFMASKDECAY;
-    x->x_learn = 0;
-    x->x_learndebounce = clock_getsystime();
-    x->x_learncount = 0;
-    x->x_debouncedecay = DEFDEBOUNCEDECAY;
-    x->x_minvel = DEFMINVEL;
-    x->x_useloudness = 0;
-    x->x_debouncevel = 0;
-    x->x_attackbins = DEFATTACKBINS;
-    x->x_sr = samplerate;
-    x->x_filterbank = 0;
-    x->x_hit = 0;
-    for (fb = bonk_filterbanklist; fb; fb = fb->b_next)
-        if (fb->b_nfilters == x->x_nfilters &&
-            fb->b_halftones == x->x_halftones &&
-            fb->b_firstbin == firstbin &&
-            fb->b_overlap == overlap &&
-            fb->b_npoints == x->x_npoints &&
-            fb->b_minbandwidth == minbandwidth)
-    {
-        fb->b_refcount++;
-        x->x_filterbank = fb;
-        break;
-    }
-    if (!x->x_filterbank)
-        x->x_filterbank = bonk_newfilterbank(npoints, nfilters, 
-            halftones, overlap, firstbin, minbandwidth),
-                x->x_filterbank->b_refcount++;
-}
-
-static void bonk_tick(t_bonk *x)
-{
-    t_atom at[MAXNFILTERS], *ap, at2[3];
-    int i, j, k, n;
-    t_hist *h;
-    float *pp, vel = 0, temperature = 0;
-    float *fp;
-    t_template *tp;
-    int nfit, ninsig = x->x_ninsig, ntemplate = x->x_ntemplate, nfilters = x->x_nfilters;
-    t_insig *gp;
-#ifdef _MSC_VER
-    float powerout[MAXNFILTERS*MAXCHANNELS];
-#else
-    float *powerout = alloca(x->x_nfilters * x->x_ninsig * sizeof(*powerout));
-#endif
-    
-    for (i = ninsig, pp = powerout, gp = x->x_insig; i--; gp++)
-    {
-        for (j = 0, h = gp->g_hist; j < nfilters; j++, h++, pp++)
-        {
-            float power = h->h_outpower;
-            float intensity = *pp = (power > 0 ? 100. * qrsqrt(qrsqrt(power)) : 0);
-            vel += intensity;
-            temperature += intensity * (float)j;
-        }
-    }
-    if (vel > 0) temperature /= vel;
-    else temperature = 0;
-    vel *= 0.5 / ninsig;        /* fudge factor */
-    if (x->x_hit)
-    {
-        /* if hit nonzero it's a clock callback.  if in "learn" mode update the
-         template list; in any event match the hit to known templates. */
-        
-        if (vel < x->x_debouncevel)
-        {
-            if (x->x_debug)
-                post("bounce cancelled: vel %f debounce %f",
-                     vel, x->x_debouncevel);
-            return;
-        }
-        if (vel < x->x_minvel)
-        {
-            if (x->x_debug)
-                post("low velocity cancelled: vel %f, minvel %f",
-                     vel, x->x_minvel);
-            return;
-        }
-        x->x_debouncevel = vel;
-        if (x->x_learn)
-        {
-            double lasttime = x->x_learndebounce;
-            double msec = clock_gettimesince(lasttime);
-            if ((!ntemplate) || (msec > 200))
-            {
-                int countup = x->x_learncount;
-                /* normalize to 100  */
-                float norm;
-                for (i = nfilters * ninsig, norm = 0, pp = powerout; i--; pp++)
-                    norm += *pp * *pp;
-                if (norm < 1.0e-15) norm = 1.0e-15;
-                norm = 100.f * qrsqrt(norm);
-                /* check if this is the first strike for a new template */
-                if (!countup)
-                {
-                    int oldn = ntemplate;
-                    x->x_ntemplate = ntemplate = oldn + ninsig;
-                    x->x_template = (t_template *)t_resizebytes(x->x_template,
-                        oldn * sizeof(x->x_template[0]),
-                            ntemplate * sizeof(x->x_template[0]));
-                    for (i = ninsig, pp = powerout; i--; oldn++)
-                        for (j = nfilters, fp = x->x_template[oldn].t_amp; j--;
-                             pp++, fp++)
-                                *fp = *pp * norm;
-                }
-                else
-                {
-                    int oldn = ntemplate - ninsig;
-                    if (oldn < 0) post("bonk_tick bug");
-                    for (i = ninsig, pp = powerout; i--; oldn++)
-                    {
-                        for (j = nfilters, fp = x->x_template[oldn].t_amp; j--;
-                             pp++, fp++)
-                            *fp = (countup * *fp + *pp * norm)
-                            /(countup + 1.0f);
-                    }
-                }
-                countup++;
-                if (countup == x->x_learn) countup = 0;
-                x->x_learncount = countup;
-            }
-            else return;
-        }
-        x->x_learndebounce = clock_getsystime();
-        if (ntemplate)
-        {
-            float bestfit = -1e30;
-            int templatecount;
-            nfit = -1;
-            for (i = 0, templatecount = 0, tp = x->x_template; 
-                 templatecount < ntemplate; i++)
-            {
-                float dotprod = 0;
-                for (k = 0, pp = powerout;
-                     k < ninsig && templatecount < ntemplate;
-                     k++, tp++, templatecount++)
-                {
-                    for (j = nfilters, fp = tp->t_amp;
-                         j--; fp++, pp++)
-                    {
-                        if (*fp < 0 || *pp < 0) post("bonk_tick bug 2");
-                        dotprod += *fp * *pp;
-                    }
-                }
-                if (dotprod > bestfit)
-                {
-                    bestfit = dotprod;
-                    nfit = i;
-                }
-            }
-            if (nfit < 0) post("bonk_tick bug");
-        }
-        else nfit = 0;
-    }
-    else nfit = -1;     /* hit is zero; this is the "bang" method. */
-    
-    x->x_attacked = 1;
-    if (x->x_debug)
-        post("bonk out: number %d, vel %f, temperature %f",
-            nfit, vel, temperature);
-    
-    SETFLOAT(at2, nfit);
-    SETFLOAT(at2+1, vel);
-    SETFLOAT(at2+2, temperature);
-    outlet_list(x->x_cookedout, 0, 3, at2);
-    
-    for (n = 0, gp = x->x_insig + (ninsig-1),
-        pp = powerout + nfilters * (ninsig-1); n < ninsig;
-            n++, gp--, pp -= nfilters)
-    {
-        float *pp2;
-        for (i = 0, ap = at, pp2 = pp; i < nfilters;
-            i++, ap++, pp2++)
-        {
-            ap->a_type = A_FLOAT;
-            ap->a_w.w_float = *pp2;
-        }
-        outlet_list(gp->g_outlet, 0, nfilters, at);
-    }
-}
-
-static void bonk_doit(t_bonk *x)
-{
-    int i, j, ch, n;
-    t_filterkernel *k;
-    t_hist *h;
-    float growth = 0, *fp1, *fp3, *fp4, hithresh, lothresh;
-    int ninsig = x->x_ninsig, nfilters = x->x_nfilters,
-        maskphase = x->x_maskphase, nextphase, oldmaskphase;
-    t_insig *gp;
-    nextphase = maskphase + 1;
-    if (nextphase >= MASKHIST)
-        nextphase = 0;
-    x->x_maskphase = nextphase;
-    oldmaskphase = nextphase - x->x_attackbins;
-    if (oldmaskphase < 0)
-        oldmaskphase += MASKHIST;
-    if (x->x_useloudness)
-        hithresh = qrsqrt(qrsqrt(x->x_hithresh)),
-        lothresh = qrsqrt(qrsqrt(x->x_lothresh));
-    else hithresh = x->x_hithresh, lothresh = x->x_lothresh;
-    for (ch = 0, gp = x->x_insig; ch < ninsig; ch++, gp++)
-    {
-        for (i = 0, k = x->x_filterbank->b_vec, h = gp->g_hist;
-             i < nfilters; i++, k++, h++)
-        {
-            float power = 0, maskpow = h->h_mask[maskphase];
-            float *inbuf= gp->g_inbuf + k->k_skippoints;
-            int countup = h->h_countup;
-            int filterpoints = k->k_filterpoints;
-            /* if the user asked for more filters that fit under the
-             Nyquist frequency, some filters won't actually be filled in
-             so we skip running them. */
-            if  (!filterpoints)
-            {
-                h->h_countup = 0;
-                h->h_mask[nextphase] = 0;
-                h->h_power = 0;
-                continue;
-            }
-            /* run the filter repeatedly, sliding it forward by hoppoints,
-             for nhop times */
-            for (fp1 = inbuf, n = 0;
-                 n < k->k_nhops; fp1 += k->k_hoppoints, n++)
-            {
-                float rsum = 0, isum = 0;
-                for (fp3 = fp1, fp4 = k->k_stuff, j = filterpoints; j--;)
-                {
-                    float g = *fp3++;
-                    rsum += g * *fp4++;
-                    isum += g * *fp4++;
-                }
-                power += rsum * rsum + isum * isum;
-            }
-            if (!x->x_willattack) 
-                h->h_before = maskpow;
-            
-            if (power > h->h_mask[oldmaskphase])
-            {
-                if (x->x_useloudness)
-                    growth += qrsqrt(qrsqrt(
-                        power/(h->h_mask[oldmaskphase] + 1.0e-15))) - 1.f;
-                else growth += power/(h->h_mask[oldmaskphase] + 1.0e-15) - 1.f;
-            }
-            if (!x->x_willattack && countup >= x->x_masktime)
-                maskpow *= x->x_maskdecay;
-            
-            if (power > maskpow)
-            {
-                maskpow = power;
-                countup = 0;
-            }
-            countup++;
-            h->h_countup = countup;
-            h->h_mask[nextphase] = maskpow;
-            h->h_power = power;
-        }
-    }
-    if (x->x_willattack)
-    {
-        if (x->x_willattack > MAXATTACKWAIT || growth < x->x_lothresh)
-        {
-            /* if haven't yet, and if not in spew mode, report a hit */
-            if (!x->x_spew && !x->x_attacked)
-            {
-                for (ch = 0, gp = x->x_insig; ch < ninsig; ch++, gp++)
-                    for (i = nfilters, h = gp->g_hist; i--; h++)
-                        h->h_outpower = h->h_mask[nextphase];
-                x->x_hit = 1;
-                clock_delay(x->x_clock, 0);
-            }
-        }
-        if (growth < x->x_lothresh)
-            x->x_willattack = 0;
-        else x->x_willattack++;
-    }
-    else if (growth > x->x_hithresh)
-    {
-        if (x->x_debug) post("attack: growth = %f", growth);
-        x->x_willattack = 1;
-        x->x_attacked = 0;
-        for (ch = 0, gp = x->x_insig; ch < ninsig; ch++, gp++)
-            for (i = nfilters, h = gp->g_hist; i--; h++)
-                h->h_mask[nextphase] = h->h_power, h->h_countup = 0;
-    }
-    
-    /* if in "spew" mode just always output */
-    if (x->x_spew)
-    {
-        for (ch = 0, gp = x->x_insig; ch < ninsig; ch++, gp++)
-            for (i = nfilters, h = gp->g_hist; i--; h++)
-                h->h_outpower = h->h_power;
-        x->x_hit = 0;
-        clock_delay(x->x_clock, 0);
-    }
-    x->x_debouncevel *= x->x_debouncedecay;
-}
-
-static t_int *bonk_perform(t_int *w)
-{
-    t_bonk *x = (t_bonk *)(w[1]);
-    int n = (int)(w[2]);
-    int onset = 0;
-    if (x->x_countdown >= n)
-        x->x_countdown -= n;
-    else
-    {
-        int i, j, ninsig = x->x_ninsig;
-        t_insig *gp;
-        if (x->x_countdown > 0)
-        {
-            n -= x->x_countdown;
-            onset += x->x_countdown;
-            x->x_countdown = 0;
-        }
-        while (n > 0)
-        {
-            int infill = x->x_infill;
-            int m = (n < (x->x_npoints - infill) ?
-                     n : (x->x_npoints - infill));
-            for (i = 0, gp = x->x_insig; i < ninsig; i++, gp++)
-            {
-                float *fp = gp->g_inbuf + infill;
-                t_float *in1 = gp->g_invec + onset;
-                for (j = 0; j < m; j++)
-                    *fp++ = *in1++;
-            }
-            infill += m;
-            x->x_infill = infill;   
-            if (infill == x->x_npoints)
-            {
-                bonk_doit(x);
-                
-                /* shift or clear the input buffer and update counters */
-                if (x->x_period > x->x_npoints)
-                    x->x_countdown = x->x_period - x->x_npoints;
-                else x->x_countdown = 0;
-                if (x->x_period < x->x_npoints)
-                {
-                    int overlap = x->x_npoints - x->x_period;
-                    float *fp1, *fp2;
-                    for (n = 0, gp = x->x_insig; n < ninsig; n++, gp++)
-                        for (i = overlap, fp1 = gp->g_inbuf,
-                             fp2 = fp1 + x->x_period; i--;)
-                                *fp1++ = *fp2++;
-                    x->x_infill = overlap;
-                }
-                else x->x_infill = 0;
-            }
-            n -= m;
-            onset += m;
-        }
-    }
-    return (w+3);
-}
-
-static void bonk_dsp(t_bonk *x, t_signal **sp)
-{
-    int i, n = sp[0]->s_n, ninsig = x->x_ninsig;
-    t_insig *gp;
-    
-    x->x_sr = sp[0]->s_sr;
-    
-    for (i = 0, gp = x->x_insig; i < ninsig; i++, gp++)
-        gp->g_invec = (*(sp++))->s_vec;
-    
-    dsp_add(bonk_perform, 2, x, n);
-}
-
-static void bonk_thresh(t_bonk *x, t_floatarg f1, t_floatarg f2)
-{
-    if (f1 > f2)
-        post("bonk: warning: low threshold greater than hi threshold");
-    x->x_lothresh = (f1 <= 0 ? 0.0001 : f1);
-    x->x_hithresh = (f2 <= 0 ? 0.0001 : f2);
-}
-
-#ifdef PD
-static void bonk_mask(t_bonk *x, t_floatarg f1, t_floatarg f2)
-{
-    int ticks = f1;
-    if (ticks < 0) ticks = 0;
-    if (f2 < 0) f2 = 0;
-    else if (f2 > 1) f2 = 1;
-    x->x_masktime = ticks;
-    x->x_maskdecay = f2;
-}
-
-static void bonk_debounce(t_bonk *x, t_floatarg f1)
-{
-    if (f1 < 0) f1 = 0;
-    else if (f1 > 1) f1 = 1;
-    x->x_debouncedecay = f1;
-}
-
-static void bonk_minvel(t_bonk *x, t_floatarg f)
-{
-    if (f < 0) f = 0; 
-    x->x_minvel = f;
-}
-
-static void bonk_debug(t_bonk *x, t_floatarg f)
-{
-    x->x_debug = (f != 0);
-}
-
-static void bonk_spew(t_bonk *x, t_floatarg f)
-{
-    x->x_spew = (f != 0);
-}
-
-static void bonk_useloudness(t_bonk *x, t_floatarg f)
-{
-    x->x_useloudness = (f != 0);
-}
-
-static void bonk_attackbins(t_bonk *x, t_floatarg f)
-{
-    if (f < 1)
-        f = 1;
-    else if (f > MASKHIST)
-        f = MASKHIST;
-    x->x_attackbins = f;
-}
-
-static void bonk_learn(t_bonk *x, t_floatarg f)
-{
-    int n = f;
-    if (n < 0) n = 0;
-    if (n)
-    {
-        x->x_template = (t_template *)t_resizebytes(x->x_template,
-            x->x_ntemplate * sizeof(x->x_template[0]), 0);
-        x->x_ntemplate = 0;
-    }
-    x->x_learn = n;
-    x->x_learncount = 0;
-}
-#endif
-
-static void bonk_print(t_bonk *x, t_floatarg f)
-{
-    int i;
-    post("thresh %f %f", x->x_lothresh, x->x_hithresh);
-    post("mask %d %f", x->x_masktime, x->x_maskdecay);
-    post("attack-frames %d", x->x_attackbins);
-    post("debounce %f", x->x_debouncedecay);
-    post("minvel %f", x->x_minvel);
-    post("spew %d", x->x_spew);
-    post("useloudness %d", x->x_useloudness);
-    
-#if 0       /* LATER rewrite without hard-coded 11 filters */
-    if (x->x_ntemplate)
-    {
-        post("templates:");
-        for (i = 0; i < x->x_ntemplate; i++)
-            post(
-"%2d %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f",
-                i,
-                x->x_template[i].t_amp[0],
-                x->x_template[i].t_amp[1],
-                x->x_template[i].t_amp[2],
-                x->x_template[i].t_amp[3],
-                x->x_template[i].t_amp[4],
-                x->x_template[i].t_amp[5],
-                x->x_template[i].t_amp[6],
-                x->x_template[i].t_amp[7],
-                x->x_template[i].t_amp[8],
-                x->x_template[i].t_amp[9],
-                x->x_template[i].t_amp[10]);
-    }
-    else post("no templates");
-#endif
-    post("number of templates %d", x->x_ntemplate);
-    if (x->x_learn) post("learn mode");
-    if (f != 0)
-    {
-        int j, ninsig = x->x_ninsig;
-        t_insig *gp;
-        for (j = 0, gp = x->x_insig; j < ninsig; j++, gp++)
-        {
-            t_hist *h;
-            if (ninsig > 1) post("input %d:", j+1);
-            for (i = x->x_nfilters, h = gp->g_hist; i--; h++)
-                post("pow %f mask %f before %f count %d",
-                     h->h_power, h->h_mask[x->x_maskphase],
-                     h->h_before, h->h_countup);
-        }
-        post("filter details (frequencies are in units of %.2f-Hz. bins):",
-             x->x_sr/x->x_npoints);
-        for (j = 0; j < x->x_nfilters; j++)
-            post("%2d  cf %.2f  bw %.2f  nhops %d hop %d skip %d npoints %d",
-                 j, 
-                 x->x_filterbank->b_vec[j].k_centerfreq,
-                 x->x_filterbank->b_vec[j].k_bandwidth,
-                 x->x_filterbank->b_vec[j].k_nhops,
-                 x->x_filterbank->b_vec[j].k_hoppoints,
-                 x->x_filterbank->b_vec[j].k_skippoints,
-                 x->x_filterbank->b_vec[j].k_filterpoints);
-    }
-    if (x->x_debug) post("debug mode");
-}
-
-static void bonk_forget(t_bonk *x)
-{
-    int ntemplate = x->x_ntemplate, newn = ntemplate - x->x_ninsig;
-    if (newn < 0) newn = 0;
-    x->x_template = (t_template *)t_resizebytes(x->x_template,
-        x->x_ntemplate * sizeof(x->x_template[0]),
-            newn * sizeof(x->x_template[0]));
-    x->x_ntemplate = newn;
-    x->x_learncount = 0;
-}
-
-static void bonk_bang(t_bonk *x)
-{
-    int i, ch;
-    t_insig *gp;
-    x->x_hit = 0;
-    for (ch = 0, gp = x->x_insig; ch < x->x_ninsig; ch++, gp++)
-    {
-        t_hist *h;
-        for (i = 0, h = gp->g_hist; i < x->x_nfilters; i++, h++)
-            h->h_outpower = h->h_power;
-    }
-    bonk_tick(x);
-}
-
-static void bonk_read(t_bonk *x, t_symbol *s)
-{
-    FILE *fd = fopen(s->s_name, "r");
-    float vec[MAXNFILTERS];
-    int i, ntemplate = 0, remaining;
-    float *fp, *fp2;
-    if (!fd)
-    {
-        post("%s: open failed", s->s_name);
-        return;
-    }
-    x->x_template = (t_template *)t_resizebytes(x->x_template, 
-        x->x_ntemplate * sizeof(t_template), 0);
-    while (1)
-    {
-        for (i = x->x_nfilters, fp = vec; i--; fp++)
-            if (fscanf(fd, "%f", fp) < 1) goto nomore;
-        x->x_template = (t_template *)t_resizebytes(x->x_template,
-            ntemplate * sizeof(t_template),
-                (ntemplate + 1) * sizeof(t_template));
-        for (i = x->x_nfilters, fp = vec,
-             fp2 = x->x_template[ntemplate].t_amp; i--;)
-            *fp2++ = *fp++;
-        ntemplate++;
-    }
-nomore:
-    if (remaining = (ntemplate % x->x_ninsig))
-    {
-        post("bonk_read: %d templates not a multiple of %d; dropping extras");
-        x->x_template = (t_template *)t_resizebytes(x->x_template,
-            ntemplate * sizeof(t_template),
-                (ntemplate - remaining) * sizeof(t_template));
-        ntemplate = ntemplate - remaining;
-    }
-    post("bonk: read %d templates\n", ntemplate);
-    x->x_ntemplate = ntemplate;
-    fclose(fd);
-}
-
-static void bonk_write(t_bonk *x, t_symbol *s)
-{
-    FILE *fd = fopen(s->s_name, "w");
-    int i, ntemplate = x->x_ntemplate;
-    t_template *tp = x->x_template;
-    float *fp;
-    if (!fd)
-    {
-        post("%s: couldn't create", s->s_name);
-        return;
-    }
-    for (; ntemplate--; tp++)
-    {
-        for (i = x->x_nfilters, fp = tp->t_amp; i--; fp++)
-            fprintf(fd, "%6.2f ", *fp);
-        fprintf(fd, "\n");
-    }
-    post("bonk: wrote %d templates\n", x->x_ntemplate);
-    fclose(fd);
-}
-
-static void bonk_free(t_bonk *x)
-{
-    
-    int i, ninsig = x->x_ninsig;
-    t_insig *gp = x->x_insig;
-#ifdef MSP
-    dsp_free((t_pxobject *)x);
-#endif
-    for (i = 0, gp = x->x_insig; i < ninsig; i++, gp++)
-        freebytes(gp->g_inbuf, x->x_npoints * sizeof(float));
-    clock_free(x->x_clock);
-    if (!--(x->x_filterbank->b_refcount))
-        bonk_freefilterbank(x->x_filterbank);
-    
-}
-
-/* -------------------------- Pd glue ------------------------- */
-#ifdef PD
-
-static void *bonk_new(t_symbol *s, int argc, t_atom *argv)
-{
-    t_bonk *x = (t_bonk *)pd_new(bonk_class);
-    int nsig = 1, period = DEFPERIOD, npts = DEFNPOINTS,
-        nfilters = DEFNFILTERS, j;
-    float halftones = DEFHALFTONES, overlap = DEFOVERLAP,
-        firstbin = DEFFIRSTBIN, minbandwidth = DEFMINBANDWIDTH;
-    t_insig *g;
-
-    if (argc > 0 && argv[0].a_type == A_FLOAT)
-    {
-            /* old style args for compatibility */
-        period = atom_getfloatarg(0, argc, argv);
-        nsig = atom_getfloatarg(1, argc, argv);
-    }
-    else while (argc > 0)
-    {
-        t_symbol *firstarg = atom_getsymbolarg(0, argc, argv);
-        if (!strcmp(firstarg->s_name, "-npts") && argc > 1)
-        {
-            npts = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-hop") && argc > 1)
-        {
-            period = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-nsigs") && argc > 1)
-        {
-            nsig = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-nfilters") && argc > 1)
-        {
-            nfilters = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-halftones") && argc > 1)
-        {
-            halftones = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-overlap") && argc > 1)
-        {
-            overlap = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-firstbin") && argc > 1)
-        {
-            firstbin = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-minbandwidth") && argc > 1)
-        {
-            minbandwidth = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-spew") && argc > 1)
-        {
-            x->x_spew = (atom_getfloatarg(1, argc, argv) != 0);
-            argc -= 2; argv += 2;
-        }
-        else
-        {
-            pd_error(x,
-"usage is: bonk [-npts #] [-hop #] [-nsigs #] [-nfilters #] [-halftones #]"); 
-            post(
-"... [-overlap #] [-firstbin #] [-spew #]");
-            argc = 0;
-        }
-    }
-
-    x->x_npoints = (npts >= MINPOINTS ? npts : DEFNPOINTS);
-    x->x_period = (period >= 1 ? period : npts/2);
-    x->x_nfilters = (nfilters >= 1 ? nfilters : DEFNFILTERS);
-    if (halftones < 0.01)
-        halftones = DEFHALFTONES;
-    else if (halftones > 12)
-        halftones = 12;
-    if (nsig < 1)
-        nsig = 1;
-    else if (nsig > MAXCHANNELS)
-        nsig = MAXCHANNELS;
-    if (firstbin < 0.5)
-        firstbin = 0.5;
-    if (overlap < 1)
-        overlap = 1;
-
-    x->x_clock = clock_new(x, (t_method)bonk_tick);
-    x->x_insig = (t_insig *)getbytes(nsig * sizeof(*x->x_insig));
-    for (j = 0, g = x->x_insig; j < nsig; j++, g++)
-    {
-        g->g_outlet = outlet_new(&x->x_obj, gensym("list"));
-        if (j)
-            inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
-    }
-    x->x_cookedout = outlet_new(&x->x_obj, gensym("list"));
-    bonk_donew(x, npts, period, nsig, nfilters, halftones, overlap,
-        firstbin, minbandwidth, sys_getsr());
-    return (x);
-}
-
-void bonk_tilde_setup(void)
-{
-    bonk_class = class_new(gensym("bonk~"), (t_newmethod)bonk_new,
-        (t_method)bonk_free, sizeof(t_bonk), 0, A_GIMME, 0);
-    class_addmethod(bonk_class, nullfn, gensym("signal"), 0);
-    class_addmethod(bonk_class, (t_method)bonk_dsp, gensym("dsp"), 0);
-    class_addbang(bonk_class, bonk_bang);
-    class_addmethod(bonk_class, (t_method)bonk_learn,
-        gensym("learn"), A_FLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_forget, gensym("forget"), 0);
-    class_addmethod(bonk_class, (t_method)bonk_thresh,
-        gensym("thresh"), A_FLOAT, A_FLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_mask,
-        gensym("mask"), A_FLOAT, A_FLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_debounce,
-        gensym("debounce"), A_FLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_minvel,
-        gensym("minvel"), A_FLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_print,
-        gensym("print"), A_DEFFLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_debug,
-        gensym("debug"), A_DEFFLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_spew,
-        gensym("spew"), A_DEFFLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_useloudness,
-        gensym("useloudness"), A_DEFFLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_attackbins,
-        gensym("attack-bins"), A_DEFFLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_attackbins,
-        gensym("attack-frames"), A_DEFFLOAT, 0);
-    class_addmethod(bonk_class, (t_method)bonk_read,
-        gensym("read"), A_SYMBOL, 0);
-    class_addmethod(bonk_class, (t_method)bonk_write,
-        gensym("write"), A_SYMBOL, 0);
-    post("bonk version 1.3");
-}
-#endif
-
-/* -------------------------- MSP glue ------------------------- */
-#ifdef MSP
-
-int main()
-{       
-        t_class *c;
-        t_object *attr;
-        long attrflags = 0;
-        t_symbol *sym_long = gensym("long"), *sym_float32 = gensym("float32");
-        
-        c = class_new("bonk~", (method)bonk_new, (method)bonk_free, sizeof(t_bonk), (method)0L, A_GIMME, 0);
-        
-        class_obexoffset_set(c, calcoffset(t_bonk, obex));
-        
-        attr = attr_offset_new("npoints", sym_long, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_npoints));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("hop", sym_long, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_period));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("nfilters", sym_long, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_nfilters));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("halftones", sym_float32, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_halftones));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("overlap", sym_float32, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_overlap));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("firstbin", sym_float32, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_firstbin));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("minbandwidth", sym_float32, attrflags, (method)0L, (method)0L, calcoffset(t_bonk, x_minbandwidth));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("minvel", sym_float32, attrflags, (method)0L, (method)bonk_minvel_set, calcoffset(t_bonk, x_minvel));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("lothresh", sym_float32, attrflags, (method)0L, (method)bonk_lothresh_set, calcoffset(t_bonk, x_lothresh));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("hithresh", sym_float32, attrflags, (method)0L, (method)bonk_hithresh_set, calcoffset(t_bonk, x_hithresh));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("masktime", sym_long, attrflags, (method)0L, (method)bonk_masktime_set, calcoffset(t_bonk, x_masktime));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("maskdecay", sym_float32, attrflags, (method)0L, (method)bonk_maskdecay_set, calcoffset(t_bonk, x_maskdecay));
-        class_addattr(c, attr);
-    
-        attr = attr_offset_new("debouncedecay", sym_float32, attrflags, (method)0L, (method)bonk_debouncedecay_set, calcoffset(t_bonk, x_debouncedecay));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("debug", sym_long, attrflags, (method)0L, (method)bonk_debug_set, calcoffset(t_bonk, x_debug));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("spew", sym_long, attrflags, (method)0L, (method)bonk_spew_set, calcoffset(t_bonk, x_spew));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("useloudness", sym_long, attrflags, (method)0L, (method)bonk_useloudness_set, calcoffset(t_bonk, x_useloudness));
-        class_addattr(c, attr);
-
-        attr = attr_offset_new("attackframes", sym_long, attrflags, (method)0L, (method)bonk_attackbins_set, calcoffset(t_bonk, x_attackbins));
-        class_addattr(c, attr);
-        
-        attr = attr_offset_new("learn", sym_long, attrflags, (method)0L, (method)bonk_learn_set, calcoffset(t_bonk, x_learn));
-        class_addattr(c, attr);
-    
-        class_addmethod(c, (method)bonk_dsp, "dsp", A_CANT, 0);
-        class_addmethod(c, (method)bonk_bang, "bang", A_CANT, 0);
-        class_addmethod(c, (method)bonk_forget, "forget", 0);
-        class_addmethod(c, (method)bonk_thresh, "thresh", A_FLOAT, A_FLOAT, 0);
-        class_addmethod(c, (method)bonk_print, "print", A_DEFFLOAT, 0);
-        class_addmethod(c, (method)bonk_read, "read", A_DEFSYM, 0);
-        class_addmethod(c, (method)bonk_write, "write", A_DEFSYM, 0);
-        class_addmethod(c, (method)bonk_assist, "assist", A_CANT, 0);
-        
-        class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0);
-        class_addmethod(c, (method)object_obex_quickref, "quickref", A_CANT, 0);
-        
-        class_dspinit(c);
-    
-        class_register(CLASS_BOX, c);
-        bonk_class = c;
-        
-        post("bonk~ v1.3");
-        return (0);
-}
-
-static void *bonk_new(t_symbol *s, long ac, t_atom *av)
-{
-    short j;
-    t_bonk *x;
-        
-    if (x = (t_bonk *)object_alloc(bonk_class)) {
-        
-        t_insig *g;
-
-        x->x_npoints = DEFNPOINTS;
-        x->x_period = DEFPERIOD;
-        x->x_nfilters = DEFNFILTERS;
-        x->x_halftones = DEFHALFTONES;
-        x->x_firstbin = DEFFIRSTBIN;
-        x->x_minbandwidth = DEFMINBANDWIDTH;
-        x->x_overlap = DEFOVERLAP;
-        x->x_ninsig = 1;
-
-        x->x_hithresh = DEFHITHRESH;
-        x->x_lothresh = DEFLOTHRESH;
-        x->x_masktime = DEFMASKTIME;
-        x->x_maskdecay = DEFMASKDECAY;
-        x->x_debouncedecay = DEFDEBOUNCEDECAY;
-        x->x_minvel = DEFMINVEL;
-        x->x_attackbins = DEFATTACKBINS;
-        
-        if (!x->x_period) x->x_period = x->x_npoints/2;
-        x->x_template = (t_template *)getbytes(0);
-        x->x_ntemplate = 0;
-        x->x_infill = 0;
-        x->x_countdown = 0;
-        x->x_willattack = 0;
-        x->x_attacked = 0;
-        x->x_maskphase = 0;
-        x->x_debug = 0;
-        x->x_learn = 0;
-        x->x_learndebounce = clock_getsystime();
-        x->x_learncount = 0;
-        x->x_useloudness = 0;
-        x->x_debouncevel = 0;
-        x->x_sr = sys_getsr();
-        
-        if (ac) {
-            switch (av[0].a_type) {
-                case A_LONG:
-                    x->x_ninsig = av[0].a_w.w_long;
-                    break;
-            }
-        }
-
-        if (x->x_ninsig < 1) x->x_ninsig = 1;
-        if (x->x_ninsig > MAXCHANNELS) x->x_ninsig = MAXCHANNELS;
-        
-        attr_args_process(x, ac, av);   
-
-        x->x_insig = (t_insig *)getbytes(x->x_ninsig * sizeof(*x->x_insig));
-
-        dsp_setup((t_pxobject *)x, x->x_ninsig);
-
-        object_obex_store(x, gensym("dumpout"), outlet_new(x, NULL));
-
-        x->x_cookedout = listout((t_object *)x);
-
-        for (j = 0, g = x->x_insig + x->x_ninsig-1; j < x->x_ninsig; j++, g--) {
-                g->g_outlet = listout((t_object *)x);
-        }
-
-        x->x_clock = clock_new(x, (method)bonk_tick);
-
-        bonk_donew(x, x->x_npoints, x->x_period, x->x_ninsig, x->x_nfilters,
-            x->x_halftones, x->x_overlap, x->x_firstbin, x->x_minbandwidth,
-                sys_getsr());
-    }
-    return (x);
-}
-
-/* Attribute setters. */
-void bonk_minvel_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        float f = atom_getfloat(av);
-        if (f < 0) f = 0; 
-        x->x_minvel = f;
-    }
-}
-
-void bonk_lothresh_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        float f = atom_getfloat(av);
-        if (f > x->x_hithresh)
-            post("bonk: warning: low threshold greater than hi threshold");
-        x->x_lothresh = (f <= 0 ? 0.0001 : f);
-    }
-}
-    
-void bonk_hithresh_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        float f = atom_getfloat(av);
-        if (f < x->x_lothresh)
-            post("bonk: warning: low threshold greater than hi threshold");
-        x->x_hithresh = (f <= 0 ? 0.0001 : f);
-    }
-}
-
-void bonk_masktime_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        int n = atom_getlong(av);
-        x->x_masktime = (n < 0) ? 0 : n;
-    }
-}
-
-void bonk_maskdecay_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        float f = atom_getfloat(av);
-        f = (f < 0) ? 0 : f;
-        f = (f > 1) ? 1 : f;
-        x->x_maskdecay = f;
-    }
-}
-
-void bonk_debouncedecay_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        float f = atom_getfloat(av);
-        f = (f < 0) ? 0 : f;
-        f = (f > 1) ? 1 : f;
-        x->x_debouncedecay = f;
-    }
-}
-
-void bonk_debug_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        int n = atom_getlong(av);
-        x->x_debug = (n != 0);
-    }
-}
-
-void bonk_spew_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        int n = atom_getlong(av);
-        x->x_spew = (n != 0);
-    }
-}
-
-void bonk_useloudness_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        int n = atom_getlong(av);
-        x->x_useloudness = (n != 0);
-    }
-}
-
-void bonk_attackbins_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        int n = atom_getlong(av);
-        n = (n < 1) ? 1 : n;
-        n = (n > MASKHIST) ? MASKHIST : n;
-        x->x_attackbins = n;
-    }
-}
-
-void bonk_learn_set(t_bonk *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av) {
-        int n = atom_getlong(av);
-        if (n != 0) {
-            x->x_template = (t_template *)t_resizebytes(x->x_template,
-                x->x_ntemplate * sizeof(x->x_template[0]), 0);
-            x->x_ntemplate = 0;
-        }
-        x->x_learn = (n != 0);
-        x->x_learncount = 0;
-    }
-}
-/* end attr setters */
-
-void bonk_assist(t_bonk *x, void *b, long m, long a, char *s)
-{
-}
-
-    /* get current system time */
-double clock_getsystime()
-{
-    return gettime();
-}
-
-    /* elapsed time in milliseconds since the given system time */
-double clock_gettimesince(double prevsystime)
-{
-    return ((gettime() - prevsystime));
-}
-
-float qrsqrt(float f)
-{
-    return 1/sqrt(f);
-}
-#endif /* MSP */
diff --git a/extra/bonk~/makefile b/extra/bonk~/makefile
deleted file mode 100644
index af6399cca..000000000
--- a/extra/bonk~/makefile
+++ /dev/null
@@ -1,4 +0,0 @@
-NAME=bonk~
-CSYM=bonk_tilde
-
-include ../makefile
diff --git a/extra/bonk~/templates.txt b/extra/bonk~/templates.txt
deleted file mode 100644
index f3528d78a..000000000
--- a/extra/bonk~/templates.txt
+++ /dev/null
@@ -1,4 +0,0 @@
- 10.47   9.65  14.95  23.77  28.32  38.84  53.21  41.20  31.25  21.70  16.48 
-  6.52  13.93  27.82  58.05  24.11  35.26  35.98  37.78  22.54  13.56  10.75 
- 30.45  28.86  29.42  21.94  29.92  35.70  38.49  32.01  28.19  27.38  22.10 
- 66.77  46.27  28.82  25.95  22.84  20.61  20.33  14.18   6.86   8.92   7.37 
diff --git a/extra/choice/choice.pd_linux b/extra/choice/choice.pd_linux
new file mode 100755
index 0000000000000000000000000000000000000000..a87b6fd233a5ca89b252282084d41212f0d49be6
GIT binary patch
literal 9536
zcmeHNeQ;FO6~74!EOjL-UG1tn<q1z4YupA*TWA?wAq)Kom9Gdb;1ZHecFQIkcV7fG
z#Z8~gbbYKvp)*VeX-8%{PD@9pP;JrC;HF@zwyB+V_9=^~gMAUC!QvN++u!f*KC&BY
zr_=GzT;{xU&ON_-?!D)pd-vsC?g}<7tg5OKc9|e12x=pfglGV-zoKYq5Q>;2YQ<&Z
zQfasG<U21a(nKn5A?=RoLO8xuqyQW?f#6cwtHHdmdtoOHK_}7fDA5^kn^edo+qU$$
z)&})s#csb0_VWHe1d_z|7>48?@Cl$r-)R;H8aKW>b^5YzPu`L3+_yMCvgeoAy@V+V
zFK7w~QxeqazXnuZCPTRxG!^u@l3`kj)Bk@f9M2^s0LSGl$rpe#Mi+t@)6arF11c}B
zl48$;eX<S5n66f;#6VyQ>u6^m2VT3scR}!PCv&&1^8G$@dg>d0{pZvh@2T4jQ$;DS
z;JlZYS*dfJc2OW)V=Lg)?<~`a?;N8yjnVgv(H}0;IsUa}I{h6Qqdz`Izi*8G=P~;J
zF}klzp8<JmnJ(866JAnZtaOXhg*PEKmg#54=p5r-xe<hzhE-$iolG8-X;{%4z#l=<
zTn4|>1XeK=>gbGjg_2rJLJNgNDB2a(M5rAMrq)d@6kB4^JHjILt=mG&!X4417EUaP
zwIq|_q-c%AqpjgkGOYD<i;i$t^7c;AN?WKays;#;w6%4HwMe{eRFA=lXwl-Gp^mWD
z9*ei2_YM(@ceIOmj}{ASAz3N9<G>}tNp!#db`AX{Z%t^TyG?p8A=weU6z%Paa0wZU
zu5a}x<NmJ*NS#F~6mCOLnAds?P|jF{!d-1*QPVf)F9^-{&+=b)UM|I02JZZW89rJj
zAmgjX{4-(Z8YrOT^eDFP1Thh@W+C=9aN1ei(I~c9wYaEc51>!(K?`TnBy8T3<k+Mm
z<ZJ}{WMCcS7>bh|I2SqA+)a)R=pn}%d&%L@M~;yw<k-k6IW~DMIZ~jG93!bG$3fCS
zUL(XDa<>rk$dN<M>Ep}wlMahxU)`6T_eCL$?Pm&w!j>1biPrTT`2!f9^&a|IwR$jH
z*vAv5u*W`E3VYC*h=9cKF*GaefpZa|d3Z?bJS`%u9PXDoPrwKt!;eUvyCtGf|GCsD
zMrx^Vle$VBqZPv`snZmhL%mz-b<_jY*GZkw$Tz4jk$MC5CDa2_XVb_k>h)5eM|~Z2
zMd|_S5$bNKH&XAWE~HM^kxkS`J}MNz8N-{GTfc_XmpzN&=_lQ($JwLkS!?JYqScmu
zZK|O+p(gE6t%p!!=qsRQ_W2-ZwtMls`tJuns@6|c%^gW9nMc`L@2^TrSYd}wM6u1>
zk;LnVbh@w72i&V~S)1h=T7FdYW$%>TdyMUz3zqO=Lw}D_zji@J)}=jaVMrhFtX`Wn
zd}?+Z%W~^9Fn!tUW#ih6UjIs=z=6gw!HiLNj6>XuXSzvsq*tiU!;Pw!0|fW*#{t}3
z(p~T&C;6{)Z1q)o@~CN@0k@{ZpJ7leZ-LAbX_uOARGk_9i98xKst#)=``-TbVtea2
zyq#~!j2mqcvs;{&J>FPqvG0>x>^f5F<0)d~&@$VP<WRW+^TWJ5P_GZvuFe+Mp?M{i
z_fHs4U-t4ZAj&8AqJLw*`V84#^*OR9)PAtT4rZ%JYw#0Ooz_%1vK82PCYWo~P1ZX|
zin4khL8$Mwj#k#=91!L%H3ep6D^1*mFx^elLzO1}Qo!^hnlhCpE*4B%X-ZU@_|gH>
zHkwvenw&+`4w~jwn)oV%Ry%3B0w!al@;l^GVaq#aKk9d(zUE#9^EOY-dh-A+vtT(<
zzb&I(CGxMnd~Ek^7v*0x2hG9sTPLPu_FshtBA+vEQuISr`XB1%p02s~LNqrP`HY*?
zD$5KwwhZQ))J?gAX21!d_b3EcZmXI?L&|Q*j0$BBWQKvV7c%Ef*$0^urK~{a%qXjn
zITgyax#x}^thsv?hK!|IVh$Qyq5y`vMy&@aNERQH<&6(8ZOCS$y5#5}o(iZQ6fpk?
z^s~bk!-cWYhxLw}n3T_*sLtm$yisQ~sgd;1VaL@%q;5Fj$miO(A@5@^f#BU?taM@D
zSc~DjZ-Du>`j*hzQa<K${HLESq=&R;w+wE65YaKMCz)NDXhA<d*%Y~ha27GWdVih%
ze%0pmmN&J{`nf7Cte>mirY+acP0;4+=N#HB{oKTD+I0QgByFlGo@62-vTSAwtiY!r
za|JJ85aG{Be`cT#Y*n2ZSVg|dOmVp&?j$!;kCZfWGj*h-k(((e=13&DnQAC$<P+E7
zG57RcJM+2W-8?$v37UBd%>?(aezF%^Rc5z?G0iTWiLCm8vZYXS@6UkA=u2>L%tCrH
zaK+X}v#;u`ez-0(-+|o7uTfVZUBH@<L12wYDzJITGq47v9vG(O0#lKlU_Rt4n8%z?
z<}$0zUbPF!65-}Yd}|(SQoFFuzjd|aY>k;QB)}Tg3EpKrh=Y4>k5cpF9z;(c=#>c|
z_l<s%$>cROBq5yREaeUr)-`82u}w3C*l@E_$HUB6C{y$?xH`O0At=4jXP^z*di4Qc
zR{AT(r^$$^>#TpgPah5N0Z7E?Rb$3tC9||@!_##e2I+GS;^X8Gff4k9HE;{8gn!Ix
z4syC7-K?a8zD%9-aFG24(!GFVwxy%d`ruvULciJUI67En!s6kGIC4;KF9jRGZM{HX
zvorTh8B89O*kRb9*n!r=65^_W$TM>kvQ<Ld6%YqI8-+wA#8Uy0XXq$op@euVAo467
zh0K%?Uj;;-siP1fAxZ^Ao~@&h{5zbqS^<$~>?q^_AqZe?@vuQC@at<1=3jaFSl-;d
z@q784X_-MsZqQuoFoRBVrx|pSyUd`Q+-(Lu<Q_BVCHI;^AGyyAD&&e8RLRxc;#zZU
ztv=8slMlU~%^$;=eTS##^1PXQd>6J17GfSoFz<wcqiu5WT+iiws<jN`tb`1Qk;$3c
z1b$6Z2t{A^`RROF@)-O0N|0_)t<7kYF&6PB94`citW$48YT&DZ!<r47okW*VE+({j
zic5*KesLHhtNF>nnx8&B<u5gl9!xJ((<6M-xg~qzLiwI!KX4d$k*bPy7H;~oi!h1}
zOG_K(M!8{LN5A@jcXjdosQ7;OyaZncu%YwK5HD8RrI~#cOTSzCDMw+*m;^)58T-Ag
z?A`j<=dnkJ;Q70Fk1qa^CGd9?{(=g(Bt&;2+NFu&pGb(tm9yKFmX5GOzEQdI%l_Hz
z|KAh7_zNT1_+vZ*;}IB-z<314BQPF;@d%7ZU_1ij5g3oacmzK62;i^60-f5Nvi!(V
z;;(_bK)lz(HI2N_<97)!KyQCkh!24CBSZ?{Gx()}7qR?MemUxSm+J=cQ^y(HBk`+9
z3giLtT99|fb!bf41<pH11;jgFes93%vG{Z73}cJ4?FjfT==gjThx`Al@Xp;XZ=ug>
z40;-9252^DK4=+eJtzVCA?SY4gP`Alo(8=DdKJVwvqcLQd`+osUf<KD^(YPg2LG&U
z8+xQR_v)f9gg+TcY6-1nz3_L%wXnaVtH-~-CmL(JHrghn7HLUFgum@}d50;vmMB_o
z3n!A%cvpoIf-Mn_5mywtW18^G%TvD=-UL}*q52bXdFAL2M?&q1md>#7w`%c35*-!U
z_gmozPFgynt>_?*hIsg;w_;1&RiaV6vonmp`Tys_b>}A~uGyIqso-|O63Q|IPv#DB
z%qJ2*A=`Fx623<WeAJLRz<eX|Hf$`e7Io~K{^SEf3Rw05Ch^QiESt<p;+VH2=Br(7
zaSkf%++*I6*w*fs?MXopbCojll@x$%&&|fKKpj7l5yyNdDUfYDIrE<P{x**LgOoxY
z?VO*DYlqCSA{FKS+zTAXXBXmFT0l1L2rwi!D@uhpQVe9{_<vwXUT)@6VeD8EAREW~
zeUeXFiVwTrO(h)Xs{%vn{tviR8EywKB-;n!wtP<s$MZz~{~CPbV!Z5P<L*NR$48tC
z``z^kI9{RHI1g|h;A|f-otGbg%ox+3{C_*Z4M9d2WnmkR;};;?AMepE;COc0g*ei$
zKsJu&;u+wYY)}b9-2O5g&zgWTIwqLTkM96v_RsP0|7SERAMY0?@f3*t0wN1>GfOfV
TZ8p)DT{;vYp0O2hVp#qS*Kwc>

literal 0
HcmV?d00001

diff --git a/extra/expr~/LICENSE.txt b/extra/expr~/LICENSE.txt
deleted file mode 100644
index a52b16e40..000000000
--- a/extra/expr~/LICENSE.txt
+++ /dev/null
@@ -1,341 +0,0 @@
-
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-                       59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-			    Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, not
-price.  Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-		    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
-  2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) Accompany it with the complete corresponding machine-readable
-    source code, which must be distributed under the terms of Sections
-    1 and 2 above on a medium customarily used for software interchange; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable.  However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
-  5. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
-  7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time.  Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation.  If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission.  For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this.  Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
-			    NO WARRANTY
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
-
-	    How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) 19yy  <name of author>
-
-    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
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) 19yy name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff --git a/extra/expr~/README.txt b/extra/expr~/README.txt
deleted file mode 100644
index bf84f2ae6..000000000
--- a/extra/expr~/README.txt
+++ /dev/null
@@ -1,97 +0,0 @@
-
-You can get more information on the expr object at
-http://www.crca.ucsd.edu/~yadegari/expr.html
-
------------
-
-New if Version 0.4
-
--access to variables (made by value object)
--multiple expression separated by ;
--added the following shorthands:
-	$y or $y1 = $y1[-1] and $y2 = $y2[-1]
--new functions:
-	if - conditional evaluation
-	cbrt - cube root
-	erf - error function
-	erfc - complementary error function
-	expm1 - exponential minus 1,
-	log1p - logarithm of 1 plus
-	isinf - is the value infinite,
-	finite - is the value finite
-	isnan -- is the resut a nan (Not a number)
-	copysign - copy sign of a number
-	ldexp  -  multiply floating-point number by integral power of 2
-	imodf -	get signed integral value from floating-point number
-	modf - get signed fractional value from floating-point number
-	drem - floating-point remainder function
-
-   Thanks to Orm Finnendahl for adding the following functions:
-	fmod - floating-point remainder function
-	ceil - ceiling function: smallest integral value not less than argument 
-	floor - largest integral value not greater than argument
-
-------------
-
-New in Version 0.3
--Full function functionality
-
-------------
-
-The object "expr" is used for expression evaluaion of control data.
-
-Expr~ and fexpr~ are extentions to the expr object to work with vectors.
-The expr~ object is designed to efficiently combine signal and control
-stream processing by vector operations on the basis of the block size of
-the environment.
-
-fexpr~ object provides a flexible mechanism for building FIR and
-IIR filters by evaluating expressions on a sample by sample basis
-and providing access to prior samples of the input and output audio
-streams. When fractional offset is used, fexpr~ uses linear interpolation
-to determine the value of the indexed sample. fexpr~ evaluates the
-expression for every single sample and at every evaluation previous
-samples (limited by the audio vector size) can be accessed. $x is used to
-denote a singnal input whose samples we would like to access. The syntax
-is $x followed by the inlet number and indexed by brackets, for example
-$x1[-1] specifies the previous sample of the first inlet. Therefore,
-if we are to build a simple filter which replaces every sample by
-the average of that sample and its previous one, we would use "fexpr~
-($x1[0]+$x1[-1])/2 ". For ease of when the brackets are omitted, the
-current sample is implied, so we can right the previous filter expression
-as follows:  " fexpr~ ($x1+$x1[-1])/2". To build IIR filters $y is used
-to access the previous samples of the output stream.
-
-The three objects expr, expr~, and fexpr~ are implemented in the same object
-so the files expr~.pd_linux and fexpr~.pd_linux are links to expr.pd_linux
-This release has been compiled and tested on Linux 6.0.
-
---------
-
-Here are some syntax information: (refer to help-expr.pd for examples)
- 
-Syntyax:
-The syntax is very close to how expression are written in
-C. Variables are specified as follows where the '#' stands
-for the inlet number:
-$i#: integer input variable
-$f#: float input variable
-$s#: symbol input variable
-
-Used for expr~ only:
-$v#: signal (vector) input (vector by vector evaluation)
-
-Used for fexpr~ only:
-$x#[n]: the sample from inlet # indexed by n, where n has to
-	satisfy 0 => n >= -vector size,
-	($x# is a shorthand for $x#[0], specifying the current sample)
-
-$y#[n]: the output value indexed by n, where n has to
-	satisfy 0 > n >= -vector size,
-	$y[n] is a shorthand for $y1[n]
-
-
-I'll appreciate hearing about bugs, comments, suggestions, ...
-
-Shahrokh Yadegari (sdy@ucsd.edu)
-7/10/02
diff --git a/extra/expr~/fts_to_pd.h b/extra/expr~/fts_to_pd.h
deleted file mode 100644
index 9ca2fc422..000000000
--- a/extra/expr~/fts_to_pd.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/* fts_to_pd.h -- alias some fts names to compile in Pd.
-
-copyright 1999 Miller Puckette;
-permission is granted to use this file for any purpose.
-*/
-
-
-#define fts_malloc malloc
-#define fts_calloc calloc
-#define fts_free free
-#define fts_realloc realloc
-#define fts_atom_t t_atom
-#define fts_object_t t_object
-typedef t_symbol *fts_symbol_t;
-
-#ifdef MSP
-#define t_atom          Atom
-#define t_symbol        Symbol
-#define pd_new(x)       newobject(x);
-#define pd_free(x)      freeobject(x);
-#define t_outlet        void
-#define t_binbuf        void
-typedef t_class         *t_pd;
-typedef float           t_floatarg;
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <string.h>
-#include <errno.h>
-
-void pd_error(void *object, char *fmt, ...);
-
-#endif /* MSP */
-
-#define post_error pd_error
-#define fts_is_floatg(x) ((x)->a_type == A_FLOAT)
-
-#define fts_new_symbol_copy gensym
-
-#define fts_symbol_name(x) ((x)->s_name)
diff --git a/extra/expr~/makefile b/extra/expr~/makefile
deleted file mode 100644
index 15593d390..000000000
--- a/extra/expr~/makefile
+++ /dev/null
@@ -1,191 +0,0 @@
-
-current: expr.pd_linux expr~.pd_linux fexpr~.pd_linux \
-     ../expr.pd_linux ../expr~.pd_linux ../fexpr~.pd_linux
-
-install: install_linux
-
-clean: clean_linux
-
-PDEXTERN=/usr/local/lib/pd/externs
-
-# ----------------------- NT -----------------------
-
-pd_nt: expr.dll
-
-NTOBJ =  vexp.obj vexp_fun.obj vexp_if.obj
-
-PDNTCFLAGS = /W3 /DNT /DPD /nologo
-VC = "C:\Program Files\Microsoft Visual Studio 9.0\VC"
-VSTK = "C:\Program Files\Microsoft SDKs\Windows\v6.0A"
-
-PDNTINCLUDE = /I. /I..\..\src /I$(VC)\include
-
-PDNTLDIR = $(VC)\lib
-PDNTLIB = /NODEFAULTLIB:libcmt /NODEFAULTLIB:oldnames /NODEFAULTLIB:kernel32 \
-	$(PDNTLDIR)\libcmt.lib $(PDNTLDIR)\oldnames.lib \
-        $(VSTK)\lib\kernel32.lib \
-	 ..\..\bin\pd.lib 
-
-.c.obj:
-	cl $(PDNTCFLAGS) $(PDNTINCLUDE) /c $*.c
-
-expr.dll: $(NTOBJ)
-	link /dll /export:expr_setup /export:expr_tilde_setup \
-	    /export:fexpr_tilde_setup $(NTOBJ) $(PDNTLIB)
-	ren vexp.dll expr.dll
-	copy expr.dll ..\expr.dll
-	copy expr.dll ..\expr~.dll
-	copy expr.dll ..\fexpr~.dll
-	copy help-expr.pd ..\help-expr.pd
-
-# ----------------------- IRIX 5.x -----------------------
-
-pd_irix5: 
-
-.SUFFIXES: .pd_irix5
-
-SGICFLAGS5 = -o32 -DPD -DSGI -O2
-
-
-SGIINCLUDE =  -I/usr/people/msp/pd/pd/src
-
-.c.pd_irix5:
-	$(CC) $(SGICFLAGS5) $(SGIINCLUDE) -o $*.o -c $*.c
-	ld -elf -shared -rdata_shared -o $*.pd_irix5 $*.o
-	rm $*.o
-
-# ----------------------- IRIX 6.x -----------------------
-
-pd_irix6: 
-
-.SUFFIXES: .pd_irix6
-
-SGICFLAGS6 = -DPD -DSGI -n32 \
-	-OPT:roundoff=3 -OPT:IEEE_arithmetic=3 -OPT:cray_ivdep=true \
-	-Ofast=ip32
-
-SGICFLAGS5 = -DPD -O2 -DSGI
-
-SGIINCLUDE =  -I/usr/people/msp/pd/pd/src
-
-.c.pd_irix6:
-	$(CC) $(SGICFLAGS6) $(SGIINCLUDE) -o $*.o -c $*.c
-	ld -elf -shared -rdata_shared -o $*.pd_irix6 $*.o
-	rm $*.o
-
-# ----------------------- LINUX i386 -----------------------
-
-LINUXOBJ =  vexp.pd_linux_o vexp_fun.pd_linux_o vexp_if.pd_linux_o
-.SUFFIXES: .pd_linux_o
-
-LINUXCFLAGS = -DPD -O2 -funroll-loops -fomit-frame-pointer -fPIC \
-    -fno-strict-aliasing -Wall -W -Wshadow -Wstrict-prototypes \
-    -Wno-unused -Wno-parentheses -Wno-switch 
-
-LINUXINCLUDE =  -I../../src
-
-.c.pd_linux_o:
-	$(CC) -g $(LINUXCFLAGS) $(LINUXINCLUDE) -o $*.pd_linux_o -c $*.c
-
-expr.pd_linux: $(LINUXOBJ)
-	$(CC) -shared -o expr.pd_linux $(LINUXOBJ) -lc -lm
-	strip --strip-unneeded expr.pd_linux
-
-expr~.pd_linux: expr.pd_linux
-	-ln -s expr.pd_linux expr~.pd_linux
-
-fexpr~.pd_linux: expr.pd_linux
-	-ln -s expr.pd_linux fexpr~.pd_linux
-
-../expr.pd_linux: expr.pd_linux
-	-ln -s expr~/expr.pd_linux ../expr.pd_linux
-
-../expr~.pd_linux: expr.pd_linux
-	-ln -s expr~/expr.pd_linux ../expr~.pd_linux
-
-../fexpr~.pd_linux: expr.pd_linux
-	-ln -s expr~/expr.pd_linux ../fexpr~.pd_linux
-
-install_linux:
-	install expr.pd_linux $(PDEXTERN)
-	rm -f $(PDEXTERN)/expr~.pd_linux
-	rm -f $(PDEXTERN)/fexpr~.pd_linux
-	cd $(PDEXTERN); \
-	-ln -s expr.pd_linux expr~.pd_linux
-	-ln -s expr.pd_linux fexpr~.pd_linux
-
-
-linux_clean:
-	rm -f *.pd_linux_o *.o
-
-# ----------------------- MAC OSX -----------------------
-
-MACOSXOBJ3 =  vexp.d_ppc_o vexp_fun.d_ppc_o vexp_if.d_ppc_o
-MACOSXOBJ =  vexp.d_fat_o vexp_fun.d_fat_o vexp_if.d_fat_o
-.SUFFIXES: .d_ppc_o .d_fat_o
-
-MACOSXCFLAGS = -DMACOSX -DPD -O2 -Wall -W -Wshadow -Wstrict-prototypes \
-    -Wno-unused -Wno-parentheses -Wno-switch 
-
-MACOSXINCLUDE =  -I../../src
-
-d_ppc: expr.d_ppc expr~.d_ppc fexpr~.d_ppc
-.c.d_ppc_o:
-	$(CC) -g $(MACOSXCFLAGS) $(MACOSXINCLUDE) -o $*.d_ppc_o -c $*.c
-
-expr.d_ppc: $(MACOSXOBJ3)
-	$(CC) -bundle -undefined suppress  -flat_namespace \
-		-o expr.d_ppc $(MACOSXOBJ3)  -lm
-	rm -f ../expr.d_ppc
-	-ln -s expr~/expr.d_ppc ..
-
-expr~.d_ppc: expr.d_ppc
-	-ln -s expr.d_ppc expr~.d_ppc
-	rm -f ../expr~.d_ppc
-	-ln -s expr~/expr~.d_ppc ..
-
-fexpr~.d_ppc: expr.d_ppc
-	-ln -s expr.d_ppc fexpr~.d_ppc
-	rm -f ../fexpr~.d_ppc
-	-ln -s expr~/fexpr~.d_ppc ..
-
-install_d_fat:
-	install expr.d_fat $(PDEXTERN)
-	rm -f $(PDEXTERN)/expr~.d_fat
-	rm -f $(PDEXTERN)/fexpr~.d_fat
-	cd $(PDEXTERN); \
-	-ln -s expr.d_fat expr~.d_fat; \
-	-ln -s expr.d_fat fexpr~.d_fat
-
-d_fat: expr.d_fat expr~.d_fat fexpr~.d_fat
-.c.d_fat_o:
-	$(CC) -g $(MACOSXCFLAGS) $(MACOSXINCLUDE)  -arch i386 -arch ppc \
-	-o $*.d_fat_o -c $*.c
-
-expr.d_fat: $(MACOSXOBJ)
-	$(CC) -arch i386 -arch ppc -bundle -undefined suppress  -flat_namespace \
-		-o expr.d_fat $(MACOSXOBJ)  -lm
-	rm -f ../expr.d_fat
-	-ln -s expr~/expr.d_fat ..
-
-expr~.d_fat: expr.d_fat
-	-ln -s expr.d_fat expr~.d_fat
-	rm -f ../expr~.d_fat
-	-ln -s expr~/expr~.d_fat ..
-
-fexpr~.d_fat: expr.d_fat
-	-ln -s expr.d_fat fexpr~.d_fat
-	rm -f ../fexpr~.d_fat
-	-ln -s expr~/fexpr~.d_fat ..
-
-install_d_ppc:
-	install expr.d_ppc $(PDEXTERN)
-	rm -f $(PDEXTERN)/expr~.d_ppc
-	rm -f $(PDEXTERN)/fexpr~.d_ppc
-	cd $(PDEXTERN); \
-	-ln -s expr.d_ppc expr~.d_ppc; \
-	-ln -s expr.d_ppc fexpr~.d_ppc
-
-clean_d_ppc:
-	rm -f *.d_ppc_o *.o
-
diff --git a/extra/expr~/vexp.c b/extra/expr~/vexp.c
deleted file mode 100644
index 659bd2973..000000000
--- a/extra/expr~/vexp.c
+++ /dev/null
@@ -1,2142 +0,0 @@
-/*
- * jMax
- * Copyright (C) 1994, 1995, 1998, 1999 by IRCAM-Centre Georges Pompidou, Paris, France.
- * 
- * 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.
- * 
- * See file LICENSE for further informations on licensing terms.
- * 
- * 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.
- * 
- * Based on Max/ISPW by Miller Puckette.
- *
- * Authors: Maurizio De Cecco, Francois Dechelle, Enzo Maggi, Norbert Schnell.
- *
- */
-
-/* "expr" was written by Shahrokh Yadegari c. 1989. -msp */
-/* "expr~" and "fexpr~" conversion by Shahrokh Yadegari c. 1999,2000 */
-
-/*
- * Feb 2002 -   added access to variables
- *              multiple expression support
- *              new short hand forms for fexpr~
- *                      now $y or $y1 = $y1[-1] and $y2 = $y2[-1]
- *              --sdy
- *
- * July 2002
- *              fixed bugs introduced in last changes in store and ET_EQ
- *              --sdy
- *              
- */
-
-/*
- * vexp.c -- a variable expression evaluator
- *
- * This modules implements an expression evaluator using the
- * operator-precedence parsing.  It transforms an infix expression
- * to a prefix stack ready to be evaluated.  The expression sysntax
- * is close to that of C.  There are a few operators that are not
- * supported and functions are also recognized.  Strings can be
- * passed to functions when they are quoted in '"'s. "[]" are implememted
- * as an easy way of accessing the content of tables, and the syntax
- * table_name[index].
- * Variables (inlets) are specified with the following syntax: $x#,
- * where x is either i(integers), f(floats), and s(strings); and #
- * is a digit that coresponds to the inlet number.  The string variables
- * can be used as strings when they are quoted and can also be used as
- * table names when they are followed by "[]".
- *
- * signal vectors have been added to this implementation:
- * $v# denotes a signal vector
- * $x#[index]  is the value of a sample at the index of a the signal vector
- * $x# is the shorthand for $x#[0]
- * $y[index]   is the value of the sample output at the index of a the
- *             signal output
- * "index" for $x#[index] has to have this range (0 <= index < vectorsize)
- * "index" for $y[index]  has to have this range (0 <  index < vectorsize)
- */
-
-#include <string.h>
-#include <stdlib.h>
-#include <ctype.h>
-#include "vexp.h" 
-#ifdef MSP
-#undef isdigit
-#define isdigit(x)      (x >= '0' && x <= '9')
-#endif
-
-char *atoif(char *s, long int *value, long int *type);
-
-static struct ex_ex *ex_lex(struct expr *expr, long int *n);
-struct ex_ex *ex_match(struct ex_ex *eptr, long int op);
-struct ex_ex *ex_parse(struct expr *expr, struct ex_ex *iptr,
-                                        struct ex_ex *optr, long int *argc);
-struct ex_ex *ex_eval(struct expr *expr, struct ex_ex *eptr,
-                                                struct ex_ex *optr, int i);
-
-int expr_donew(struct expr *exprr, int ac, t_atom *av);
-struct ex_ex *eval_func(struct expr *expr,struct ex_ex *eptr,
-                                                struct ex_ex *optr, int i);
-struct ex_ex *eval_tab(struct expr *expr, struct ex_ex *eptr,
-                                                struct ex_ex *optr, int i);
-struct ex_ex *eval_var(struct expr *expr, struct ex_ex *eptr,
-                                                struct ex_ex *optr, int i);
-struct ex_ex *eval_store(struct expr *expr, struct ex_ex *eptr,
-                                                struct ex_ex *optr, int i);
-struct ex_ex *eval_sigidx(struct expr *expr, struct ex_ex *eptr,
-                                                struct ex_ex *optr, int i);
-static int cal_sigidx(struct ex_ex *optr,       /* The output value */
-           int i, float rem_i,      /* integer and fractinal part of index */
-           int idx,                  /* index of current fexpr~ processing */
-           int vsize,                                       /* vector size */
-           float *curvec, float *prevec);   /* current and previous table */
-t_ex_func *find_func(char *s);
-void ex_dzdetect(struct expr *expr);
-
-#define MAX_ARGS        10
-extern t_ex_func ex_funcs[];
-
-struct ex_ex nullex;
-
-void set_tokens (char *s);
-int getoken (struct expr *expr, struct ex_ex *eptr);
-void ex_print (struct ex_ex *eptr);
-#ifdef MSP
-void atom_string(t_atom *a, char *buf, unsigned int bufsize);
-
-void atom_string(t_atom *a, char *buf, unsigned int bufsize)
-{
-    char tbuf[30];
-    switch(a->a_type)
-    {
-    case A_SEMI: strcpy(buf, ";"); break;
-    case A_COMMA: strcpy(buf, ","); break;
-#ifdef PD
-    case A_POINTER:
-        strcpy(buf, "(pointer)");
-        break;
-#endif
-    case A_FLOAT:
-        sprintf(tbuf, "%g", a->a_w.w_float);
-        if (strlen(tbuf) < bufsize-1) strcpy(buf, tbuf);
-        else if (a->a_w.w_float < 0) strcpy(buf, "-");
-        else  strcat(buf, "+");
-        break;
-    case A_LONG:
-        sprintf(tbuf, "%d", a->a_w.w_long);
-        if (strlen(tbuf) < bufsize-1) strcpy(buf, tbuf);
-        else if (a->a_w.w_float < 0) strcpy(buf, "-");
-        else  strcat(buf, "+");
-        break;
-    case A_SYMBOL:
-    {   
-        char *sp;       
-        unsigned int len;
-        int quote;
-        for (sp = a->a_w.w_symbol->s_name, len = 0, quote = 0; *sp; sp++, len++)
-            if (*sp == ';' || *sp == ',' || *sp == '\\' ||
-                (*sp == '$' && sp == a->a_w.w_symbol->s_name && sp[1] >= '0'
-                    && sp[1] <= '9'))
-                quote = 1;
-        if (quote)
-        {
-            char *bp = buf, *ep = buf + (bufsize-2);
-            sp = a->a_w.w_symbol->s_name;
-            while (bp < ep && *sp)
-            {
-                if (*sp == ';' || *sp == ',' || *sp == '\\' ||
-                    (*sp == '$' && bp == buf && sp[1] >= '0' && sp[1] <= '9'))
-                        *bp++ = '\\';
-                *bp++ = *sp++;
-            }
-            if (*sp) *bp++ = '*';
-            *bp = 0;
-            /* post("quote %s -> %s", a->a_w.w_symbol->s_name, buf); */
-        }
-        else
-        {
-            if (len < bufsize-1) strcpy(buf, a->a_w.w_symbol->s_name);
-            else
-            {
-                strncpy(buf, a->a_w.w_symbol->s_name, bufsize - 2);
-                strcpy(buf + (bufsize - 2), "*");
-            }
-        }
-    }
-        break;
-#ifdef PD
-    case A_DOLLAR:
-        sprintf(buf, "$%d", a->a_w.w_index);
-        break;
-    case A_DOLLSYM:
-        sprintf(buf, "$%s", a->a_w.w_symbol->s_name);
-                break;
-#else /* MAX */
- case A_DOLLAR:
-        sprintf(buf, "$%s", a->a_w.w_symbol->s_name);
-        break;
-#endif
-    default:
-        post("atom_string bug");
-    }
-}
-#endif /* MSP */
-/*
- * expr_donew -- create a new "expr" object.  
- *           returns 1 on failure, 0 on success.
- */ 
-int
-expr_donew(struct expr *expr, int ac, t_atom *av)
-{
-        struct ex_ex *list;
-        struct ex_ex *ret;
-        long max_node = 0;              /* maximum number of nodes needed */
-        char *exp_string;
-        int exp_strlen;
-        t_binbuf *b;
-        int i;
-
-        memset(expr->exp_var, 0, MAX_VARS * sizeof (*expr->exp_var));
-#ifdef PD
-        b = binbuf_new();
-        binbuf_add(b, ac, av);
-        binbuf_gettext(b, &exp_string, &exp_strlen);
-
-#else /* MSP */
- {
-    char *buf = getbytes(0), *newbuf;
-    int length = 0;
-    char string[250];
-    t_atom *ap;
-    int indx;
-
-    for (ap = av, indx = 0; indx < ac; indx++, ap = ++av) {
-        int newlength;
-        if ((ap->a_type == A_SEMI || ap->a_type == A_COMMA) &&
-                length && buf[length-1] == ' ') length--;
-        atom_string(ap, string, 250);
-        newlength = length + strlen(string) + 1;
-        if (!(newbuf = t_resizebytes(buf, length, newlength))) break;
-        buf = newbuf;
-        strcpy(buf + length, string);
-        length = newlength;
-        if (ap->a_type == A_SEMI) buf[length-1] = '\n';
-        else buf[length-1] = ' ';
-    }
-
-    if (length && buf[length-1] == ' ') {
-        if (newbuf = t_resizebytes(buf, length, length-1))
-        {
-            buf = newbuf;
-            length--;
-        }
-    }
-    exp_string = buf;
-    exp_strlen  = length;
- }
-#endif
-        exp_string = (char *)t_resizebytes(exp_string, exp_strlen,exp_strlen+1);
-        exp_string[exp_strlen] = 0;
-        expr->exp_string = exp_string;
-        expr->exp_str = exp_string;
-        expr->exp_nexpr = 0;
-        ret = (struct ex_ex *) 0;
-        /*
-         * if ret == 0 it means that we have no expression
-         * so we let the pass go through to build a single null stack
-         */
-        while (*expr->exp_str || !ret) {
-                list = ex_lex(expr, &max_node);
-                if (!list) {            /* syntax error */
-                        goto error;
-                }
-                expr->exp_stack[expr->exp_nexpr] =
-                  (struct ex_ex *)fts_malloc(max_node * sizeof (struct ex_ex));
-                expr->exp_nexpr++;
-                ret = ex_match(list, (long)0);
-                if (!ret)               /* syntax error */
-                        goto error;
-                ret = ex_parse(expr,
-                        list, expr->exp_stack[expr->exp_nexpr - 1], (long *)0);
-                if (!ret)
-                        goto error;
-        }
-        *ret = nullex;
-        t_freebytes(exp_string, exp_strlen+1);
-        return (0);
-error:
-        for (i = 0; i < expr->exp_nexpr; i++) {
-                fts_free(expr->exp_stack[i]);
-                expr->exp_stack[i] = 0;
-        }
-        expr->exp_nexpr = 0;
-        if (list)
-                fts_free(list);
-        t_freebytes(exp_string, exp_strlen+1);
-        return (1);
-}
-
-/*
- * ex_lex -- This routine is a bit more than a lexical parser since it will
- *           also do some syntax checking.  It reads the string s and will
- *           return a linked list of struct ex_ex. 
- *           It will also put the number of the nodes in *n.
- */
-struct ex_ex *
-ex_lex(struct expr *expr, long int *n)
-{
-        struct ex_ex *list_arr;
-        struct ex_ex *exptr;
-        long non = 0;           /* number of nodes */
-        long maxnode = 0;
-
-        list_arr = (struct ex_ex *)fts_malloc(sizeof (struct ex_ex) * MINODES);
-        if (! list_arr) {
-                post("ex_lex: no mem\n");
-                return ((struct ex_ex *)0);
-        }
-        exptr = list_arr;
-        maxnode = MINODES;
-
-        while (8)
-        {
-                if (non >= maxnode) {
-                        maxnode += MINODES;
-
-                        list_arr = fts_realloc((void *)list_arr,
-                                        sizeof (struct ex_ex) * maxnode);
-                        if (!list_arr) {
-                                post("ex_lex: no mem\n");
-                                return ((struct ex_ex *)0);
-                        }
-                        exptr = &(list_arr)[non];
-                }
-
-                if (getoken(expr, exptr)) {
-                        fts_free(list_arr);
-                        return ((struct ex_ex *)0);
-                }
-                non++;
-
-                if (!exptr->ex_type)
-                        break;
-
-                exptr++;
-        }
-        *n = non;
-
-        return list_arr;
-}
-
-/*
- * ex_match -- this routine walks through the eptr and matches the
- *             perentheses and brackets, it also converts the function
- *             names to a pointer to the describing structure of the 
- *             specified function
- */
-/* operator to match */
-struct ex_ex *
-ex_match(struct ex_ex *eptr, long int op)
-{
-        int firstone = 1;
-        struct ex_ex *ret;
-        t_ex_func *fun;
-
-        for (; 8; eptr++, firstone = 0) {
-                switch (eptr->ex_type) {
-                case 0:
-                        if (!op)
-                                return (eptr);
-                        post("expr syntax error: an open %s not matched\n",
-                            op == OP_RP ? "parenthesis" : "bracket");
-                        return (exNULL);
-                case ET_INT:
-                case ET_FLT:
-                case ET_II:
-                case ET_FI:
-                case ET_SI:
-                case ET_VI:
-                case ET_SYM:
-                case ET_VSYM:
-                        continue;
-                case ET_YO:
-                        if (eptr[1].ex_type != ET_OP || eptr[1].ex_op != OP_LB)
-                                eptr->ex_type = ET_YOM1;
-                        continue;
-                case ET_XI:
-                        if (eptr[1].ex_type != ET_OP || eptr[1].ex_op != OP_LB)
-                                eptr->ex_type = ET_XI0;
-                        continue;
-                case ET_TBL:
-                case ET_FUNC:
-                case ET_LP:
-                        /* CHANGE
-                case ET_RP:
-                        */
-                case ET_LB:
-                        /* CHANGE
-                case ET_RB:
-                         */
-                        post("ex_match: unexpected type, %ld\n", eptr->ex_type);
-                        return (exNULL);
-                case ET_OP:
-                        if (op == eptr->ex_op)
-                                return (eptr);
-                        /*
-                         * if we are looking for a right peranthesis
-                         * or a right bracket and find the other kind,
-                         * it has to be a syntax error
-                         */
-                        if ((eptr->ex_op == OP_RP && op == OP_RB) ||
-                            (eptr->ex_op == OP_RB && op == OP_RP)) {
-                                post("expr syntax error: prenthesis or brackets not matched\n");
-                                return (exNULL);
-                        }
-                        /*
-                         * Up to now we have marked the unary minuses as
-                         * subrtacts.  Any minus that is the first one in
-                         * chain or is preceeded by anything except ')' and
-                         * ']' is a unary minus.
-                         */
-                        if (eptr->ex_op == OP_SUB) {
-                                ret = eptr - 1;
-                                if (firstone ||  (ret->ex_type == ET_OP &&
-                                    ret->ex_op != OP_RB && ret->ex_op != OP_RP))
-                                        eptr->ex_op = OP_UMINUS;
-                        } else if (eptr->ex_op == OP_LP) {
-                                ret = ex_match(eptr + 1, OP_RP);
-                                if (!ret)
-                                        return (ret);
-                                eptr->ex_type = ET_LP;
-                                eptr->ex_ptr = (char *) ret;
-                                eptr = ret;
-                        } else if (eptr->ex_op == OP_LB) {
-                                ret = ex_match(eptr + 1, OP_RB);
-                                if (!ret)
-                                        return (ret);
-                                eptr->ex_type = ET_LB;
-                                eptr->ex_ptr = (char *) ret;
-                                eptr = ret;
-                        }
-                        continue;
-                case ET_STR:
-                        if (eptr[1].ex_op == OP_LB) {
-                                char *tmp;
-
-                                eptr->ex_type = ET_TBL;
-                                tmp = eptr->ex_ptr;
-                                if (ex_getsym(tmp, (t_symbol **)&(eptr->ex_ptr))) {
-                                        post("expr: syntax error: problms with ex_getsym\n");
-                                        return (exNULL);
-                                }
-                                fts_free((void *)tmp);
-                        } else if (eptr[1].ex_op == OP_LP) {
-                                fun = find_func(eptr->ex_ptr);
-                                if (!fun) {
-                                        post(
-                                         "expr: error: function %s not found\n",
-                                                                eptr->ex_ptr);
-                                        return (exNULL);
-                                }
-                                eptr->ex_type = ET_FUNC;
-                                eptr->ex_ptr = (char *) fun;
-                        } else {
-                                char *tmp;
-
-                                if (eptr[1].ex_type && eptr[1].ex_type!=ET_OP){
-                                        post("expr: syntax error: bad string '%s'\n", eptr->ex_ptr);
-                                        return (exNULL);
-                                }
-                                /* it is a variable */
-                                eptr->ex_type = ET_VAR;
-                                tmp = eptr->ex_ptr;
-                                if (ex_getsym(tmp,
-                                                (t_symbol **)&(eptr->ex_ptr))) {
-                                        post("expr: variable '%s' not found",tmp);
-                                        return (exNULL);
-                                }
-                        }
-                        continue;
-                default:
-                        post("ex_match: bad type\n");
-                        return (exNULL);
-                }
-        }
-        /* NOTREACHED */
-}
-
-/*
- * ex_parse -- This function if called when we have already done some
- *             parsing on the expression, and we have already matched
- *             our brackets and parenthesis.  The main job of this
- *             function is to convert the infix expression to the
- *             prefix form. 
- *             First we find the operator with the lowest precedence and
- *             put it on the stack ('optr', it is really just an array), then
- *             we call ourself (ex_parse()), on its arguments (unary operators
- *             only have one operator.)  
- *             When "argc" is set it means that we are parsing the arguments
- *             of a function and we will increment *argc anytime we find
- *             a a segment that can qualify as an argument (counting commas).
- *
- *             returns 0 on syntax error
- */
-/* number of argument separated by comma */
-struct ex_ex *
-ex_parse(struct expr *x, struct ex_ex *iptr, struct ex_ex *optr, long int *argc)
-{
-        struct ex_ex *eptr;
-        struct ex_ex *lowpre = 0;       /* pointer to the lowest precedence */
-        struct ex_ex savex;
-        long pre = HI_PRE;
-        long count;
-
-        if (!iptr) {
-                post("ex_parse: input is null, iptr = 0x%lx\n", iptr);
-                return (exNULL);
-        }
-        if (!iptr->ex_type)
-                return (exNULL);
-
-        /*
-         * the following loop finds the lowest precedence operator in the
-         * the input token list, comma is explicitly checked here since
-         * that is a special operator and is only legal in functions
-         */
-        for (eptr = iptr, count = 0; eptr->ex_type; eptr++, count++)
-                switch (eptr->ex_type) {
-                case ET_SYM:
-                case ET_VSYM:
-                        if (!argc) {
-                                post("expr: syntax error: symbols allowed for functions only\n");
-                                ex_print(eptr);
-                                return (exNULL);
-                        }
-                case ET_INT:
-                case ET_FLT:
-                case ET_II:
-                case ET_FI:
-                case ET_XI0:
-                case ET_YOM1:
-                case ET_VI:
-                case ET_VAR:
-                        if (!count && !eptr[1].ex_type) {
-                                *optr++ = *eptr;
-                                return (optr);
-                        }
-                        break;
-                case ET_XI:
-                case ET_YO:
-                case ET_SI:
-                case ET_TBL:
-                        if (eptr[1].ex_type != ET_LB) {
-                                post("expr: syntax error: brackets missing\n");
-                                ex_print(eptr);
-                                return (exNULL);
-                        }
-                        /* if this table is the only token, parse the table */
-                        if (!count &&
-                            !((struct ex_ex *) eptr[1].ex_ptr)[1].ex_type) {
-                                savex = *((struct ex_ex *) eptr[1].ex_ptr);
-                                *((struct ex_ex *) eptr[1].ex_ptr) = nullex;
-                                *optr++ = *eptr;
-                                lowpre = ex_parse(x, &eptr[2], optr, (long *)0);
-                                *((struct ex_ex *) eptr[1].ex_ptr) = savex;
-                                return(lowpre);
-                        }
-                        eptr = (struct ex_ex *) eptr[1].ex_ptr;
-                        break;
-                case ET_OP:
-                        if (eptr->ex_op == OP_COMMA) {
-                                if (!argc || !count || !eptr[1].ex_type) {
-                                        post("expr: syntax error: illegal comma\n");
-                                        ex_print(eptr[1].ex_type ? eptr : iptr);
-                                        return (exNULL);
-                                }
-                        }
-                        if (!eptr[1].ex_type) {
-                                post("expr: syntax error: missing operand\n");
-                                ex_print(iptr);
-                                return (exNULL);
-                        }
-                        if ((eptr->ex_op & PRE_MASK) <= pre) {
-                                pre = eptr->ex_op & PRE_MASK;
-                                lowpre = eptr;
-                        }
-                        break;
-                case ET_FUNC:
-                        if (eptr[1].ex_type != ET_LP) {
-                                post("expr: ex_parse: no parenthesis\n");
-                                return (exNULL);
-                        }
-                        /* if this function is the only token, parse it */
-                        if (!count &&
-                            !((struct ex_ex *) eptr[1].ex_ptr)[1].ex_type) {
-                                long ac;
-
-                                if (eptr[1].ex_ptr == (char *) &eptr[2]) {
-                                        post("expr: syntax error: missing argument\n");
-                                        ex_print(eptr);
-                                        return (exNULL);
-                                }
-                                ac = 0;
-                                savex = *((struct ex_ex *) eptr[1].ex_ptr);
-                                *((struct ex_ex *) eptr[1].ex_ptr) = nullex;
-                                *optr++ = *eptr;
-                                lowpre = ex_parse(x, &eptr[2], optr, &ac);
-                                if (!lowpre)
-                                        return (exNULL);
-                                ac++;
-                                if (ac !=
-                                    ((t_ex_func *)eptr->ex_ptr)->f_argc){
-                                        post("expr: syntax error: function '%s' needs %ld arguments\n",
-                                            ((t_ex_func *)eptr->ex_ptr)->f_name,
-                                            ((t_ex_func *)eptr->ex_ptr)->f_argc);
-                                        return (exNULL);
-                                }
-                                *((struct ex_ex *) eptr[1].ex_ptr) = savex;
-                                return (lowpre);
-                        }
-                        eptr = (struct ex_ex *) eptr[1].ex_ptr;
-                        break;
-                case ET_LP:
-                case ET_LB:
-                        if (!count &&
-                            !((struct ex_ex *) eptr->ex_ptr)[1].ex_type) {
-                                if (eptr->ex_ptr == (char *)(&eptr[1])) {
-                                        post("expr: syntax error: empty '%s'\n",
-                                            eptr->ex_type==ET_LP?"()":"[]");
-                                        ex_print(eptr);
-                                        return (exNULL);
-                                }
-                                savex = *((struct ex_ex *) eptr->ex_ptr);
-                                *((struct ex_ex *) eptr->ex_ptr) = nullex;
-                                lowpre = ex_parse(x, &eptr[1], optr, (long *)0);
-                                *((struct ex_ex *) eptr->ex_ptr) = savex;
-                                return (lowpre);
-                        }
-                        eptr = (struct ex_ex *)eptr->ex_ptr;
-                        break;
-                case ET_STR:
-                default:
-                        ex_print(eptr);
-                        post("expr: ex_parse: type = 0x%lx\n", eptr->ex_type);
-                        return (exNULL);
-                }
-
-        if (pre == HI_PRE) {
-                post("expr: syntax error: missing operation\n");
-                ex_print(iptr);
-                return (exNULL);
-        }
-        if (count < 2) {
-                post("expr: syntax error: mission operand\n");
-                ex_print(iptr);
-                return (exNULL);
-        }
-        if (count == 2) {
-                if (lowpre != iptr) {
-                        post("expr: ex_parse: unary operator should be first\n");
-                        return (exNULL);
-                }
-                if (!unary_op(lowpre->ex_op)) {
-                        post("expr: syntax error: not a uniary operator\n");
-                        ex_print(iptr);
-                        return (exNULL);
-                }
-                *optr++ = *lowpre;
-                eptr = ex_parse(x, &lowpre[1], optr, argc);
-                return (eptr);
-        }
-        if (lowpre == iptr) {
-                post("expr: syntax error: mission operand\n");
-                ex_print(iptr);
-                return (exNULL);
-        }
-        savex = *lowpre;
-        *lowpre = nullex;
-        if (savex.ex_op != OP_COMMA)
-                *optr++ = savex;
-        else
-                (*argc)++;
-        eptr = ex_parse(x, iptr, optr, argc);
-        if (eptr) {
-                eptr = ex_parse(x, &lowpre[1], eptr, argc);
-                *lowpre = savex;
-        }
-        return (eptr);
-}
-
-/*
- * this is the devide zero check for a a non devide operator
- */
-#define DZC(ARG1,OPR,ARG2)      (ARG1 OPR ARG2)
-
-#define EVAL(OPR);                                                      \
-eptr = ex_eval(expr, ex_eval(expr, eptr, &left, idx), &right, idx);     \
-switch (left.ex_type) {                                                 \
-case ET_INT:                                                            \
-        switch(right.ex_type) {                                         \
-        case ET_INT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = (float)DZC(left.ex_int, OPR, right.ex_int); \
-                        for (j = 0; j < expr->exp_vsize; j++)           \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_INT;                         \
-                        optr->ex_int = DZC(left.ex_int, OPR, right.ex_int); \
-                }                                                       \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = DZC(((float)left.ex_int), OPR, right.ex_flt);\
-                        for (j = 0; j < expr->exp_vsize; j++)           \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_FLT;                         \
-                        optr->ex_flt = DZC(((float)left.ex_int), OPR,   \
-                                                        right.ex_flt);  \
-                }                                                       \
-                break;                                                  \
-        case ET_VEC:                                                    \
-        case ET_VI:                                                     \
-                if (optr->ex_type != ET_VEC) {                          \
-                        if (optr->ex_type == ET_VI) {                   \
-                                post("expr~: Int. error %d", __LINE__); \
-                                abort();                                \
-                        }                                               \
-                        optr->ex_type = ET_VEC;                         \
-                        optr->ex_vec = (t_float *)                      \
-                          fts_malloc(sizeof (t_float)*expr->exp_vsize); \
-                }                                                       \
-                scalar = left.ex_int;                                   \
-                rp = right.ex_vec;                                      \
-                op = optr->ex_vec;                                      \
-                for (i = 0; i < expr->exp_vsize; i++) {                 \
-                        *op++ = DZC (scalar, OPR, *rp);                 \
-                        rp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_SYM:                                                    \
-        default:                                                        \
-                post_error((fts_object_t *) expr,                       \
-                      "expr: ex_eval(%d): bad right type %ld\n",        \
-                                              __LINE__, right.ex_type); \
-                nullret = 1;                                            \
-        }                                                               \
-        break;                                                          \
-case ET_FLT:                                                            \
-        switch(right.ex_type) {                                         \
-        case ET_INT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = DZC((float) left.ex_flt, OPR, right.ex_int); \
-                        for (j = 0; j < expr->exp_vsize; j++)           \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_FLT;                         \
-                        optr->ex_flt = DZC(left.ex_flt, OPR, right.ex_int); \
-                }                                                       \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = DZC(left.ex_flt, OPR, right.ex_flt);   \
-                        for (j = 0; j < expr->exp_vsize; j++)           \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_FLT;                         \
-                        optr->ex_flt= DZC(left.ex_flt, OPR, right.ex_flt); \
-                }                                                       \
-                break;                                                  \
-        case ET_VEC:                                                    \
-        case ET_VI:                                                     \
-                if (optr->ex_type != ET_VEC) {                          \
-                        if (optr->ex_type == ET_VI) {                   \
-                                post("expr~: Int. error %d", __LINE__); \
-                                abort();                                \
-                        }                                               \
-                        optr->ex_type = ET_VEC;                         \
-                        optr->ex_vec = (t_float *)                      \
-                          fts_malloc(sizeof (t_float)*expr->exp_vsize); \
-                }                                                       \
-                scalar = left.ex_flt;                                   \
-                rp = right.ex_vec;                                      \
-                op = optr->ex_vec;                                      \
-                for (i = 0; i < expr->exp_vsize; i++) {                 \
-                        *op++ = DZC(scalar, OPR, *rp);                  \
-                        rp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_SYM:                                                    \
-        default:                                                        \
-                post_error((fts_object_t *) expr,                       \
-                      "expr: ex_eval(%d): bad right type %ld\n",        \
-                                              __LINE__, right.ex_type); \
-                nullret = 1;                                            \
-        }                                                               \
-        break;                                                          \
-case ET_VEC:                                                            \
-case ET_VI:                                                             \
-        if (optr->ex_type != ET_VEC) {                                  \
-                if (optr->ex_type == ET_VI) {                           \
-                        post("expr~: Int. error %d", __LINE__);         \
-                        abort();                                        \
-                }                                                       \
-                optr->ex_type = ET_VEC;                                 \
-                optr->ex_vec = (t_float *)                              \
-                  fts_malloc(sizeof (t_float)*expr->exp_vsize);         \
-        }                                                               \
-        op = optr->ex_vec;                                              \
-        lp = left.ex_vec;                                               \
-        switch(right.ex_type) {                                         \
-        case ET_INT:                                                    \
-                scalar = right.ex_int;                                  \
-                for (i = 0; i < expr->exp_vsize; i++) {                 \
-                        *op++ = DZC(*lp, OPR, scalar);                  \
-                        lp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                scalar = right.ex_flt;                                  \
-                for (i = 0; i < expr->exp_vsize; i++) {                 \
-                        *op++ = DZC(*lp, OPR, scalar);                  \
-                        lp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_VEC:                                                    \
-        case ET_VI:                                                     \
-                rp = right.ex_vec;                                      \
-                for (i = 0; i < expr->exp_vsize; i++) {                 \
-                        /*                                              \
-                         * on a RISC processor one could copy           \
-                         * 8 times in each round to get a considerable  \
-                         * improvement                                  \
-                         */                                             \
-                        *op++ = DZC(*lp, OPR, *rp);                     \
-                        rp++; lp++;                                     \
-                }                                                       \
-                break;                                                  \
-        case ET_SYM:                                                    \
-        default:                                                        \
-                post_error((fts_object_t *) expr,                       \
-                      "expr: ex_eval(%d): bad right type %ld\n",        \
-                                              __LINE__, right.ex_type); \
-                nullret = 1;                                            \
-        }                                                               \
-        break;                                                          \
-case ET_SYM:                                                            \
-default:                                                                \
-                post_error((fts_object_t *) expr,                       \
-                      "expr: ex_eval(%d): bad left type %ld\n",         \
-                                              __LINE__, left.ex_type);  \
-}                                                                       \
-break;
-
-/*
- * evaluate a unary operator, TYPE is applied to float operands
- */
-#define EVAL_UNARY(OPR, TYPE)                                           \
-        eptr = ex_eval(expr, eptr, &left, idx);                         \
-        switch(left.ex_type) {                                          \
-        case ET_INT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        ex_mkvector(optr->ex_vec,(float)(OPR left.ex_int),\
-                                                        expr->exp_vsize);\
-                        break;                                          \
-                }                                                       \
-                optr->ex_type = ET_INT;                                 \
-                optr->ex_int = OPR left.ex_int;                         \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        ex_mkvector(optr->ex_vec, OPR (TYPE left.ex_flt),\
-                                                        expr->exp_vsize);\
-                        break;                                          \
-                }                                                       \
-                optr->ex_type = ET_FLT;                                 \
-                optr->ex_flt = OPR (TYPE left.ex_flt);                  \
-                break;                                                  \
-        case ET_VI:                                                     \
-        case ET_VEC:                                                    \
-                j = expr->exp_vsize;                                    \
-                if (optr->ex_type != ET_VEC) {                          \
-                        optr->ex_type = ET_VEC;                         \
-                        optr->ex_vec = (t_float *)                      \
-                          fts_malloc(sizeof (t_float)*expr->exp_vsize); \
-                }                                                       \
-                op = optr->ex_vec;                                      \
-                lp = left.ex_vec;                                       \
-                j = expr->exp_vsize;                                    \
-                for (i = 0; i < j; i++)                                 \
-                        *op++ = OPR (TYPE *lp++);                       \
-                break;                                                  \
-        default:                                                        \
-                post_error((fts_object_t *) expr,                       \
-                        "expr: ex_eval(%d): bad left type %ld\n",       \
-                                              __LINE__, left.ex_type);  \
-                nullret++;                                              \
-        }                                                               \
-        break;
-
-void
-ex_mkvector(t_float *fp, t_float x, int size)
-{
-        while (size--)
-                *fp++ = x;
-}
-
-/*
- * ex_dzdetect -- divide by zero detected
- */
-void
-ex_dzdetect(struct expr *expr)
-{
-        char *etype;
-
-        if (!expr->exp_error & EE_DZ) {
-                if (IS_EXPR(expr))
-                        etype = "expr";
-                else if (IS_EXPR_TILDE(expr))
-                        etype = "expr~";
-                else if (IS_FEXPR_TILDE(expr))
-                        etype = "fexpr~";
-                else {
-                        post ("expr -- ex_dzdetect internal error");
-                        etype = "";
-                }
-                post ("%s divide by zero detected", etype);
-                expr->exp_error |= EE_DZ;
-        }
-}
-                
-
-/*
- * ex_eval -- evaluate the array of prefix expression
- *            ex_eval returns the pointer to the first unevaluated node
- *            in the array.  This is a recursive routine.
- */
-
-/* SDY
-all the returns in this function need to be changed so that the code
-ends up at the end to check for newly allocated right and left vectors which
-need to be freed
-
-look into the variable nullret
-*/
-struct ex_ex *
-ex_eval(struct expr *expr, struct ex_ex *eptr, struct ex_ex *optr, int idx)
-/* the expr object data pointer */
-/* the operation stack */
-/* the result pointer */
-/* the sample numnber processed for fexpr~ */
-{
-        int i, j;
-        t_float *lp, *rp, *op; /* left, right, and out pointer to vectors */
-        t_float scalar;
-        int nullret = 0;                /* did we have an error */
-        struct ex_ex left, right;       /* left and right operands */
-
-        left.ex_type = 0;
-        left.ex_int = 0;
-        right.ex_type = 0;
-        right.ex_int = 0;
-
-        if (!eptr)
-                return (exNULL);
-        switch (eptr->ex_type) {
-        case ET_INT:
-                if (optr->ex_type == ET_VEC)
-                        ex_mkvector(optr->ex_vec, (float) eptr->ex_int,
-                                                                expr->exp_vsize);
-                else
-                        *optr = *eptr;
-                return (++eptr);
-
-        case ET_FLT:
-
-                if (optr->ex_type == ET_VEC)
-                        ex_mkvector(optr->ex_vec, eptr->ex_flt, expr->exp_vsize);
-                else
-                        *optr = *eptr;
-                return (++eptr);
-
-        case ET_SYM:
-                if (optr->ex_type == ET_VEC) {
-                        post_error((fts_object_t *) expr,
-                              "expr: ex_eval: cannot turn string to vector\n");
-                        return (exNULL);
-                }
-                *optr = *eptr;
-                return (++eptr);
-        case ET_II:
-                if (eptr->ex_int == -1) {
-                        post_error((fts_object_t *) expr,
-                            "expr: ex_eval: inlet number not set\n");
-                        return (exNULL);
-                }
-                if (optr->ex_type == ET_VEC) {
-                        ex_mkvector(optr->ex_vec,
-                               (t_float)expr->exp_var[eptr->ex_int].ex_int,
-                                                                expr->exp_vsize);
-                } else {
-                        optr->ex_type = ET_INT;
-                        optr->ex_int = expr->exp_var[eptr->ex_int].ex_int;
-                }
-                return (++eptr);
-        case ET_FI:
-                if (eptr->ex_int == -1) {
-                        post_error((fts_object_t *) expr,
-                            "expr: ex_eval: inlet number not set\n");
-                        return (exNULL);
-                }
-                if (optr->ex_type == ET_VEC) {
-                        ex_mkvector(optr->ex_vec,
-                             expr->exp_var[eptr->ex_int].ex_flt, expr->exp_vsize);
-                } else {
-                        optr->ex_type = ET_FLT;
-                        optr->ex_flt = expr->exp_var[eptr->ex_int].ex_flt;
-                }
-                return (++eptr);
-
-        case ET_VSYM:
-                if (optr->ex_type == ET_VEC) {
-                        post_error((fts_object_t *) expr,
-                            "expr: IntErr. vsym in for vec out\n");
-                        return (exNULL);
-                }
-                if (eptr->ex_int == -1) {
-                        post_error((fts_object_t *) expr,
-                                "expr: ex_eval: inlet number not set\n");
-                        return (exNULL);
-                }
-                optr->ex_type = ET_SYM;
-                optr->ex_ptr = expr->exp_var[eptr->ex_int].ex_ptr;
-                return(++eptr);
-
-        case ET_VI:
-                if (optr->ex_type != ET_VEC)
-                        *optr = expr->exp_var[eptr->ex_int];
-                else if (optr->ex_vec != expr->exp_var[eptr->ex_int].ex_vec)
-                        memcpy(optr->ex_vec, expr->exp_var[eptr->ex_int].ex_vec,
-                                        expr->exp_vsize * sizeof (t_float));
-                return(++eptr);
-        case ET_VEC:
-                if (optr->ex_type != ET_VEC) {
-                        optr->ex_type = ET_VEC;
-                        optr->ex_vec = eptr->ex_vec;
-                        eptr->ex_type = ET_INT;
-                        eptr->ex_int = 0;
-                } else if (optr->ex_vec != eptr->ex_vec) {
-                        memcpy(optr->ex_vec, eptr->ex_vec,
-                                        expr->exp_vsize * sizeof (t_float));
-/* do we need to free here? or can we free higher up */
-/* SDY  the next lines do not make sense */
-post("calling fts_free\n");
-abort();
-                        fts_free(optr->ex_vec);
-                        optr->ex_type = ET_INT;
-                        eptr->ex_int = 0;
-                } else { /* this should not happen */   
-                        post("expr int. error, optr->ex_vec = %d",optr->ex_vec);
-                        abort();
-                }
-                return(++eptr);
-        case ET_XI0:
-                /* short hand for $x?[0] */
-
-                /* SDY delete the following check */
-                if (!IS_FEXPR_TILDE(expr) || optr->ex_type==ET_VEC) {
-                        post("%d:exp->exp_flags = %d", __LINE__,expr->exp_flags);
-                        abort();
-                }
-                optr->ex_type = ET_FLT;
-                optr->ex_flt = expr->exp_var[eptr->ex_int].ex_vec[idx];
-                return(++eptr);
-        case ET_YOM1:
-                /*
-                 * short hand for $y?[-1]
-                 * if we are calculating the first sample of the vector
-                 * we need to look at the previous results buffer
-                 */
-                optr->ex_type = ET_FLT;
-                if (idx == 0)
-                        optr->ex_flt =
-                        expr->exp_p_res[eptr->ex_int][expr->exp_vsize - 1];
-                else
-                        optr->ex_flt=expr->exp_tmpres[eptr->ex_int][idx-1];
-                return(++eptr);
-                
-        case ET_YO:
-        case ET_XI:
-                /* SDY delete the following */
-                if (!IS_FEXPR_TILDE(expr) || optr->ex_type==ET_VEC) {
-                        post("%d:expr->exp_flags = %d", __LINE__,expr->exp_flags);
-                        abort();
-                }
-                return (eval_sigidx(expr, eptr, optr, idx));
-                        
-        case ET_TBL:
-        case ET_SI:
-                return (eval_tab(expr, eptr, optr, idx));
-        case ET_FUNC:
-                return (eval_func(expr, eptr, optr, idx));
-        case ET_VAR:
-                return (eval_var(expr, eptr, optr, idx));
-        case ET_OP:
-                break;
-        case ET_STR:
-        case ET_LP:
-        case ET_LB:
-        default:
-                post_error((fts_object_t *) expr,
-                        "expr: ex_eval: unexpected type %ld\n", eptr->ex_type);
-                return (exNULL);
-        }
-        if (!eptr[1].ex_type) {
-                post_error((fts_object_t *) expr,
-                                        "expr: ex_eval: not enough nodes 1\n");
-                return (exNULL);
-        }
-        if (!unary_op(eptr->ex_op) && !eptr[2].ex_type) {
-                post_error((fts_object_t *) expr,
-                                        "expr: ex_eval: not enough nodes 2\n");
-                return (exNULL);
-        }
-
-        switch((eptr++)->ex_op) {
-        case OP_STORE:
-                return (eval_store(expr, eptr, optr, idx));
-        case OP_NOT:
-                EVAL_UNARY(!, +);
-        case OP_NEG:
-                EVAL_UNARY(~, (long));
-        case OP_UMINUS:
-                EVAL_UNARY(-, +);
-        case OP_MUL:
-                EVAL(*);
-        case OP_ADD:
-                EVAL(+);
-        case OP_SUB:
-                EVAL(-);
-        case OP_LT:
-                EVAL(<);
-        case OP_LE:
-                EVAL(<=);
-        case OP_GT:
-                EVAL(>);
-        case OP_GE:
-                EVAL(>=);
-        case OP_EQ:
-                EVAL(==);
-        case OP_NE:
-                EVAL(!=);
-/*
- * following operators convert their argument to integer
- */
-#undef DZC
-#define DZC(ARG1,OPR,ARG2)      (((int)ARG1) OPR ((int)ARG2))
-        case OP_SL:
-                EVAL(<<);
-        case OP_SR:
-                EVAL(>>);
-        case OP_AND:
-                EVAL(&);
-        case OP_XOR:
-                EVAL(^);
-        case OP_OR:
-                EVAL(|);
-        case OP_LAND:
-                EVAL(&&);
-        case OP_LOR:
-                EVAL(||);
-/*
- * for modulo we need to convert to integer and check for divide by zero
- */
-#undef DZC
-#define DZC(ARG1,OPR,ARG2)      (((ARG2)?(((int)ARG1) OPR ((int)ARG2)) \
-                                                        : (ex_dzdetect(expr),0)))
-        case OP_MOD:
-                EVAL(%);
-/*
- * define the divide by zero check for divide
- */
-#undef DZC
-#define DZC(ARG1,OPR,ARG2)      (((ARG2)?(ARG1 OPR ARG2):(ex_dzdetect(expr),0)))
-        case OP_DIV:
-                EVAL(/);
-        case OP_LP:
-        case OP_RP:
-        case OP_LB:
-        case OP_RB:
-        case OP_COMMA:
-        case OP_SEMI:
-        default:
-                post_error((fts_object_t *) expr, "expr: ex_print: bad op 0x%lx\n", eptr->ex_op);
-                return (exNULL);
-        }
-
-
-        /*
-         * the left and right nodes could have been transformed to vectors
-         * down the chain
-         */
-        if (left.ex_type == ET_VEC)
-                fts_free(left.ex_vec);
-        if (right.ex_type == ET_VEC)
-                fts_free(right.ex_vec);
-        if (nullret)
-                return (exNULL);
-        else
-                return (eptr);
-}
-
-/*
- * eval_func --  evaluate a function, call ex_eval() on all the arguments
- *               so that all of them are terminal nodes. The call the
- *               appropriate function
- */
-struct ex_ex *
-eval_func(struct expr *expr, struct ex_ex *eptr, struct ex_ex *optr, int idx)
-/* the expr object data pointer */
-/* the operation stack */
-/* the result pointer */
-{
-        int i;
-        struct ex_ex args[MAX_ARGS];
-        t_ex_func *f;
-
-        f = (t_ex_func *)(eptr++)->ex_ptr;
-        if (!f || !f->f_name) {
-                return (exNULL);
-        }
-        if (f->f_argc > MAX_ARGS) {
-                post_error((fts_object_t *) expr, "expr: eval_func: asking too many arguments\n");
-                return (exNULL);
-        }
-
-        for (i = 0; i < f->f_argc; i++) {
-                args[i].ex_type = 0;
-                args[i].ex_int = 0;
-                eptr = ex_eval(expr, eptr, &args[i], idx);
-        }
-        (*f->f_func)(expr, f->f_argc, args, optr);
-        for (i = 0; i < f->f_argc; i++) {
-                if (args[i].ex_type == ET_VEC)
-                        fts_free(args[i].ex_vec);
-        }
-        return (eptr);
-}
-
-
-/*
- * eval_store --  evaluate the '=' operator, 
- *                make sure the first operator is a legal left operator
- *                and call ex_eval on the right operator
- */
-struct ex_ex *
-eval_store(struct expr *expr, struct ex_ex *eptr, struct ex_ex *optr, int idx)
-/* the expr object data pointer */
-/* the operation stack */
-/* the result pointer */
-{
-        struct ex_ex arg;
-        int isvalue;
-        char *tbl = (char *) 0;
-        char *var = (char *) 0;
-        int badleft = 0;
-
-post("store called\n");
-ex_print(eptr);
-eptr = ex_eval(expr, ++eptr, optr, idx);
-return (eptr);
-
-#ifdef notdef /* SDY */
-        arg.ex_type = ET_INT;
-        arg.ex_int = 0;
-        if (eptr->ex_type == ET_VAR) {
-                var = (char *) eptr->ex_ptr;
-
-                eptr = ex_eval(expr, ++eptr, &arg, idx);
-                (void)max_ex_var_store(expr, (t_symbol *)var, &arg, optr);
-                if (arg.ex_type == ET_VEC)
-                        fts_free(arg.ex_vec);
-        }
-
-
-        if (eptr->ex_type == ET_SI) {
-                eptr++;
-                if (eptr->ex_type =
-        }
-
-        /* the left operator should either be a value or a array member */
-        switch (eptr->ex_type) {
-        case ET_SI:
-                if ((eptr + 1)->ex_type == OP_LB) {
-                }
-                if (!expr->exp_var[eptr->ex_int].ex_ptr) {
-                                if (!(expr->exp_error & EE_NOTABLE)) {
-                                        post("expr: syntax error: no string for inlet %d", eptr->ex_int + 1);
-                                        post("expr: No more table errors will be reported");
-                                        post("expr: till the next reset");
-                                        expr->exp_error |= EE_NOTABLE;
-                                }
-                                badleft++;
-                } else
-                        tbl = (char *) expr->exp_var[eptr->ex_int].ex_ptr;
-                break;
-        case ET_TBL:
-        }
-#endif /* SDY */
-}
-
-/*
- * eval_tab -- evaluate a table operation
- */
-struct ex_ex *
-eval_tab(struct expr *expr, struct ex_ex *eptr, struct ex_ex *optr, int idx)
-/* the expr object data pointer */
-/* the operation stack */
-/* the result pointer */
-{
-        struct ex_ex arg;
-        char *tbl = (char *) 0;
-        int notable = 0;
-        
-        if (eptr->ex_type == ET_SI) {
-                if (!expr->exp_var[eptr->ex_int].ex_ptr) {
-/* SDY post_error() does not work in MAX/MSP yet
-                                post_error((fts_object_t *) expr,
-                                     "expr: syntax error: no string for inlet %d\n", eptr->ex_int + 1);
-*/
-                                if (!(expr->exp_error & EE_NOTABLE)) {
-                                        post("expr: syntax error: no string for inlet %d", eptr->ex_int + 1);
-                                        post("expr: No more table errors will be reported");
-                                        post("expr: till the next reset");
-                                        expr->exp_error |= EE_NOTABLE;
-                                }
-                                notable++;
-                } else
-                        tbl = (char *) expr->exp_var[eptr->ex_int].ex_ptr;
-        } else if (eptr->ex_type == ET_TBL)
-                tbl = (char *) eptr->ex_ptr;
-        else {
-                post_error((fts_object_t *) expr, "expr: eval_tbl: bad type %ld\n", eptr->ex_type);
-                notable++;
-
-        }
-        arg.ex_type = 0;
-        arg.ex_int = 0;
-        eptr = ex_eval(expr, ++eptr, &arg, idx);
-
-        optr->ex_type = ET_INT;
-        optr->ex_int = 0;
-        if (!notable)
-                (void)max_ex_tab(expr, (t_symbol *)tbl, &arg, optr);
-        if (arg.ex_type == ET_VEC)
-                fts_free(arg.ex_vec);
-        return (eptr);
-}
-
-/*
- * eval_var -- evaluate a variable
- */
-struct ex_ex *
-eval_var(struct expr *expr, struct ex_ex *eptr, struct ex_ex *optr, int idx)
-/* the expr object data pointer */
-/* the operation stack */
-/* the result pointer */
-{
-        struct ex_ex arg;
-        char *var = (char *) 0;
-        int novar = 0;
-        
-        if (eptr->ex_type == ET_SI) {
-                if (!expr->exp_var[eptr->ex_int].ex_ptr) {
-/* SDY post_error() does not work in MAX/MSP yet
-post_error((fts_object_t *) expr,
-"expr: syntax error: no string for inlet %d\n", eptr->ex_int + 1);
-*/
-                                if (!(expr->exp_error & EE_NOVAR)) {
-                                        post("expr: syntax error: no string for inlet %d", eptr->ex_int + 1);
-                                        post("expr: No more table errors will be reported");
-                                        post("expr: till the next reset");
-                                        expr->exp_error |= EE_NOVAR;
-                                }
-                                novar++;
-                } else
-                        var = (char *) expr->exp_var[eptr->ex_int].ex_ptr;
-        } else if (eptr->ex_type == ET_VAR)
-                var = (char *) eptr->ex_ptr;
-        else {
-                post_error((fts_object_t *) expr, "expr: eval_tbl: bad type %ld\n", eptr->ex_type);
-                novar++;
-
-        }
-
-        optr->ex_type = ET_INT;
-        optr->ex_int = 0;
-        if (!novar)
-                (void)max_ex_var(expr, (t_symbol *)var, optr);
-        return (++eptr);
-}
-
-/*
- * eval_sigidx -- evaluate the value of an indexed signal for fexpr~
- */
-struct ex_ex *
-eval_sigidx(struct expr *expr, struct ex_ex *eptr, struct ex_ex *optr, int idx)
-/* the expr object data pointer */
-/* the operation stack */
-/* the result pointer */
-/* the index */
-{
-        struct ex_ex arg;
-        struct ex_ex *reteptr;
-        int i = 0, j = 0;
-        float fi = 0,           /* index in float */
-              rem_i = 0;        /* remains of the float */
-        char *tbl;
-
-        arg.ex_type = 0;
-        arg.ex_int = 0;
-        reteptr = ex_eval(expr, eptr + 1, &arg, idx);
-        if (arg.ex_type == ET_FLT) {
-                fi = arg.ex_flt;                /* float index */
-                i = (int) arg.ex_flt;           /* integer index */
-                rem_i =  arg.ex_flt - i;        /* remains of integer */
-        } else if (arg.ex_type == ET_INT) {
-                fi = arg.ex_int;                /* float index */
-                i = arg.ex_int;
-                rem_i = 0;
-        } else {
-                post("eval_sigidx: bad res type (%d)", arg.ex_type);
-        }
-        optr->ex_type = ET_FLT;
-        /*
-         * indexing an input vector
-         */
-        if (eptr->ex_type == ET_XI) {
-                if (fi > 0) {
-                        if (!(expr->exp_error & EE_BI_INPUT)) {
-                                expr->exp_error |= EE_BI_INPUT;
-                          post("expr: input vector index > 0, (vector x%d[%f])",
-                                               eptr->ex_int + 1, i + rem_i);
-                                post("fexpr~: index assumed to be = 0");
-                                post("fexpr~: no error report till next reset");
-                                ex_print(eptr);
-                        }
-                        /* just replace it with zero */
-                        i = 0;
-                        rem_i = 0;
-                }
-                if (cal_sigidx(optr, i, rem_i, idx, expr->exp_vsize,
-                                        expr->exp_var[eptr->ex_int].ex_vec,
-                                                expr->exp_p_var[eptr->ex_int])) {
-                        if (!(expr->exp_error & EE_BI_INPUT)) {
-                                expr->exp_error |= EE_BI_INPUT;
-                                post("expr: input vector index <  -VectorSize, (vector x%d[%f])", eptr->ex_int + 1, fi);
-                                ex_print(eptr);
-                                post("fexpr~: index assumed to be = -%d",
-                                        expr->exp_vsize);
-                                post("fexpr~: no error report till next reset");
-                        }
-                }
-
-        /*
-         * indexing an output vector
-         */
-        } else if (eptr->ex_type == ET_YO) {
-                /* for output vectors index of zero is not legal */
-                if (fi >= 0) {
-                        if (!(expr->exp_error & EE_BI_OUTPUT)) {
-                                expr->exp_error |= EE_BI_OUTPUT;
-                                post("fexpr~: bad output index, (%f)", fi);
-                                ex_print(eptr);
-                                post("fexpr~: no error report till next reset");
-                                post("fexpr~: index assumed to be = -1");
-                        }
-                        i = -1;
-                }
-                if (eptr->ex_int >= expr->exp_nexpr) {
-                        post("fexpr~: $y%d illegal: not that many exprs",
-                                                                eptr->ex_int);
-                        optr->ex_flt = 0;
-                        return (reteptr);
-                }
-                if (cal_sigidx(optr, i, rem_i, idx, expr->exp_vsize,
-                             expr->exp_tmpres[eptr->ex_int],
-                                                expr->exp_p_res[eptr->ex_int])) {
-                        if (!(expr->exp_error & EE_BI_OUTPUT)) {
-                                expr->exp_error |= EE_BI_OUTPUT;
-                                post("fexpr~: bad output index, (%f)", fi);
-                                ex_print(eptr);
-                                post("fexpr~: index assumed to be = -%d",
-                                        expr->exp_vsize);
-                        }
-                }
-        } else {
-                optr->ex_flt = 0;
-                post("fexpr~:eval_sigidx: internal error - unknown vector (%d)",
-                                                                eptr->ex_type);
-        }
-        return (reteptr);
-}
-
-/*
- * cal_sigidx -- given two tables (one current one previous) calculate an
- *               evaluation of a float index into the vectors by linear
- *               interpolation
- *              return 0 on success, 1 on failure (index out of bound)
- */
-static int
-cal_sigidx(struct ex_ex *optr,  /* The output value */
-           int i, float rem_i,  /* integer and fractinal part of index */
-           int idx,             /* index of current fexpr~ processing */
-           int vsize,           /* vector size */
-           float *curvec, float *prevec)        /* current and previous table */
-{
-        int n;
-
-        n = i + idx;
-        if (n > 0) {
-                /* from the curvec */
-                if (rem_i)
-                        optr->ex_flt = curvec[n] +
-                                        rem_i * (curvec[n] - curvec[n - 1]);
-                else
-                        optr->ex_flt = curvec[n];
-                return (0);
-        }
-        if (n == 0) {
-                /*
-                 * this is the case that the remaining float
-                 * is between two tables
-                 */
-                if (rem_i)
-                        optr->ex_flt = *curvec +
-                                        rem_i * (*curvec - prevec[vsize - 1]);
-                else
-                        optr->ex_flt = *curvec;
-                return (0);
-        }
-        /* find the index in the saved buffer */
-        n = vsize + n;
-        if (n > 0) {
-                if (rem_i)
-                        optr->ex_flt = prevec[n] +
-                                        rem_i * (prevec[n] - prevec[n - 1]);
-                else
-                        optr->ex_flt = prevec[n];
-                return (0);
-        }
-        /* out of bound */
-        optr->ex_flt = *prevec;
-        return (1);
-}
-
-/*
- * getoken -- return 1 on syntax error otherwise 0
- */
-int
-getoken(struct expr *expr, struct ex_ex *eptr)
-{
-        char *p;
-        long i;
-
-
-        if (!expr->exp_str) {
-                post("expr: getoken: expression string not set\n");
-                return (0);
-        }
-retry:
-        if (!*expr->exp_str) {
-                eptr->ex_type = 0;
-                eptr->ex_int = 0;
-                return (0);
-        }
-        if (*expr->exp_str == ';') {
-                expr->exp_str++;
-                eptr->ex_type = 0;
-                eptr->ex_int = 0;
-                return (0);
-        }
-        eptr->ex_type = ET_OP;
-        switch (*expr->exp_str++) {
-        case '\\':
-        case ' ':
-        case '\t':
-                goto retry;
-        case ';':
-                post("expr: syntax error: ';' not implemented\n");
-                return (1);
-        case ',':
-                eptr->ex_op = OP_COMMA;
-                break;
-        case '(':
-                eptr->ex_op = OP_LP;
-                break;
-        case ')':
-                eptr->ex_op = OP_RP;
-                break;
-        case ']':
-                eptr->ex_op = OP_RB;
-                break;
-        case '~':
-                eptr->ex_op = OP_NEG;
-                break;
-                /* we will take care of unary minus later */
-        case '*':
-                eptr->ex_op = OP_MUL;
-                break;
-        case '/':
-                eptr->ex_op = OP_DIV;
-                break;
-        case '%':
-                eptr->ex_op = OP_MOD;
-                break;
-        case '+':
-                eptr->ex_op = OP_ADD;
-                break;
-        case '-':
-                eptr->ex_op = OP_SUB;
-                break;
-        case '^':
-                eptr->ex_op = OP_XOR;
-                break;
-        case '[':
-                eptr->ex_op = OP_LB;
-                break;
-        case '!':
-                if (*expr->exp_str == '=') {
-                        eptr->ex_op = OP_NE;
-                        expr->exp_str++;
-                } else
-                        eptr->ex_op = OP_NOT;
-                break;
-        case '<':
-                switch (*expr->exp_str) {
-                case '<':
-                        eptr->ex_op = OP_SL;
-                        expr->exp_str++;
-                        break;
-                case '=':
-                        eptr->ex_op = OP_LE;
-                        expr->exp_str++;
-                        break;
-                default:
-                        eptr->ex_op = OP_LT;
-                        break;
-                }
-                break;
-        case '>':
-                switch (*expr->exp_str) {
-                case '>':
-                        eptr->ex_op = OP_SR;
-                        expr->exp_str++;
-                        break;
-                case '=':
-                        eptr->ex_op = OP_GE;
-                        expr->exp_str++;
-                        break;
-                default:
-                        eptr->ex_op = OP_GT;
-                        break;
-                }
-                break;
-        case '=':
-                if (*expr->exp_str++ != '=') {
-                        post("expr: syntax error: =\n");
-                        return (1);
-                }
-                eptr->ex_op = OP_EQ;
-                break;
-/* do not allow the store till the function is fixed
-                if (*expr->exp_str != '=')
-                        eptr->ex_op = OP_STORE;
-                else {
-                        expr->exp_str++;
-                        eptr->ex_op = OP_EQ;
-                }
-                break;
-*/
-
-        case '&':
-                if (*expr->exp_str == '&') {
-                        expr->exp_str++;
-                        eptr->ex_op = OP_LAND;
-                } else
-                        eptr->ex_op = OP_AND;
-                break;
-
-        case '|':
-                if ((*expr->exp_str == '|')) {
-                        expr->exp_str++;
-                        eptr->ex_op = OP_LOR;
-                } else
-                        eptr->ex_op = OP_OR;
-                break;
-        case '$':
-                switch (*expr->exp_str++) {
-                case 'I':
-                case 'i':
-                        eptr->ex_type = ET_II;
-                        break;
-                case 'F':
-                case 'f':
-                        eptr->ex_type = ET_FI;
-                        break;
-                case 'S':
-                case 's':
-                        eptr->ex_type = ET_SI;
-                        break;
-                case 'V':
-                case 'v':
-                        if (IS_EXPR_TILDE(expr)) {
-                                eptr->ex_type = ET_VI;
-                                break;
-                        }
-                        post("$v? works only for expr~");
-                        post("expr: syntax error: %s\n", &expr->exp_str[-2]);
-                        return (1);
-                case 'X':
-                case 'x':
-                        if (IS_FEXPR_TILDE(expr)) {
-                                eptr->ex_type = ET_XI;
-                                if (isdigit(*expr->exp_str))
-                                        break;
-                                /* for $x[] is a shorhand for $x1[] */
-                                eptr->ex_int = 0;
-                                goto noinletnum;
-                        }
-                        post("$x? works only for fexpr~");
-                        post("expr: syntax error: %s\n", &expr->exp_str[-2]);
-                        return (1);
-                case 'y':
-                case 'Y':
-                        if (IS_FEXPR_TILDE(expr)) {
-                                eptr->ex_type = ET_YO;
-                                /*$y takes no number */
-                                if (isdigit(*expr->exp_str))
-                                        break;
-                                /* for $y[] is a shorhand for $y1[] */
-                                eptr->ex_int = 0;
-                                goto noinletnum;
-                        }
-                        post("$y works only for fexpr~");
-                default:
-                        post("expr: syntax error: %s\n", &expr->exp_str[-2]);
-                        return (1);
-                }
-                p = atoif(expr->exp_str, &eptr->ex_op, &i);
-                if (!p) {
-                        post("expr: syntax error: %s\n", &expr->exp_str[-2]);
-                        return (1);
-                }
-                if (i != ET_INT) {
-                        post("expr: syntax error: %s\n", expr->exp_str);
-                        return (1);
-                }
-                /*
-                 * make the user inlets one based rather than zero based
-                 * therefore we decrement the number that user has supplied
-                 */
-                if (!eptr->ex_op || (eptr->ex_op)-- > MAX_VARS) {
-                 post("expr: syntax error: inlet or outlet out of range: %s\n",
-                                                             expr->exp_str);
-                        return (1);
-                }
-
-                /*
-                 * until we can change the input type of inlets on
-                 * the fly (at pd_new()
-                 * time) the first input to expr~ is always a vectore
-                 * and $f1 or $i1 is
-                 * illegal for fexr~
-                 */
-                if (eptr->ex_op == 0 &&
-                   (IS_FEXPR_TILDE(expr) ||  IS_EXPR_TILDE(expr)) &&
-                   (eptr->ex_type==ET_II || eptr->ex_type==ET_FI ||
-                                                        eptr->ex_type==ET_SI)) {
-                       post("first inlet of expr~/fexpr~ can only be a vector");
-                       return (1);
-                }
-                /* record the inlet or outlet type and check for consistency */
-                if (eptr->ex_type == ET_YO ) {
-                        /* it is an outlet  for fexpr~*/
-                        /* no need to do anything */
-                        ;
-                } else if (!expr->exp_var[eptr->ex_op].ex_type)
-                        expr->exp_var[eptr->ex_op].ex_type = eptr->ex_type;
-                else if (expr->exp_var[eptr->ex_op].ex_type != eptr->ex_type) {
-                        post("expr: syntax error: inlets can only have one type: %s\n", expr->exp_str);
-                        return (1);
-                }
-                expr->exp_str = p;
-noinletnum:
-                break;
-        case '"':
-                {
-                        struct ex_ex ex;
-
-                        p = expr->exp_str;
-                        if (!*expr->exp_str || *expr->exp_str == '"') {
-                                post("expr: syntax error: empty symbol: %s\n", --expr->exp_str);
-                                return (1);
-                        }
-                        if (getoken(expr, &ex))
-                                return (1);
-                        switch (ex.ex_type) {
-                        case ET_STR:
-                                if (ex_getsym(ex.ex_ptr, (t_symbol **)&(eptr->ex_ptr))) {
-                                        post("expr: syntax error: getoken: problms with ex_getsym\n");
-                                        return (1);
-                                }
-                                eptr->ex_type = ET_SYM;
-                                break;
-                        case ET_SI:
-                                *eptr = ex;
-                                eptr->ex_type = ET_VSYM;
-                                break;
-                        default:
-                                post("expr: syntax error: bad symbol name: %s\n", p);
-                                return (1);
-                        }
-                        if (*expr->exp_str++ != '"') {
-                                post("expr: syntax error: missing '\"'\n");
-                                return (1);
-                        }
-                        break;
-                }
-        case '.':
-        case '0':
-        case '1':
-        case '2':
-        case '3':
-        case '4':
-        case '5':
-        case '6':
-        case '7':
-        case '8':
-        case '9':
-                p = atoif(--expr->exp_str, &eptr->ex_int, &eptr->ex_type);
-                if (!p)
-                        return (1);
-                expr->exp_str = p;
-                break;
-
-        default:
-                /*
-                 * has to be a string, it should either be a 
-                 * function or a table 
-                 */
-                p = --expr->exp_str;
-                for (i = 0; name_ok(*p); i++)
-                        p++;
-                if (!i) {
-                        post("expr: syntax error: %s\n", expr->exp_str);
-                        return (1);
-                }
-                eptr->ex_ptr = (char *)fts_malloc(i + 1);
-                strncpy(eptr->ex_ptr, expr->exp_str, (int) i);
-                (eptr->ex_ptr)[i] = 0;
-                expr->exp_str = p;
-                /*
-                 * we mark this as a string and later we will change this
-                 * to either a function or a table
-                 */
-                eptr->ex_type = ET_STR;
-                break;
-        }
-        return (0);
-}
-
-/*
- * atoif -- ascii to float or integer (understands hex numbers also)
- */
-char *
-atoif(char *s, long int *value, long int *type)
-{
-        char *p;
-        long int_val = 0;
-        int flt = 0;
-        float pos = 0;
-        float flt_val = 0;
-        int base = 10;
-
-        p = s;
-        if (*p == '0' && (p[1] == 'x' || p[1] == 'X')) {
-                base = 16;
-                p += 2;
-        }
-        while (8) {
-                switch (*p) {
-                case '.':
-                        if (flt || base != 10) {
-                                post("expr: syntax error: %s\n", s);
-                                return ((char *) 0);
-                        }
-                        flt++;
-                        pos = 10;
-                        flt_val = int_val;
-                        break;
-                case '0':
-                case '1':
-                case '2':
-                case '3':
-                case '4':
-                case '5':
-                case '6':
-                case '7':
-                case '8':
-                case '9':
-                        if (flt) {
-                                flt_val += (*p - '0') / pos;
-                                pos *= 10;
-                        } else {
-                                int_val *= base;
-                                int_val += (*p - '0');
-                        }
-                        break;
-                case 'a':
-                case 'b':
-                case 'c':
-                case 'd':
-                case 'e':
-                case 'f':
-                        if (base != 16 || flt) {
-                                post("expr: syntax error: %s\n", s);
-                                return ((char *) 0);
-                        }
-                        int_val *= base;
-                        int_val += (*p - 'a' + 10);
-                        break;
-                case 'A':
-                case 'B':
-                case 'C':
-                case 'D':
-                case 'E':
-                case 'F':
-                        if (base != 16 || flt) {
-                                post("expr: syntax error: %s\n", s);
-                                return ((char *) 0);
-                        }
-                        int_val *= base;
-                        int_val += (*p - 'A' + 10);
-                        break;
-                default:
-                        if (flt) {
-                                *type = ET_FLT;
-                                *((float *) value) = flt_val;
-                        } else {
-                                *type = ET_INT;
-                                *value = int_val;
-                        }
-                        return (p);
-                }
-                p++;
-        }
-}
-
-/*
- * find_func -- returns a pointer to the found function structure
- *              otherwise it returns 0
- */
-t_ex_func *
-find_func(char *s)
-{
-        t_ex_func *f;
-
-        for (f = ex_funcs; f->f_name; f++)
-                if (!strcmp(f->f_name, s))
-                        return (f);
-        return ((t_ex_func *) 0);
-}
-
-
-/*
- * ex_print -- print an expression array
- */
-
-void
-ex_print(struct ex_ex *eptr)
-{
-
-        while (eptr->ex_type) {
-                switch (eptr->ex_type) {
-                case ET_INT:
-                        post("%ld ", eptr->ex_int);
-                        break;
-                case ET_FLT:
-                        post("%f ", eptr->ex_flt);
-                        break;
-                case ET_STR:
-                        post("%s ", eptr->ex_ptr);
-                        break;
-                case ET_TBL:
-                case ET_VAR:
-                        post("%s ", ex_symname((fts_symbol_t )eptr->ex_ptr));
-                        break;
-                case ET_SYM:
-                        post("\"%s\" ", ex_symname((fts_symbol_t )eptr->ex_ptr));
-                        break;
-                case ET_VSYM:
-                        post("\"$s%ld\" ", eptr->ex_int + 1);
-                        break;
-                case ET_FUNC:
-                        post("%s ",
-                            ((t_ex_func *)eptr->ex_ptr)->f_name);
-                        break;
-                case ET_LP:
-                        post("%c", '(');
-                        break;
-                        /* CHANGE
-                 case ET_RP:
-                         post("%c ", ')');
-                         break;
-                         */
-                case ET_LB:
-                        post("%c", '[');
-                        break;
-                        /* CHANGE
-                case ET_RB:
-                         post("%c ", ']');
-                         break;
-                         */
-                case ET_II:
-                        post("$i%ld ", eptr->ex_int + 1);
-                        break;
-                case ET_FI:
-                        post("$f%ld ", eptr->ex_int + 1);
-                        break;
-                case ET_SI:
-                        post("$s%lx ", eptr->ex_ptr);
-                        break;
-                case ET_VI:
-                        post("$v%lx ", eptr->ex_vec);
-                        break;
-                case ET_VEC:
-                        post("vec = %ld ", eptr->ex_vec);
-                        break;
-                case ET_YOM1:
-                case ET_YO:
-                        post("$y%d", eptr->ex_int + 1);
-                        break;
-                case ET_XI:
-                case ET_XI0:
-                        post("$x%d", eptr->ex_int + 1);
-                        break;
-                case ET_OP:
-                        switch (eptr->ex_op) {
-                        case OP_LP:
-                                post("%c", '(');
-                                break;
-                        case OP_RP:
-                                post("%c ", ')');
-                                break;
-                        case OP_LB:
-                                post("%c", '[');
-                                break;
-                        case OP_RB:
-                                post("%c ", ']');
-                                break;
-                        case OP_NOT:
-                                post("%c", '!');
-                                break;
-                        case OP_NEG:
-                                post("%c", '~');
-                                break;
-                        case OP_UMINUS:
-                                post("%c", '-');
-                                break;
-                        case OP_MUL:
-                                post("%c", '*');
-                                break;
-                        case OP_DIV:
-                                post("%c", '/');
-                                break;
-                        case OP_MOD:
-                                post("%c", '%');
-                                break;
-                        case OP_ADD:
-                                post("%c", '+');
-                                break;
-                        case OP_SUB:
-                                post("%c", '-');
-                                break;
-                        case OP_SL:
-                                post("%s", "<<");
-                                break;
-                        case OP_SR:
-                                post("%s", ">>");
-                                break;
-                        case OP_LT:
-                                post("%c", '<');
-                                break;
-                        case OP_LE:
-                                post("%s", "<=");
-                                break;
-                        case OP_GT:
-                                post("%c", '>');
-                                break;
-                        case OP_GE:
-                                post("%s", ">=");
-                                break;
-                        case OP_EQ:
-                                post("%s", "==");
-                                break;
-                        case OP_STORE:
-                                post("%s", "=");
-                                break;
-                        case OP_NE:
-                                post("%s", "!=");
-                                break;
-                        case OP_AND:
-                                post("%c", '&');
-                                break;
-                        case OP_XOR:
-                                post("%c", '^');
-                                break;
-                        case OP_OR:
-                                post("%c", '|');
-                                break;
-                        case OP_LAND:
-                                post("%s", "&&");
-                                break;
-                        case OP_LOR:
-                                post("%s", "||");
-                                break;
-                        case OP_COMMA:
-                                post("%c", ',');
-                                break;
-                        case OP_SEMI:
-                                post("%c", ';');
-                                break;
-                        default:
-                                post("expr: ex_print: bad op 0x%lx\n", eptr->ex_op);
-                        }
-                        break;
-                default:
-                        post("expr: ex_print: bad type 0x%lx\n", eptr->ex_type);
-                }
-                eptr++;
-        }
-        post("\n");
-}
-
-#ifdef NT
-void ABORT( void) {bug("expr");}
-#endif
diff --git a/extra/expr~/vexp.h b/extra/expr~/vexp.h
deleted file mode 100644
index 92dfb06ef..000000000
--- a/extra/expr~/vexp.h
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * jMax
- * Copyright (C) 1994, 1995, 1998, 1999 by IRCAM-Centre Georges Pompidou, Paris, France.
- * 
- * 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.
- * 
- * See file LICENSE for further informations on licensing terms.
- * 
- * 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.
- * 
- * Based on Max/ISPW by Miller Puckette.
- *
- * Authors: Maurizio De Cecco, Francois Dechelle, Enzo Maggi, Norbert Schnell.
- *
- */
-
-/* "expr" was written by Shahrokh Yadegari c. 1989. -msp */
-/* "expr~" and "fexpr~" conversion by Shahrokh Yadegari c. 1999,2000 */
-
-#define MSP
-#ifdef PD
-#undef MSP
-#endif
-
-#ifdef PD
-#include "m_pd.h"
-#else /* MSP */
-#include "ext.h"
-#include "z_dsp.h"
-#endif
-
-#include "fts_to_pd.h"
-/* This is put in fts_to_pd.h
-
-#ifdef MSP
-#define t_atom  Atom
-#define t_symbol Symbol
-#define pd_new(x)       newobject(x);
-#define t_outlet void
-#endif
-*/
-
-/*
- * Currently the maximum number of variables (inlets) that are supported
- * is 10.
- */
-
-#define MAX_VARS        9
-#define MINODES         10 /* was 200 */
-
-/* terminal defines */
-
-/*
- * operations
- * (x<<16|y) x defines the level of precedence,
- * the lower the number the lower the precedence
- * separators are defines as operators just for convenience
- */
-
-#define OP_SEMI         ((long)(1<<16|1))               /* ; */
-#define OP_COMMA        ((long)(2<<16|2))               /* , */
-#define OP_LOR          ((long)(3<<16|3))               /* || */
-#define OP_LAND         ((long)(4<<16|4))               /* && */
-#define OP_OR           ((long)(5<<16|5))               /* | */
-#define OP_XOR          ((long)(6<<16|6))               /* ^ */
-#define OP_AND          ((long)(7<<16|7))               /* & */
-#define OP_NE           ((long)(8<<16|8))               /* != */
-#define OP_EQ           ((long)(8<<16|9))               /* == */
-#define OP_GE           ((long)(9<<16|10))              /* >= */
-#define OP_GT           ((long)(9<<16|11))              /* > */
-#define OP_LE           ((long)(9<<16|12))              /* <= */
-#define OP_LT           ((long)(9<<16|13))              /* < */
-#define OP_SR           ((long)(10<<16|14))             /* >> */
-#define OP_SL           ((long)(10<<16|15))             /* << */
-#define OP_SUB          ((long)(11<<16|16))             /* - */
-#define OP_ADD          ((long)(11<<16|17))             /* + */
-#define OP_MOD          ((long)(12<<16|18))             /* % */
-#define OP_DIV          ((long)(12<<16|19))             /* / */
-#define OP_MUL          ((long)(12<<16|20))             /* * */
-#define OP_UMINUS       ((long)(13<<16|21))             /* - unary minus */
-#define OP_NEG          ((long)(13<<16|22))             /* ~ one complement */
-#define OP_NOT          ((long)(13<<16|23))             /* ! */
-#define OP_RB           ((long)(14<<16|24))             /* ] */
-#define OP_LB           ((long)(14<<16|25))             /* [ */
-#define OP_RP           ((long)(14<<16|26))             /* ) */
-#define OP_LP           ((long)(14<<16|27))             /* ( */
-#define OP_STORE        ((long)(15<<16|28))             /* = */
-#define HI_PRE          ((long)(100<<16))       /* infinite precedence */
-#define PRE_MASK        ((long)0xffff0000)      /* precedence level mask */
-
-struct ex_ex;
-
-#define name_ok(c)      (((c)=='_') || ((c)>='a' && (c)<='z') || \
-                        ((c)>='A' && (c)<='Z') || ((c) >= '0' && (c) <= '9'))
-#define unary_op(x)     ((x) == OP_NOT || (x) == OP_NEG || (x) == OP_UMINUS)
-
-struct ex_ex {
-        union {
-                long v_int;
-                float v_flt;
-                t_float *v_vec;         /* this is an for allocated vector */
-                long op;
-                char *ptr;
-        } ex_cont;              /* content */
-#define ex_int          ex_cont.v_int
-#define ex_flt          ex_cont.v_flt
-#define ex_vec          ex_cont.v_vec
-#define ex_op           ex_cont.op
-#define ex_ptr          ex_cont.ptr
-        long ex_type;           /* type of the node */
-};
-#define exNULL  ((struct ex_ex *)0)
-
-/* defines for ex_type */
-#define ET_INT          1               /* an int */
-#define ET_FLT          2               /* a float */
-#define ET_OP           3               /* operator */
-#define ET_STR          4               /* string */
-#define ET_TBL          5               /* a table, the content is a pointer */
-#define ET_FUNC         6               /* a function */
-#define ET_SYM          7               /* symbol ("string") */
-#define ET_VSYM         8               /* variable symbol ("$s?") */
-                                /* we treat parenthesis and brackets */
-                                /* special to keep a pointer to their */
-                                /* match in the content */
-#define ET_LP           9               /* left parenthesis */
-#define ET_LB           10              /* left bracket */
-#define ET_II           11              /* and integer inlet */
-#define ET_FI           12              /* float inlet */
-#define ET_SI           13              /* string inlet */
-#define ET_VI           14              /* signal inlet */
-#define ET_VEC          15              /* allocated signal vector */
-                                /* special types for fexpr~ */
-#define ET_YO           16              /* vector output for fexpr~ */
-#define ET_YOM1         17              /* shorthand for $y?[-1] */
-#define ET_XI           18              /* vector input for fexpr~ */
-#define ET_XI0          20              /* shorthand for $x?[0] */
-#define ET_VAR          21              /* variable */
-
-/* defines for ex_flags */
-#define EF_TYPE_MASK    0x07    /* first three bits define the type of expr */
-#define EF_EXPR         0x01    /* expr  - control in and out */
-#define EF_EXPR_TILDE   0x02    /* expr~ signal and control in, signal out */
-#define EF_FEXPR_TILDE  0x04    /* fexpr~ filter expression */
-
-#define EF_STOP         0x08    /* is it stopped used for expr~ and fexpr~ */
-#define EF_VERBOSE      0x10    /* verbose mode */
-
-#define IS_EXPR(x)        ((((x)->exp_flags&EF_TYPE_MASK)|EF_EXPR) == EF_EXPR)
-#define IS_EXPR_TILDE(x)  \
-                 ((((x)->exp_flags&EF_TYPE_MASK)|EF_EXPR_TILDE)==EF_EXPR_TILDE)
-#define IS_FEXPR_TILDE(x) \
-               ((((x)->exp_flags&EF_TYPE_MASK)|EF_FEXPR_TILDE)==EF_FEXPR_TILDE)
-
-#define SET_EXPR(x)     (x)->exp_flags |= EF_EXPR; \
-                        (x)->exp_flags &= ~EF_EXPR_TILDE;  \
-                        (x)->exp_flags &= ~EF_FEXPR_TILDE; 
-
-#define SET_EXPR_TILDE(x)       (x)->exp_flags &= ~EF_EXPR; \
-                                (x)->exp_flags |= EF_EXPR_TILDE;  \
-                                (x)->exp_flags &= ~EF_FEXPR_TILDE; 
-
-#define SET_FEXPR_TILDE(x)      (x)->exp_flags &= ~EF_EXPR; \
-                                (x)->exp_flags &= ~EF_EXPR_TILDE;  \
-                                (x)->exp_flags |= EF_FEXPR_TILDE; 
-
-/*
- * defines for expr_error
- */
-#define EE_DZ           0x01    /* divide by zero error */
-#define EE_BI_OUTPUT    0x02    /* Bad output index */
-#define EE_BI_INPUT     0x04    /* Bad input index */
-#define EE_NOTABLE      0x08    /* NO TABLE */
-#define EE_NOVAR        0x10    /* NO VARIABLE */
-
-typedef struct expr {
-#ifdef PD
-        t_object exp_ob;
-#else /* MSP */
-        t_pxobject exp_ob;
-#endif
-        int     exp_flags;              /* are we expr~, fexpr~, or expr */
-        int     exp_error;              /* reported errors */
-        int     exp_nexpr;              /* number of expressions */
-        char    *exp_string;            /* the full expression string */
-        char    *exp_str;               /* current parsing position */
-        t_outlet *exp_outlet[MAX_VARS];
-#ifdef PD
-        struct _exprproxy *exp_proxy;
-#else /* MAX */
-        void *exp_proxy[MAX_VARS];
-        long exp_proxy_id;
-#endif
-        struct ex_ex *exp_stack[MAX_VARS];
-        struct ex_ex exp_var[MAX_VARS];
-        struct ex_ex exp_res[MAX_VARS]; /* the evluation result */
-        t_float *exp_p_var[MAX_VARS];
-        t_float *exp_p_res[MAX_VARS];   /* the previous evaluation result */
-        t_float *exp_tmpres[MAX_VARS];          /* temporty result for fexpr~ */
-        int exp_vsize;                  /* the size of the signal vector */
-        int exp_nivec;                  /* # of vector inlets */
-        float exp_f;            /* control value to be transformed to signal */
-} t_expr;
-
-typedef struct ex_funcs {
-        char *f_name;                                   /* function name */
-        void (*f_func)(t_expr *, long, struct ex_ex *, struct ex_ex *);
-          /* the real function performing the function (void, no return!!!) */
-        long f_argc;                            /* number of arguments */
-} t_ex_func;
-
-/* function prototypes for pd-related functions called withing vexp.h */
-
-extern int max_ex_tab(struct expr *expr, t_symbol *s, struct ex_ex *arg, struct ex_ex *optr);
-extern int max_ex_var(struct expr *expr, t_symbol *s, struct ex_ex *optr);
-extern int ex_getsym(char *p, t_symbol **s);
-extern const char *ex_symname(t_symbol *s);
-void ex_mkvector(t_float *fp, t_float x, int size);
-extern void ex_size(t_expr *expr, long int argc, struct ex_ex *argv,
-                                                        struct ex_ex *optr);
-extern void ex_sum(t_expr *expr, long int argc, struct ex_ex *argv,                                                                     struct ex_ex *optr);
-extern void ex_Sum(t_expr *expr, long int argc, struct ex_ex *argv,                                                                     struct ex_ex *optr);
-extern void ex_avg(t_expr *expr, long int argc, struct ex_ex *argv,                                                                     struct ex_ex *optr);
-extern void ex_Avg(t_expr *expr, long int argc, struct ex_ex *argv,                                                                     struct ex_ex *optr);
-extern void ex_store(t_expr *expr, long int argc, struct ex_ex *argv,                                                                   struct ex_ex *optr);
-
-int value_getonly(t_symbol *s, t_float *f);
-
-#ifdef NT
-#pragma warning (disable: 4305 4244)
-
-#define abort ABORT
-void ABORT(void);
-#endif
diff --git a/extra/expr~/vexp_fun.c b/extra/expr~/vexp_fun.c
deleted file mode 100644
index fba49b188..000000000
--- a/extra/expr~/vexp_fun.c
+++ /dev/null
@@ -1,1315 +0,0 @@
-/*
- * jMax
- * Copyright (C) 1994, 1995, 1998, 1999 by IRCAM-Centre Georges Pompidou, Paris, France.
- * 
- * 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.
- * 
- * See file LICENSE for further informations on licensing terms.
- * 
- * 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.
- * 
- * Based on Max/ISPW by Miller Puckette.
- *
- * Authors: Maurizio De Cecco, Francois Dechelle, Enzo Maggi, Norbert Schnell.
- *
- */
-
-/* "expr" was written by Shahrokh Yadegari c. 1989. -msp
- *
- * Nov. 2001 --sdy
- *      conversion for expr~
- *
- * Jan, 2002 --sdy
- *      added fmod()
- *
- * May  2002
- *      added floor and ceil for expr -- Orm Finnendahl
- *
- * July 2002 --sdy
- *      added the following math funtions:
- *              cbrt - cube root
- *              erf - error function
- *              erfc - complementary error function
- *              expm1 - exponential minus 1,
- *              log1p - logarithm of 1 plus
- *              isinf - is the value infinite,
- *              finite - is the value finite
- *              isnan -- is the resut a nan (Not a number)
- *              copysign - copy sign of a number
- *              ldexp  -  multiply floating-point number by integral power of 2
- *              imodf - get signed integral value from floating-point number
- *              modf - get signed fractional value from floating-point number
- *              drem - floating-point remainder function
- *
- *      The following are done but not popular enough in math libss
- *      to be included yet
- *              hypoth - Euclidean distance function
- *              trunc
- *              round
- *              nearbyint - 
- */
-
-
-
-/*
- * vexp_func.c -- this file include all the functions for vexp.
- *                the first two arguments to the function are the number
- *                of argument and an array of arguments (argc, argv)
- *                the last argument is a pointer to a struct ex_ex for
- *                the result.  Up do this point, the content of the
- *                struct ex_ex that these functions receive are either
- *                ET_INT (long), ET_FLT (float), or ET_SYM (char **, it is
- *                char ** and not char * since NewHandle of Mac returns
- *                a char ** for relocatability.)  The common practice in
- *                these functions is that they figure out the type of their
- *                result according to the type of the arguments. In general
- *                the ET_SYM is used an ET_INT when we expect a value.
- *                It is the users responsibility not to pass strings to the
- *                function.
- */
-
-#include <stdlib.h>
-#include <string.h>
-
-#define __STRICT_BSD__
-#include <math.h>
-#undef __STRICT_BSD__
-
-
-#include "vexp.h"
-
-/* forward declarations */
-
-static void ex_min(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_max(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_toint(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_rint(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_tofloat(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_pow(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_exp(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_log(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_ln(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_sin(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_cos(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_asin(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_acos(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_tan(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_atan(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_sinh(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_cosh(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_asinh(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_acosh(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_tanh(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_atanh(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_atan2(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_sqrt(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_fact(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_random(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_abs(t_expr *expr, long int argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_fmod(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_ceil(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_floor(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_if(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_ldexp(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_imodf(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_modf(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-#ifndef NT
-static void ex_cbrt(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_erf(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_erfc(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_expm1(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_log1p(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_isinf(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_finite(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_isnan(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_copysign(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_drem(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-#endif
-#ifdef notdef
-/* the following will be added once they are more popular in math libraries */
-static void ex_round(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_trunc(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_nearbyint(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-static void ex_hypoth(t_expr *expr, long argc, struct ex_ex *argv, struct ex_ex *optr);
-#endif
- 
-
-t_ex_func ex_funcs[] = {
-        {"min",         ex_min,         2},
-        {"max",         ex_max,         2},
-        {"int",         ex_toint,       1},
-        {"rint",        ex_rint,        1},
-        {"float",       ex_tofloat,     1},
-        {"fmod",        ex_fmod,        2},
-        {"floor",       ex_floor,       2},
-        {"ceil",        ex_ceil,        2},
-        {"pow",         ex_pow,         2},
-        {"sqrt",        ex_sqrt,        1},
-        {"exp",         ex_exp,         1},
-        {"log10",       ex_log,         1},
-        {"ln",          ex_ln,          1},
-        {"log",         ex_ln,          1},
-        {"sin",         ex_sin,         1},
-        {"cos",         ex_cos,         1},
-        {"tan",         ex_tan,         1},
-        {"asin",        ex_asin,        1},
-        {"acos",        ex_acos,        1},
-        {"atan",        ex_atan,        1},
-        {"atan2",       ex_atan2,       2},
-        {"sinh",        ex_sinh,        1},
-        {"cosh",        ex_cosh,        1},
-        {"tanh",        ex_tanh,        1},
-        {"fact",        ex_fact,        1},
-        {"random",      ex_random,      2},     /* random number */
-        {"abs",         ex_abs,         1},
-        {"if",          ex_if,          3},
-        {"ldexp ",      ex_ldexp,       1},
-        {"imodf ",      ex_imodf,       1},
-        {"modf",        ex_modf,        1},
-#ifndef NT
-        {"cbrt",        ex_cbrt,        1},
-        {"erf",         ex_erf,         1},
-        {"erfc",        ex_erfc,        1},
-        {"expm1",       ex_expm1,       1},
-        {"log1p",       ex_log1p,       1},
-        {"isinf",       ex_isinf,       1},
-        {"finite",      ex_finite,      1},
-        {"isnan",       ex_isnan,       1},
-        {"copysig",     ex_copysign,    1},
-        {"drem",        ex_drem,        1},
-        {"asinh",       ex_asinh,       1},
-        {"acosh",       ex_acosh,       1},
-        {"atanh",       ex_atanh,       1},     /* hyperbolic atan */
-#endif
-#ifdef PD
-        {"size",        ex_size,        1},
-        {"sum",         ex_sum,         1},
-        {"Sum",         ex_Sum,         3},
-        {"avg",         ex_avg,         1},
-        {"Avg",         ex_Avg,         3},
-        {"store",       ex_store,       3},
-#endif
-#ifdef notdef
-/* the following will be added once they are more popular in math libraries */
-        {"round",       ex_round,       1},
-        {"trunc",       ex_trunc,       1},
-        {"nearbyint",   ex_nearbyint,   1},
-        {"hypoth",      ex_hypoth,      1},
-#endif
-        {0,             0,              0}
-};
-
-/*
- * FUN_EVAL --  do type checking, evaluate a function,
- *              if fltret is set return float
- *              otherwise return value based on regular typechecking,
- */
-#define FUNC_EVAL(left, right, func, leftfuncast, rightfuncast, optr, fltret) \
-switch (left->ex_type) {                                                \
-case ET_INT:                                                            \
-        switch(right->ex_type) {                                        \
-        case ET_INT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = (float)func(leftfuncast left->ex_int,  \
-                                        rightfuncast right->ex_int);    \
-                        j = e->exp_vsize;                               \
-                        while (j--)                                     \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        if (fltret) {                                   \
-                                optr->ex_type = ET_FLT;                 \
-                                optr->ex_flt = (float)func(leftfuncast  \
-                                left->ex_int, rightfuncast right->ex_int); \
-                        } else {                                        \
-                                optr->ex_type = ET_INT;                 \
-                                optr->ex_int = (int)func(leftfuncast    \
-                                left->ex_int, rightfuncast right->ex_int); \
-                        }                                               \
-                }                                                       \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = (float)func(leftfuncast left->ex_int,  \
-                                        rightfuncast right->ex_flt);    \
-                        j = e->exp_vsize;                               \
-                        while (j--)                                     \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_FLT;                         \
-                        optr->ex_flt = (float)func(leftfuncast left->ex_int,  \
-                                        rightfuncast right->ex_flt);    \
-                }                                                       \
-                break;                                                  \
-        case ET_VEC:                                                    \
-        case ET_VI:                                                     \
-                if (optr->ex_type != ET_VEC) {                          \
-                        if (optr->ex_type == ET_VI) {                   \
-                                post("expr~: Int. error %d", __LINE__); \
-                                abort();                                \
-                        }                                               \
-                        optr->ex_type = ET_VEC;                         \
-                        optr->ex_vec = (t_float *)                      \
-                          fts_malloc(sizeof (t_float)*e->exp_vsize);    \
-                }                                                       \
-                scalar = left->ex_int;                                  \
-                rp = right->ex_vec;                                     \
-                op = optr->ex_vec;                                      \
-                j = e->exp_vsize;                                       \
-                while (j--) {                                           \
-                        *op++ = (float)func(leftfuncast scalar,         \
-                                                rightfuncast *rp);      \
-                        rp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_SYM:                                                    \
-        default:                                                        \
-                post_error((fts_object_t *) e,                          \
-                      "expr: FUNC_EVAL(%d): bad right type %ld\n",      \
-                                              __LINE__, right->ex_type);\
-        }                                                               \
-        break;                                                          \
-case ET_FLT:                                                            \
-        switch(right->ex_type) {                                        \
-        case ET_INT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = (float)func(leftfuncast left->ex_flt,  \
-                                        rightfuncast right->ex_int);    \
-                        j = e->exp_vsize;                               \
-                        while (j--)                                     \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_FLT;                         \
-                        optr->ex_flt = (float)func(leftfuncast left->ex_flt,  \
-                                        rightfuncast right->ex_int);    \
-                }                                                       \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                if (optr->ex_type == ET_VEC) {                          \
-                        op = optr->ex_vec;                              \
-                        scalar = (float)func(leftfuncast left->ex_flt,  \
-                                        rightfuncast right->ex_flt);    \
-                        j = e->exp_vsize;                               \
-                        while (j--)                                     \
-                                *op++ = scalar;                         \
-                } else {                                                \
-                        optr->ex_type = ET_FLT;                         \
-                        optr->ex_flt = (float)func(leftfuncast left->ex_flt,  \
-                                        rightfuncast right->ex_flt);    \
-                }                                                       \
-                break;                                                  \
-        case ET_VEC:                                                    \
-        case ET_VI:                                                     \
-                if (optr->ex_type != ET_VEC) {                          \
-                        if (optr->ex_type == ET_VI) {                   \
-                                post("expr~: Int. error %d", __LINE__); \
-                                abort();                                \
-                        }                                               \
-                        optr->ex_type = ET_VEC;                         \
-                        optr->ex_vec = (t_float *)                      \
-                          fts_malloc(sizeof (t_float) * e->exp_vsize);\
-                }                                                       \
-                scalar = left->ex_flt;                                  \
-                rp = right->ex_vec;                                     \
-                op = optr->ex_vec;                                      \
-                j = e->exp_vsize;                                       \
-                while (j--) {                                           \
-                        *op++ = (float)func(leftfuncast scalar,         \
-                                                rightfuncast *rp);      \
-                        rp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_SYM:                                                    \
-        default:                                                        \
-                post_error((fts_object_t *) e,                  \
-                      "expr: FUNC_EVAL(%d): bad right type %ld\n",      \
-                                              __LINE__, right->ex_type);\
-        }                                                               \
-        break;                                                          \
-case ET_VEC:                                                            \
-case ET_VI:                                                             \
-        if (optr->ex_type != ET_VEC) {                                  \
-                if (optr->ex_type == ET_VI) {                           \
-                        post("expr~: Int. error %d", __LINE__);         \
-                        abort();                                        \
-                }                                                       \
-                optr->ex_type = ET_VEC;                                 \
-                optr->ex_vec = (t_float *)                              \
-                  fts_malloc(sizeof (t_float) * e->exp_vsize);  \
-        }                                                               \
-        op = optr->ex_vec;                                              \
-        lp = left->ex_vec;                                              \
-        switch(right->ex_type) {                                        \
-        case ET_INT:                                                    \
-                scalar = right->ex_int;                                 \
-                j = e->exp_vsize;                                       \
-                while (j--) {                                           \
-                        *op++ = (float)func(leftfuncast *lp,            \
-                                                rightfuncast scalar);   \
-                        lp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_FLT:                                                    \
-                scalar = right->ex_flt;                                 \
-                j = e->exp_vsize;                                       \
-                while (j--) {                                           \
-                        *op++ = (float)func(leftfuncast *lp,            \
-                                                rightfuncast scalar);   \
-                        lp++;                                           \
-                }                                                       \
-                break;                                                  \
-        case ET_VEC:                                                    \
-        case ET_VI:                                                     \
-                rp = right->ex_vec;                                     \
-                j = e->exp_vsize;                                       \
-                while (j--) {                                           \
-                        /*                                              \
-                         * on a RISC processor one could copy           \
-                         * 8 times in each round to get a considerable  \
-                         * improvement                                  \
-                         */                                             \
-                        *op++ = (float)func(leftfuncast *lp,            \
-                                                rightfuncast *rp);      \
-                        rp++; lp++;                                     \
-                }                                                       \
-                break;                                                  \
-        case ET_SYM:                                                    \
-        default:                                                        \
-                post_error((fts_object_t *) e,                  \
-                      "expr: FUNC_EVAL(%d): bad right type %ld\n",      \
-                                              __LINE__, right->ex_type);\
-        }                                                               \
-        break;                                                          \
-case ET_SYM:                                                            \
-default:                                                                \
-                post_error((fts_object_t *) e,                  \
-                      "expr: FUNC_EVAL(%d): bad left type %ld\n",               \
-                                              __LINE__, left->ex_type); \
-}
-
-/*
- * FUNC_EVAL_UNARY - evaluate a unary function,
- *              if fltret is set return float
- *              otherwise return value based on regular typechecking,
- */
-#define FUNC_EVAL_UNARY(left, func, leftcast, optr, fltret)             \
-switch(left->ex_type) {                                         \
-case ET_INT:                                                    \
-        if (optr->ex_type == ET_VEC) {                          \
-                ex_mkvector(optr->ex_vec,                       \
-                (float)(func (leftcast left->ex_int)), e->exp_vsize);\
-                break;                                          \
-        }                                                       \
-        if (fltret) {                                           \
-                optr->ex_type = ET_FLT;                         \
-                optr->ex_flt = (float) func(leftcast left->ex_int); \
-                break;                                          \
-        }                                                       \
-        optr->ex_type = ET_INT;                                 \
-        optr->ex_int = (int) func(leftcast left->ex_int);       \
-        break;                                                  \
-case ET_FLT:                                                    \
-        if (optr->ex_type == ET_VEC) {                          \
-                ex_mkvector(optr->ex_vec,                       \
-                (float)(func (leftcast left->ex_flt)), e->exp_vsize);\
-                break;                                          \
-        }                                                       \
-        optr->ex_type = ET_FLT;                                 \
-        optr->ex_flt = (float) func(leftcast left->ex_flt);     \
-        break;                                                  \
-case ET_VI:                                                     \
-case ET_VEC:                                                    \
-        if (optr->ex_type != ET_VEC) {                          \
-                optr->ex_type = ET_VEC;                         \
-                optr->ex_vec = (t_float *)                      \
-                  fts_malloc(sizeof (t_float)*e->exp_vsize);    \
-        }                                                       \
-        op = optr->ex_vec;                                      \
-        lp = left->ex_vec;                                      \
-        j = e->exp_vsize;                                       \
-        while (j--)                                             \
-                *op++ = (float)(func (leftcast *lp++));         \
-        break;                                                  \
-default:                                                        \
-        post_error((fts_object_t *) e,                          \
-                "expr: FUNV_EVAL_UNARY(%d): bad left type %ld\n",\
-                                      __LINE__, left->ex_type); \
-}
-
-#undef min
-#undef max
-#define min(x,y)        (x > y ? y : x)
-#define max(x,y)        (x > y ? x : y)
-
-#define FUNC_DEF(ex_func, func, castleft, castright, fltret);                   \
-static void                                                             \
-ex_func(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)\
-{                                                                       \
-        struct ex_ex *left, *right;                                     \
-        float *op; /* output pointer */                                 \
-        float *lp, *rp;         /* left and right vector pointers */    \
-        float scalar;                                                   \
-        int j;                                                          \
-                                                                        \
-        left = argv++;                                                  \
-        right = argv;                                                   \
-        FUNC_EVAL(left, right, func, castleft, castright, optr, fltret); \
-}
-
-
-#define FUNC_DEF_UNARY(ex_func, func, cast, fltret);                    \
-static void                                                             \
-ex_func(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)\
-{                                                                       \
-        struct ex_ex *left;                                             \
-        float *op; /* output pointer */                                 \
-        float *lp, *rp;         /* left and right vector pointers */    \
-        float scalar;                                                   \
-        int j;                                                          \
-                                                                        \
-        left = argv++;                                                  \
-                                                                        \
-        FUNC_EVAL_UNARY(left, func, cast, optr, fltret);                \
-}
-
-/*
- * ex_min -- if any of the arguments are or the output are vectors, a vector
- *           of floats is generated otherwise the type of the result is the
- *           type of the smaller value
- */
-static void
-ex_min(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        right = argv;
-
-        FUNC_EVAL(left, right, min, (double), (double), optr, 0);
-}
-
-/*
- * ex_max -- if any of the arguments are or the output are vectors, a vector
- *           of floats is generated otherwise the type of the result is the
- *           type of the larger value
- */
-static void
-ex_max(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        right = argv;
-
-        FUNC_EVAL(left, right, max, (double), (double), optr, 0);
-}
-
-/*
- * ex_toint -- convert to integer
- */
-static void
-ex_toint(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-#define toint(x)        ((int)(x))
-                FUNC_EVAL_UNARY(left, toint, (int), optr, 0);
-        }
-
-#ifdef NT
-/* No rint in NT land ??? */
-double rint(double x);
-
-double
-rint(double x)
-{
-        return (floor(x + 0.5));
-}
-#endif
-
-/*
- * ex_rint -- rint() round to the nearest int according to the common
- *            rounding mechanism
- */
-static void
-ex_rint(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-
-        FUNC_EVAL_UNARY(left, rint, (double), optr, 1);
-}
-
-/*
- * ex_tofloat -- convert to float
- */
-static void
-ex_tofloat(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-#define tofloat(x)      ((float)(x))
-        FUNC_EVAL_UNARY(left, tofloat, (int), optr, 1);
-}
-
-
-/*
- * ex_pow -- the power of
- */
-static void
-ex_pow(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        right = argv;
-        FUNC_EVAL(left, right, pow, (double), (double), optr, 1);
-}
-
-/*
- * ex_sqrt -- square root
- */
-static void
-ex_sqrt(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, sqrt, (double), optr, 1);
-}
-
-/*
- * ex_exp -- e to the power of
- */
-static void
-ex_exp(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, exp, (double), optr, 1);
-}
-
-/*
- * ex_log -- 10 based logarithm
- */
-static void
-ex_log(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, log10, (double), optr, 1);
-}
-
-/*
- * ex_ln -- natural log
- */
-static void
-ex_ln(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, log, (double), optr, 1);
-}
-
-static void
-ex_sin(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, sin, (double), optr, 1);
-}
-
-static void
-ex_cos(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, cos, (double), optr, 1);
-}
-
-
-static void
-ex_tan(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, tan, (double), optr, 1);
-}
-
-static void
-ex_asin(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, asin, (double), optr, 1);
-}
-
-static void
-ex_acos(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, acos, (double), optr, 1);
-}
-
-
-static void
-ex_atan(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, atan, (double), optr, 1);
-}
-
-/*
- *ex_atan2 --
- */
-static void
-ex_atan2(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        right = argv;
-        FUNC_EVAL(left, right, atan2, (double), (double), optr, 1);
-}
-
-/*
- * ex_fmod -- floating point modulo
- */
-static void
-ex_fmod(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        right = argv;
-        FUNC_EVAL(left, right, fmod, (double), (double), optr, 1);
-}
-
-
-/*
- * ex_floor -- floor
- */
-static void
-ex_floor(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        FUNC_EVAL_UNARY(left, floor, (double), optr, 1);
-}
-
-
-/*
- * ex_ceil -- ceil
- */
-static void
-ex_ceil(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        FUNC_EVAL_UNARY(left, ceil, (double), optr, 1);
-}
-
-static void
-ex_sinh(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, sinh, (double), optr, 1);
-}
-
-static void
-ex_cosh(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, cosh, (double), optr, 1);
-}
-
-
-static void
-ex_tanh(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, tanh, (double), optr, 1);
-}
-
-
-#ifndef NT
-static void
-ex_asinh(t_expr *e, long argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, asinh, (double), optr, 1);
-}
-
-static void
-ex_acosh(t_expr *e, long argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, acosh, (double), optr, 1);
-}
-
-static void
-ex_atanh(t_expr *e, long argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, atanh, (double), optr, 1);
-}
-#endif
-
-static int
-ex_dofact(int i)
-{
-        int ret = 0;
-
-        if (i)
-                ret = 1;
-        else
-                return (0);
-
-        do {
-                ret *= i;
-        } while (--i);
-
-        return(ret);
-}
-
-static void
-ex_fact(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, ex_dofact,  (int), optr, 0);
-}
-
-static int
-ex_dorandom(int i1, int i2)
-{
-        return(i1 + (((i2 - i1) * (rand() & 0x7fffL)) >> 15));
-}
-/*
- * ex_random -- return a random number
- */
-static void
-ex_random(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-        right = argv;
-        FUNC_EVAL(left, right, ex_dorandom, (int), (int), optr, 0);
-}
-
-
-static void
-ex_abs(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float scalar;
-        int j;
-
-        left = argv++;
-
-        FUNC_EVAL_UNARY(left, fabs, (double), optr, 0);
-}
-
-/*
- *ex_if -- floating point modulo
- */
-static void
-ex_if(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        struct ex_ex *left, *right, *cond, *res;
-        float *op; /* output pointer */
-        float *lp, *rp;         /* left and right vector pointers */
-        float *cp;              /* condition pointer */
-        float leftvalue, rightvalue;
-        int j;
-
-        cond = argv++;
-        left = argv++;
-        right = argv;
-
-        switch (cond->ex_type) {
-        case ET_VEC:
-        case ET_VI:
-                if (optr->ex_type != ET_VEC) {
-                        if (optr->ex_type == ET_VI) {
-                                /* SDY remove this test */
-                                post("expr~: Int. error %d", __LINE__);
-                                return;
-                        }
-                                optr->ex_type = ET_VEC;
-                                optr->ex_vec = (t_float *)
-                                  fts_malloc(sizeof (t_float) * e->exp_vsize);
-                }
-                op = optr->ex_vec;
-                j = e->exp_vsize;
-                cp = cond->ex_vec;
-                switch (left->ex_type) {
-                case ET_INT:
-                        leftvalue = left->ex_int;
-                        switch (right->ex_type) {
-                        case ET_INT:
-                                rightvalue = right->ex_int;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = leftvalue;
-                                        else
-                                                *op++ = rightvalue;
-                                }
-                        return;
-                        case ET_FLT:
-                                rightvalue = right->ex_flt;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = leftvalue;
-                                        else
-                                                *op++ = rightvalue;
-                                }
-                                return;
-                        case ET_VEC:
-                        case ET_VI:
-                                rp = right->ex_vec;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = leftvalue;
-                                        else
-                                                *op++ = *rp;
-                                        rp++;
-                                }
-                                return;
-                        case ET_SYM:
-                        default:
-                                post_error((fts_object_t *) e,
-                              "expr: FUNC_EVAL(%d): bad right type %ld\n",
-                                                      __LINE__, right->ex_type);
-                                return;
-                        }
-                case ET_FLT:
-                        leftvalue = left->ex_flt;
-                        switch (right->ex_type) {
-                        case ET_INT:
-                                rightvalue = right->ex_int;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = leftvalue;
-                                        else
-                                                *op++ = rightvalue;
-                                }
-                                return;
-                        case ET_FLT:
-                                rightvalue = right->ex_flt;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = leftvalue;
-                                        else
-                                                *op++ = rightvalue;
-                                }
-                                return;
-                        case ET_VEC:
-                        case ET_VI:
-                                rp = right->ex_vec;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = leftvalue;
-                                        else
-                                                *op++ = *rp;
-                                        rp++;
-                                }
-                                return;
-                        case ET_SYM:
-                        default:
-                                post_error((fts_object_t *) e,
-                              "expr: FUNC_EVAL(%d): bad right type %ld\n",
-                                                      __LINE__, right->ex_type);
-                                return;
-                        }
-                case ET_VEC:
-                case ET_VI:
-                        lp = left->ex_vec;
-                        switch (right->ex_type) {
-                        case ET_INT:
-                                rightvalue = right->ex_int;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = *lp;
-                                        else
-                                                *op++ = rightvalue;
-                                        lp++;
-                                }
-                                return;
-                        case ET_FLT:
-                                rightvalue = right->ex_flt;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = *lp;
-                                        else
-                                                *op++ = rightvalue;
-                                        lp++;
-                                }
-                                return;
-                        case ET_VEC:
-                        case ET_VI:
-                                rp = right->ex_vec;
-                                while (j--) {
-                                        if (*cp++)
-                                                *op++ = *lp;
-                                        else
-                                                *op++ = *rp;
-                                        lp++; rp++;
-                                }
-                                return;
-                        case ET_SYM:
-                        default:
-                                post_error((fts_object_t *) e,
-                              "expr: FUNC_EVAL(%d): bad right type %ld\n",
-                                                      __LINE__, right->ex_type);
-                                return;
-                        }
-                case ET_SYM:
-                default:
-                        post_error((fts_object_t *) e,
-                      "expr: FUNC_EVAL(%d): bad left type %ld\n",
-                                              __LINE__, left->ex_type);
-                        return;
-                }
-        case ET_INT:
-                if (cond->ex_int)
-                        res = left;
-                else
-                        res = right;
-                break;
-        case ET_FLT:
-                if (cond->ex_flt)
-                        res = left;
-                else
-                        res = right;
-                break;
-        case ET_SYM:
-        default:
-                post_error((fts_object_t *) e,
-              "expr: FUNC_EVAL(%d): bad condition type %ld\n",
-                                      __LINE__, cond->ex_type);
-                return;
-        }
-        switch(res->ex_type) {
-        case ET_INT:
-                if (optr->ex_type == ET_VEC) {
-                        ex_mkvector(optr->ex_vec, (float)res->ex_int,
-                                                                e->exp_vsize);
-                        return;
-                }
-                *optr = *res;
-                return;
-        case ET_FLT:
-                if (optr->ex_type == ET_VEC) {
-                        ex_mkvector(optr->ex_vec, (float)res->ex_flt,
-                                                                e->exp_vsize);
-                        return;
-                }
-                *optr = *res;
-                return;
-        case ET_VEC:
-        case ET_VI:
-                if (optr->ex_type != ET_VEC) {
-                        if (optr->ex_type == ET_VI) {
-                                /* SDY remove this test */
-                                post("expr~: Int. error %d", __LINE__);
-                                return;
-                        }
-                                optr->ex_type = ET_VEC;
-                                optr->ex_vec = (t_float *)
-                                  fts_malloc(sizeof (t_float) * e->exp_vsize);
-                }
-                memcpy(optr->ex_vec, res->ex_vec, e->exp_vsize*sizeof(t_float));
-                return;
-        case ET_SYM:
-        default:
-                post_error((fts_object_t *) e,
-              "expr: FUNC_EVAL(%d): bad res type %ld\n",
-                                      __LINE__, res->ex_type);
-                return;
-        }
-        
-}
-
-/*
- * ex_imodf -   extract signed integral value from floating-point number
- */
-static double
-imodf(double x)
-{
-        double  xx;
-
-        modf(x, &xx);
-        return (xx);
-}
-FUNC_DEF_UNARY(ex_imodf, imodf, (double), 1);
-
-/*
- * ex_modf - extract signed  fractional value from floating-point number
- *
- *  using fracmodf because fmodf() is alrady defined in a .h file
- */
-static double
-fracmodf(double x)
-{
-        double  xx;
-
-        return(modf(x, &xx));
-}
-FUNC_DEF_UNARY(ex_modf, fracmodf, (double), 1);
-
-/*
- * ex_ldexp  -  multiply floating-point number by integral power of 2
- */
-FUNC_DEF(ex_ldexp, ldexp, (double), (int), 1);
-
-#ifndef NT
-/*
- * ex_cbrt - cube root
- */
-FUNC_DEF_UNARY(ex_cbrt, cbrt, (double), 1);
-
-/*
- * ex_erf - error function
- */
-FUNC_DEF_UNARY(ex_erf, erf, (double), 1);
-
-/*
- * ex_erfc - complementary error function
- */
-FUNC_DEF_UNARY(ex_erfc, erfc, (double), 1);
-
-/*
- * ex_expm1 - exponential minus 1,
- */
-FUNC_DEF_UNARY(ex_expm1, expm1, (double), 1);
-
-/*
- * ex_log1p - logarithm of 1 plus
- */
-FUNC_DEF_UNARY(ex_log1p, log1p, (double), 1);
-
-/*
- * ex_isinf - is the value infinite,
- */
-FUNC_DEF_UNARY(ex_isinf, isinf, (double), 0);
-
-/*
- * ex_finite - is the value finite
- */
-FUNC_DEF_UNARY(ex_finite, finite, (double), 0);
-
-/*
- * ex_isnan -- is the resut a nan (Not a number)
- */
-FUNC_DEF_UNARY(ex_isnan, isnan, (double), 0);
-
-/*
- * ex_copysign - copy sign of a number
- */
-FUNC_DEF(ex_copysign, copysign, (double), (double), 1);
-
-/*
- * ex_drem - floating-point remainder function
- */
-FUNC_DEF(ex_drem, drem, (double), (double), 1);
-#endif
-
-#ifdef notdef
-/* the following will be added once they are more popular in math libraries */
-/*
- * ex_hypoth - Euclidean distance function
- */
-FUNC_DEF(ex_hypoth, hypoth, (double), (double), 1);
-
-/*
- * ex_round -  round to nearest integer, away from zero
- */
-FUNC_DEF_UNARY(ex_round, round, (double), 1);
-
-/*
- * ex_trunc -  round to interger, towards zero
- */
-FUNC_DEF_UNARY(ex_trunc, trunc, (double), 1);
-
-/*
- * ex_nearbyint -  round to nearest integer
- */
-FUNC_DEF_UNARY(ex_nearbyint, nearbyint, (double), 1);
-#endif
diff --git a/extra/expr~/vexp_if.c b/extra/expr~/vexp_if.c
deleted file mode 100644
index 648aba732..000000000
--- a/extra/expr~/vexp_if.c
+++ /dev/null
@@ -1,1225 +0,0 @@
-/*
- * jMax
- * Copyright (C) 1994, 1995, 1998, 1999 by IRCAM-Centre Georges Pompidou, Paris, France.
- * 
- * 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.
- * 
- * See file LICENSE for further informations on licensing terms.
- * 
- * 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.
- * 
- * Based on Max/ISPW by Miller Puckette.
- *
- * Authors: Maurizio De Cecco, Francois Dechelle, Enzo Maggi, Norbert Schnell.
- *
- */
-
-/* "expr" was written by Shahrokh Yadegari c. 1989. -msp */
-/* "expr~" and "fexpr~" conversion by Shahrokh Yadegari c. 1999,2000 */
-
-/*
- * Feb 2002 - added access to variables
- *            multiple expression support
- *            new short hand forms for fexpr~
- *              now $y or $y1 = $y1[-1] and $y2 = $y2[-1]
- * --sdy
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "vexp.h"
-
-static char *exp_version = "0.4";
-
-extern struct ex_ex *ex_eval(struct expr *expr, struct ex_ex *eptr,
-                                                struct ex_ex *optr, int n);
-
-#ifdef PD
-static t_class *expr_class;
-static t_class *expr_tilde_class;
-static t_class *fexpr_tilde_class;
-#else /* MSP */
-void *expr_tilde_class;
-#endif
-
-
-/*------------------------- expr class -------------------------------------*/
-
-extern int expr_donew(struct expr *expr, int ac, t_atom *av);
-
-/*#define EXPR_DEBUG*/
-
-static void expr_bang(t_expr *x);
-t_int *expr_perform(t_int *w);
-
-
-static void
-expr_list(t_expr *x, t_symbol *s, int argc, const fts_atom_t *argv)
-{
-        int i;
-
-        if (argc > MAX_VARS) argc = MAX_VARS;
-
-        for (i = 0; i < argc; i++)
-        {
-                if (argv[i].a_type == A_FLOAT)
-                {
-                        if (x->exp_var[i].ex_type == ET_FI)
-                                x->exp_var[i].ex_flt = argv[i].a_w.w_float;
-                        else if (x->exp_var[i].ex_type == ET_II)
-                                x->exp_var[i].ex_int = argv[i].a_w.w_float;
-                        else if (x->exp_var[i].ex_type)
-                            pd_error(x, "expr: type mismatch");
-                }
-                else if (argv[i].a_type == A_SYMBOL)
-                {
-                        if (x->exp_var[i].ex_type == ET_SI)
-                                x->exp_var[i].ex_ptr = (char *)argv[i].a_w.w_symbol;
-                        else if (x->exp_var[i].ex_type)
-                            pd_error(x, "expr: type mismatch");
-                }
-        }
-        expr_bang(x);
-}
-
-static void
-expr_flt(t_expr *x, t_float f, int in)
-{
-        if (in > MAX_VARS)
-                return;
-
-        if (x->exp_var[in].ex_type == ET_FI)
-                x->exp_var[in].ex_flt = f;
-        else if (x->exp_var[in].ex_type == ET_II)
-                x->exp_var[in].ex_int = f;
-}
-
-static t_class *exprproxy_class;
-
-typedef struct _exprproxy {
-        t_pd p_pd;
-        int p_index;
-        t_expr *p_owner;
-        struct _exprproxy *p_next;
-} t_exprproxy;
-
-t_exprproxy *exprproxy_new(t_expr *owner, int indx);
-void exprproxy_float(t_exprproxy *p, t_floatarg f);
-
-t_exprproxy *
-exprproxy_new(t_expr *owner, int indx)
-{
-        t_exprproxy *x = (t_exprproxy *)pd_new(exprproxy_class);
-        x->p_owner = owner;
-        x->p_index = indx;
-        x->p_next = owner->exp_proxy;
-        owner->exp_proxy = x;
-        return (x);
-}
-
-void
-exprproxy_float(t_exprproxy *p, t_floatarg f)
-{
-        t_expr *x = p->p_owner;
-        int in = p->p_index;
-
-        if (in > MAX_VARS)
-                return;
-
-        if (x->exp_var[in].ex_type == ET_FI)
-                x->exp_var[in].ex_flt = f;
-        else if (x->exp_var[in].ex_type == ET_II)
-                x->exp_var[in].ex_int = f;
-}
-
-/* method definitions */
-static void
-expr_ff(t_expr *x)
-{
-        t_exprproxy *y;
-        int i;
-        
-        y = x->exp_proxy;
-        while (y)
-        {
-                x->exp_proxy = y->p_next;
-#ifdef PD
-                pd_free(&y->p_pd);
-#else /*MSP */
-        /* SDY find out what needs to be called for MSP */
-
-#endif
-                y = x->exp_proxy;
-        }
-        for (i = 0 ; i < x->exp_nexpr; i++);
-                if (x->exp_stack[i])
-                        fts_free(x->exp_stack[i]);
-/*
- * SDY free all the allocated buffers here for expr~ and fexpr~
- * check to see if there are others
- */
-        for (i = 0; i < MAX_VARS; i++) {
-                if (x->exp_p_var[i])
-                        fts_free(x->exp_p_var[i]);
-                if (x->exp_p_res[i])
-                        fts_free(x->exp_p_res[i]);
-                if (x->exp_tmpres[i])
-                        fts_free(x->exp_tmpres[i]);
-        }
-
-
-}
-
-static void
-expr_bang(t_expr *x)
-{
-        int i;
-
-#ifdef EXPR_DEBUG
-        {
-                struct ex_ex *eptr;
-
-                for (i = 0, eptr = x->exp_var;  ; eptr++, i++)
-                {
-                        if (!eptr->ex_type)
-                                break;
-                        switch (eptr->ex_type)
-                        {
-                        case ET_II:
-                                fprintf(stderr,"ET_II: %d \n", eptr->ex_int);
-                                break;
-
-                        case ET_FI:
-                                fprintf(stderr,"ET_FT: %f \n", eptr->ex_flt);
-                                break;
-
-                        default:
-                                fprintf(stderr,"oups\n");
-                        }
-                }
-        }
-#endif
-        /* banging a signal or filter object means nothing */
-        if (!IS_EXPR(x))
-                return;
-
-        for (i = x->exp_nexpr - 1; i > -1 ; i--) {
-                if (!ex_eval(x, x->exp_stack[i], &x->exp_res[i], 0)) {
-                        /*fprintf(stderr,"expr_bang(error evaluation)\n"); */
-                /*  SDY now that we have mutiple ones, on error we should
-                 * continue
-                        return;
-                 */
-                }
-                switch(x->exp_res[i].ex_type) {
-                case ET_INT:
-                        outlet_float(x->exp_outlet[i], 
-                                        (t_float) x->exp_res[i].ex_int);
-                        break;
-
-                case ET_FLT:
-                        outlet_float(x->exp_outlet[i],  x->exp_res[i].ex_flt);
-                        break;
-
-                case ET_SYM:
-                        /* CHANGE this will have to be taken care of */
-
-                default:
-                        post("expr: bang: unrecognized result %ld\n", x->exp_res[i].ex_type);
-                }
-        }
-}
-
-static t_expr *
-#ifdef PD
-expr_new(t_symbol *s, int ac, t_atom *av)
-#else /* MSP */
-Nexpr_new(t_symbol *s, int ac, t_atom *av)
-#endif
-{
-        struct expr *x;
-        int i, ninlet;
-        struct ex_ex *eptr;
-        t_atom fakearg;
-        int dsp_index;  /* keeping track of the dsp inlets */
-
-
-/*
- * SDY - we may need to call dsp_setup() in this function
- */
-
-        if (!ac)
-        {
-                ac = 1;
-                av = &fakearg;
-                SETFLOAT(&fakearg, 0);
-        }
-
-#ifdef PD
-        /*
-         * figure out if we are expr, expr~, or fexpr~
-         */
-        if (!strcmp("expr", s->s_name)) {
-                x = (t_expr *)pd_new(expr_class);
-                SET_EXPR(x);
-        } else if (!strcmp("expr~", s->s_name)) {
-                x = (t_expr *)pd_new(expr_tilde_class);
-                SET_EXPR_TILDE(x);
-        } else if (!strcmp("fexpr~", s->s_name)) {
-                x = (t_expr *)pd_new(fexpr_tilde_class);
-                SET_FEXPR_TILDE(x);
-        } else {
-                post("expr_new: bad object name '%s'");
-                /* assume expr */
-                x = (t_expr *)pd_new(expr_class);
-                SET_EXPR(x);
-        }
-#else /* MSP */
-        /* for now assume an expr~ */
-        x = (t_expr *)pd_new(expr_tilde_class);
-        SET_EXPR_TILDE(x);
-#endif          
-        
-        /*
-         * initialize the newly allocated object
-         */
-        x->exp_proxy = 0;
-        x->exp_nivec = 0;
-        x->exp_nexpr = 0;
-        x->exp_error = 0;
-        for (i = 0; i < MAX_VARS; i++) {
-                x->exp_stack[i] = (struct ex_ex *)0;
-                x->exp_outlet[i] = (t_outlet *)0;
-                x->exp_res[i].ex_type = 0;
-                x->exp_res[i].ex_int = 0;
-                x->exp_p_res[i] = (t_float *)0;
-                x->exp_var[i].ex_type = 0;
-                x->exp_var[i].ex_int = 0;
-                x->exp_p_var[i] = (t_float *)0;
-                x->exp_tmpres[i] = (t_float *)0;
-                x->exp_vsize = 0;
-        }
-        x->exp_f = 0; /* save the control value to be transformed to signal */
-                
-
-        if (expr_donew(x, ac, av))
-        {
-                pd_error(x, "expr: syntax error");
-/*
-SDY the following coredumps why?
-                pd_free(&x->exp_ob.ob_pd);
-*/
-                return (0);
-        }
-
-        ninlet = 1;
-        for (i = 0, eptr = x->exp_var; i < MAX_VARS ; i++, eptr++)
-                if (eptr->ex_type) {
-                        ninlet = i + 1;
-                }
-
-        /*
-         * create the new inlets
-         */
-        for (i = 1, eptr = x->exp_var + 1, dsp_index=1; i<ninlet ; i++, eptr++)
-        {
-                t_exprproxy *p;
-                switch (eptr->ex_type)
-                {
-                case 0:
-                        /* nothing is using this inlet */
-                        if (i < ninlet)
-#ifdef PD
-                                floatinlet_new(&x->exp_ob, &eptr->ex_flt);
-#else /* MSP */
-                                inlet_new(&x->exp_ob, "float");
-#endif
-                        break;
-
-                case ET_II:
-                case ET_FI:
-                        p = exprproxy_new(x, i);
-#ifdef PD
-                        inlet_new(&x->exp_ob, &p->p_pd, &s_float, &s_float);
-#else /* MSP */
-                        inlet_new(&x->exp_ob, "float");
-#endif
-                        break;
-
-                case ET_SI:
-#ifdef PD
-                        symbolinlet_new(&x->exp_ob, (t_symbol **)&eptr->ex_ptr);
-#else /* MSP */
-                        inlet_new(&x->exp_ob, "symbol");
-#endif
-                        break;
-
-                case ET_XI:
-                case ET_VI:
-                        if (!IS_EXPR(x)) {
-                                dsp_index++;
-#ifdef PD
-                                inlet_new(&x->exp_ob, &x->exp_ob.ob_pd,
-                                                        &s_signal, &s_signal);
-#else /* MSP */
-                                inlet_new(&x->exp_ob, "signal");
-#endif
-                                break;
-                        } else
-                                post("expr: internal error expr_new");
-                default:
-                        pd_error(x, "expr: bad type (%lx) inlet = %d\n",
-                                            eptr->ex_type, i + 1, 0, 0, 0);
-                        break;
-                }
-        }
-        if (IS_EXPR(x)) {
-                for (i = 0; i < x->exp_nexpr; i++)
-                        x->exp_outlet[i] = outlet_new(&x->exp_ob, 0);
-        } else {
-                for (i = 0; i < x->exp_nexpr; i++)
-                        x->exp_outlet[i] = outlet_new(&x->exp_ob,
-                                                        gensym("signal"));
-                x->exp_nivec = dsp_index;
-        }
-        /*
-         * for now assume a 64 sample size block but this may change once
-         * expr_dsp is called
-         */
-        x->exp_vsize = 64;
-        for (i = 0; i < x->exp_nexpr; i++) {
-                x->exp_p_res[i] = fts_calloc(x->exp_vsize, sizeof (t_float));
-                x->exp_tmpres[i] = fts_calloc(x->exp_vsize, sizeof (t_float));
-        }
-        for (i = 0; i < MAX_VARS; i++)
-                x->exp_p_var[i] = fts_calloc(x->exp_vsize, sizeof (t_float));
-
-        return (x);
-}
-
-t_int *
-expr_perform(t_int *w)
-{
-        int i, j;
-        t_expr *x = (t_expr *)w[1];
-        struct ex_ex res;
-        int n;
-
-        /* sanity check */
-        if (IS_EXPR(x)) {
-                post("expr_perform: bad x->exp_flags = %d", x->exp_flags);
-                abort();
-        }
-
-        if (x->exp_flags & EF_STOP) {
-                for (i = 0; i < x->exp_nexpr; i++)
-                        memset(x->exp_res[i].ex_vec, 0,
-                                        x->exp_vsize * sizeof (float));
-                return (w + 2);
-        }
-
-        if (IS_EXPR_TILDE(x)) {
-                /*
-                 * if we have only one expression, we can right on
-                 * on the output directly, otherwise we have to copy
-                 * the data because, outputs could be the same buffer as
-                 * inputs
-                 */
-                if ( x->exp_nexpr == 1)
-                        ex_eval(x, x->exp_stack[0], &x->exp_res[0], 0);
-                else {
-                        res.ex_type = ET_VEC;
-                        for (i = 0; i < x->exp_nexpr; i++) {
-                                res.ex_vec = x->exp_tmpres[i];
-                                ex_eval(x, x->exp_stack[i], &res, 0);
-                        }
-                        n = x->exp_vsize * sizeof(t_float);
-                        for (i = 0; i < x->exp_nexpr; i++)
-                                memcpy(x->exp_res[i].ex_vec, x->exp_tmpres[i],
-                                                                        n);
-                }
-                return (w + 2);
-        }
-
-        if (!IS_FEXPR_TILDE(x)) {
-                post("expr_perform: bad x->exp_flags = %d - expecting fexpr",
-                                                                x->exp_flags);
-                return (w + 2);
-        }
-        /*
-         * since the output buffer could be the same as one of the inputs
-         * we need to keep the output in  a different buffer
-         */
-        for (i = 0; i < x->exp_vsize; i++) for (j = 0; j < x->exp_nexpr; j++) {
-                res.ex_type = 0;
-                res.ex_int = 0;
-                ex_eval(x, x->exp_stack[j], &res, i);
-                switch (res.ex_type) {
-                case ET_INT:
-                        x->exp_tmpres[j][i] = (t_float) res.ex_int;
-                        break;
-                case ET_FLT:
-                        x->exp_tmpres[j][i] = res.ex_flt;
-                        break;
-                default:
-                        post("expr_perform: bad result type %d", res.ex_type);
-                }
-        }
-        /*
-         * copy inputs and results to the save buffers
-         * inputs need to be copied first as the output buffer can be
-         * same as an input buffer
-         */
-        n = x->exp_vsize * sizeof(t_float);
-        for (i = 0; i < MAX_VARS; i++)
-                if (x->exp_var[i].ex_type == ET_XI)
-                        memcpy(x->exp_p_var[i], x->exp_var[i].ex_vec, n);
-        for (i = 0; i < x->exp_nexpr; i++) {
-                memcpy(x->exp_p_res[i], x->exp_tmpres[i], n);
-                memcpy(x->exp_res[i].ex_vec, x->exp_tmpres[i], n);
-        }
-        return (w + 2);
-}
-
-static void
-expr_dsp(t_expr *x, t_signal **sp)
-{
-        int i, nv;
-        int newsize;
-
-        x->exp_error = 0;               /* reset all errors */
-        newsize = (x->exp_vsize !=  sp[0]->s_n);
-        x->exp_vsize = sp[0]->s_n;      /* record the vector size */
-        for (i = 0; i < x->exp_nexpr; i++) {
-                x->exp_res[i].ex_type = ET_VEC;
-                x->exp_res[i].ex_vec =  sp[x->exp_nivec + i]->s_vec; 
-        }
-        for (i = 0, nv = 0; i < MAX_VARS; i++)
-                /*
-                 * the first inlet is always a signal
-                 *
-                 * SDY  We are warning the user till this limitation
-                 * is taken away from pd
-                 */
-                if (!i || x->exp_var[i].ex_type == ET_VI ||
-                                        x->exp_var[i].ex_type == ET_XI) {
-                        if (nv >= x->exp_nivec) {
-                          post("expr_dsp int. err nv = %d, x->exp_nive = %d",
-                                                          nv,  x->exp_nivec);
-                          abort();
-                        }
-                        x->exp_var[i].ex_vec  = sp[nv]->s_vec;
-                        nv++;
-                }
-        /* we always have one inlet but we may not use it */
-        if (nv != x->exp_nivec && (nv != 0 ||  x->exp_nivec != 1)) {
-                post("expr_dsp internal error 2 nv = %d, x->exp_nive = %d",
-                                                          nv,  x->exp_nivec);
-                abort();
-        }
-
-        dsp_add(expr_perform, 1, (t_int *) x);
-
-        /*
-         * The buffer are now being allocated for expr~ and fexpr~
-         * because if we have more than one expression we need the
-         * temporary buffers, The save buffers are not really needed
-        if (!IS_FEXPR_TILDE(x))
-                return;
-         */
-        /*
-         * if we have already allocated the buffers and we have a 
-         * new size free all the buffers
-         */
-        if (x->exp_p_res[0]) {
-                if (!newsize)
-                        return;
-                /*
-                 * if new size, reallocate all the previous buffers for fexpr~
-                 */
-                for (i = 0; i < x->exp_nexpr; i++) {
-                        fts_free(x->exp_p_res[i]);
-                        fts_free(x->exp_tmpres[i]);
-                }
-                for (i = 0; i < MAX_VARS; i++)
-                        fts_free(x->exp_p_var[i]);
-
-        }
-        for (i = 0; i < x->exp_nexpr; i++) {
-                x->exp_p_res[i] = fts_calloc(x->exp_vsize, sizeof (t_float));
-                x->exp_tmpres[i] = fts_calloc(x->exp_vsize, sizeof (t_float));
-        }
-        for (i = 0; i < MAX_VARS; i++)
-                x->exp_p_var[i] = fts_calloc(x->exp_vsize, sizeof (t_float));
-}
-
-/*
- * expr_verbose -- toggle the verbose switch
- */
-static void
-expr_verbose(t_expr *x)
-{
-        if (x->exp_flags & EF_VERBOSE) {
-                x->exp_flags &= ~EF_VERBOSE;
-                post ("verbose off");
-        } else {
-                x->exp_flags |= EF_VERBOSE;
-                post ("verbose on");
-        }
-}
-
-/*
- * expr_start -- turn on expr processing for now only used for fexpr~
- */
-static void
-expr_start(t_expr *x)
-{
-        x->exp_flags &= ~EF_STOP;
-}
-
-/*
- * expr_stop -- turn on expr processing for now only used for fexpr~
- */
-static void
-expr_stop(t_expr *x)
-{
-        x->exp_flags |= EF_STOP;
-}
-static void
-fexpr_set_usage(void)
-{
-        post("fexpr~: set val ...");
-        post("fexpr~: set {xy}[#] val ...");
-}
-
-/*
- * fexpr_tilde_set -- set previous values of the buffers
- *              set val val ... - sets the first elements of output buffers
- *              set x val ...   - sets the elements of the first input buffer
- *              set x# val ...  - sets the elements of the #th input buffers
- *              set y val ...   - sets the elements of the first output buffer
- *              set y# val ...  - sets the elements of the #th output buffers
- */
-static void
-fexpr_tilde_set(t_expr *x, t_symbol *s, int argc, t_atom *argv)
-{
-        t_symbol *sx;
-        int vecno;
-        int i, nargs;
-
-        if (!argc)
-                return;
-        sx = atom_getsymbolarg(0, argc, argv);
-        switch(sx->s_name[0]) {
-        case 'x':
-                if (!sx->s_name[1])
-                        vecno = 0;
-                else {
-                        vecno = atoi(sx->s_name + 1);
-                        if (!vecno) {
-                                post("fexpr~.set: bad set x vector number");
-                                fexpr_set_usage();
-                                return;
-                        }
-                        if (vecno >= MAX_VARS) {
-                                post("fexpr~.set: no more than %d inlets",
-                                                                      MAX_VARS);
-                                return;
-                        }
-                        vecno--;
-                }
-                if (x->exp_var[vecno].ex_type != ET_XI) {
-                        post("fexpr~-set: no signal at inlet %d", vecno + 1);
-                        return;
-                }
-                nargs = argc - 1;
-                if (!nargs) {
-                        post("fexpr~-set: no argument to set");
-                        return;
-                }
-                if (nargs > x->exp_vsize) {
-                   post("fexpr~.set: %d set values larger than vector size(%d)",
-                                                        nargs,  x->exp_vsize);
-                   post("fexpr~.set: only the first %d values will be set",
-                                                                x->exp_vsize);
-                   nargs = x->exp_vsize;
-                }
-                for (i = 0; i < nargs; i++) {
-                        x->exp_p_var[vecno][x->exp_vsize - i - 1] =
-                                        atom_getfloatarg(i + 1, argc, argv);
-                }
-                return;
-        case 'y':
-                if (!sx->s_name[1])
-                        vecno = 0;
-                else {
-                        vecno = atoi(sx->s_name + 1);
-                        if (!vecno) {
-                                post("fexpr~.set: bad set y vector number");
-                                fexpr_set_usage();
-                                return;
-                        }
-                        vecno--;
-                }
-                if (vecno >= x->exp_nexpr) {
-                        post("fexpr~.set: only %d outlets", x->exp_nexpr);
-                        return;
-                }
-                nargs = argc - 1;
-                if (!nargs) {
-                        post("fexpr~-set: no argument to set");
-                        return;
-                }
-                if (nargs > x->exp_vsize) {
-                   post("fexpr~-set: %d set values larger than vector size(%d)",
-                                                        nargs,  x->exp_vsize);
-                   post("fexpr~.set: only the first %d values will be set",
-                                                                x->exp_vsize);
-                   nargs = x->exp_vsize;
-                }
-                for (i = 0; i < nargs; i++) {
-                        x->exp_p_res[vecno][x->exp_vsize - i - 1] =
-                                        atom_getfloatarg(i + 1, argc, argv);
-                }
-                return;
-        case 0:
-                if (argc >  x->exp_nexpr) {
-                        post("fexpr~.set: only %d outlets available",
-                                                                x->exp_nexpr);
-                        post("fexpr~.set: the extra set values are ignored");
-                }
-                for (i = 0; i < x->exp_nexpr && i < argc; i++)
-                        x->exp_p_res[i][x->exp_vsize - 1] =
-                                        atom_getfloatarg(i, argc, argv);
-                return;
-        default:
-                fexpr_set_usage();
-                return;
-        }
-        return;
-}
-
-/*
- * fexpr_tilde_clear - clear the past buffers
- */
-static void
-fexpr_tilde_clear(t_expr *x, t_symbol *s, int argc, t_atom *argv)
-{
-        t_symbol *sx;
-        int vecno;
-        int i, nargs;
-
-        /*
-         *  if no arguement clear all input and output buffers
-         */
-        if (!argc) {
-                for (i = 0; i < x->exp_nexpr; i++)
-                        memset(x->exp_p_res[i], 0, x->exp_vsize*sizeof(float));
-                for (i = 0; i < MAX_VARS; i++)
-                        if (x->exp_var[i].ex_type == ET_XI)
-                                memset(x->exp_p_var[i], 0,
-                                                x->exp_vsize*sizeof(float));
-                return;
-        }
-        if (argc > 1) {
-                post("fexpr~ usage: 'clear' or 'clear {xy}[#]'");
-                return;
-        }
-
-        sx = atom_getsymbolarg(0, argc, argv);
-        switch(sx->s_name[0]) {
-        case 'x':
-                if (!sx->s_name[1])
-                        vecno = 0;
-                else {
-                        vecno = atoi(sx->s_name + 1);
-                        if (!vecno) {
-                                post("fexpr~.clear: bad clear x vector number");
-                                return;
-                        }
-                        if (vecno >= MAX_VARS) {
-                                post("fexpr~.clear: no more than %d inlets",
-                                                                      MAX_VARS);
-                                return;
-                        }
-                        vecno--;
-                }
-                if (x->exp_var[vecno].ex_type != ET_XI) {
-                        post("fexpr~-clear: no signal at inlet %d", vecno + 1);
-                        return;
-                }
-                memset(x->exp_p_var[vecno], 0, x->exp_vsize*sizeof(float));
-                return;
-        case 'y':
-                if (!sx->s_name[1])
-                        vecno = 0;
-                else {
-                        vecno = atoi(sx->s_name + 1);
-                        if (!vecno) {
-                                post("fexpr~.clear: bad clear y vector number");
-                                return;
-                        }
-                        vecno--;
-                }
-                if (vecno >= x->exp_nexpr) {
-                        post("fexpr~.clear: only %d outlets", x->exp_nexpr);
-                        return;
-                }
-                memset(x->exp_p_res[vecno], 0, x->exp_vsize*sizeof(float));
-                return;
-                return;
-        default:
-                post("fexpr~ usage: 'clear' or 'clear {xy}[#]'");
-                return;
-        }
-        return;
-}
-
-#ifdef PD
-
-void
-expr_setup(void)
-{
-        /*
-         * expr initialization
-         */
-        expr_class = class_new(gensym("expr"), (t_newmethod)expr_new,
-            (t_method)expr_ff, sizeof(t_expr), 0, A_GIMME, 0);
-        class_addlist(expr_class, expr_list);
-        exprproxy_class = class_new(gensym("exprproxy"), 0,
-                                        0, sizeof(t_exprproxy), CLASS_PD, 0);
-        class_addfloat(exprproxy_class, exprproxy_float);
-
-        /*
-         * expr~ initialization
-         */
-        expr_tilde_class = class_new(gensym("expr~"), (t_newmethod)expr_new,
-            (t_method)expr_ff, sizeof(t_expr), 0, A_GIMME, 0);
-        class_addmethod(expr_tilde_class, nullfn, gensym("signal"), 0);
-        CLASS_MAINSIGNALIN(expr_tilde_class, t_expr, exp_f);
-        class_addmethod(expr_tilde_class,(t_method)expr_dsp, gensym("dsp"), 0);
-        class_sethelpsymbol(expr_tilde_class, gensym("expr"));
-        /*
-         * fexpr~ initialization
-         */
-        fexpr_tilde_class = class_new(gensym("fexpr~"), (t_newmethod)expr_new,
-            (t_method)expr_ff, sizeof(t_expr), 0, A_GIMME, 0);
-        class_addmethod(fexpr_tilde_class, nullfn, gensym("signal"), 0);
-        class_addmethod(fexpr_tilde_class,(t_method)expr_start,
-                                                        gensym("start"), 0);
-        class_addmethod(fexpr_tilde_class,(t_method)expr_stop,
-                                                        gensym("stop"), 0);
-
-        class_addmethod(fexpr_tilde_class,(t_method)expr_dsp,gensym("dsp"), 0);
-        class_addmethod(fexpr_tilde_class, (t_method)fexpr_tilde_set,
-                        gensym("set"), A_GIMME, 0);
-        class_addmethod(fexpr_tilde_class, (t_method)fexpr_tilde_clear,
-                        gensym("clear"), A_GIMME, 0);
-        class_addmethod(fexpr_tilde_class,(t_method)expr_verbose,
-                                                        gensym("verbose"), 0);
-        class_sethelpsymbol(fexpr_tilde_class, gensym("expr"));
-
-
-
-        post("expr, expr~, fexpr~ version %s under GNU General Public License ", exp_version);
-
-}
-
-void
-expr_tilde_setup(void)
-{
-        expr_setup();
-}
-
-void
-fexpr_tilde_setup(void)
-{
-        expr_setup();
-}
-#else /* MSP */
-void
-main(void)
-{
-        setup((t_messlist **)&expr_tilde_class, (method)Nexpr_new,
-                (method)expr_ff, (short)sizeof(t_expr), 0L, A_GIMME, 0);
-        addmess((method)expr_dsp, "dsp", A_CANT, 0); // dsp method
-        dsp_initclass();
-}
-#endif
-
-
-/* -- the following functions use Pd internals and so are in the "if" file. */
-
-
-int
-ex_getsym(char *p, fts_symbol_t *s)
-{
-        *s = gensym(p);
-        return (0);
-}
-
-const char *
-ex_symname(fts_symbol_t s)
-{
-        return (fts_symbol_name(s));
-}
-
-/*
- * max_ex_tab -- evaluate this table access
- *               eptr is the name of the table and arg is the index we
- *               have to put the result in optr
- *               return 1 on error and 0 otherwise
- *
- * Arguments:
- *  the expr object
- *  table 
- *  the argument 
- *  the result pointer 
- */
-int
-max_ex_tab(struct expr *expr, fts_symbol_t s, struct ex_ex *arg,
-    struct ex_ex *optr)
-{
-#ifdef PD
-        t_garray *garray;
-        int size, indx;
-        t_word *wvec;
-
-        if (!s || !(garray = (t_garray *)pd_findbyclass(s, garray_class)) ||
-            !garray_getfloatwords(garray, &size, &wvec))
-        {
-                optr->ex_type = ET_FLT;
-                optr->ex_flt = 0;
-                pd_error(expr, "no such table '%s'", s->s_name);
-                return (1);
-        }
-        optr->ex_type = ET_FLT;
-
-        switch (arg->ex_type) {
-        case ET_INT:
-                indx = arg->ex_int;
-                break;
-        case ET_FLT:
-                /* strange interpolation code deleted here -msp */
-                indx = arg->ex_flt;
-                break;
-
-        default:        /* do something with strings */
-                pd_error(expr, "expr: bad argument for table '%s'\n", fts_symbol_name(s));
-                indx = 0;
-        }
-        if (indx < 0) indx = 0;
-        else if (indx >= size) indx = size - 1;
-        optr->ex_flt = wvec[indx].w_float;
-#else /* MSP */
-        /*
-         * table lookup not done for MSP yet
-         */
-        post("max_ex_tab: not complete for MSP yet!");
-        optr->ex_type = ET_FLT;
-        optr->ex_flt = 0;
-#endif  
-        return (0);
-}
-
-int
-max_ex_var(struct expr *expr, fts_symbol_t var, struct ex_ex *optr)
-{
-        optr->ex_type = ET_FLT;
-        if (value_getfloat(var, &(optr->ex_flt))) {
-                optr->ex_type = ET_FLT;
-                optr->ex_flt = 0;
-                pd_error(expr, "no such var '%s'", var->s_name);
-                return (1);
-        }
-        return (0);
-}
-
-#ifdef PD /* this goes to the end of this file as the following functions
-           * should be defined in the expr object in MSP
-           */
-#define ISTABLE(sym, garray, size, vec)                               \
-if (!sym || !(garray = (t_garray *)pd_findbyclass(sym, garray_class)) || \
-                !garray_getfloatwords(garray, &size, &vec))  {          \
-        optr->ex_type = ET_FLT;                                         \
-        optr->ex_int = 0;                                               \
-        error("no such table '%s'", sym->s_name);                       \
-        return;                                                         \
-}
-
-/*
- * ex_size -- find the size of a table
- */
-void
-ex_size(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        t_symbol *s;
-        t_garray *garray;
-        int size;
-        t_word *wvec;
-
-        if (argv->ex_type != ET_SYM)
-        {
-                post("expr: size: need a table name\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                return;
-        }
-
-        s = (fts_symbol_t ) argv->ex_ptr;
-
-        ISTABLE(s, garray, size, wvec);
-
-        optr->ex_type = ET_INT;
-        optr->ex_int = size;
-}
-
-/*
- * ex_sum -- calculate the sum of all elements of a table
- */
-
-void
-ex_sum(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        t_symbol *s;
-        t_garray *garray;
-        int size;
-        t_word *wvec;
-        float sum;
-        int indx;
-
-        if (argv->ex_type != ET_SYM)
-        {
-                post("expr: sum: need a table name\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                return;
-        }
-
-        s = (fts_symbol_t ) argv->ex_ptr;
-
-        ISTABLE(s, garray, size, wvec);
-
-        for (indx = 0, sum = 0; indx < size; indx++)
-                sum += wvec[indx].w_float;
-
-        optr->ex_type = ET_FLT;
-        optr->ex_flt = sum;
-}
-
-
-/*
- * ex_Sum -- calculate the sum of table with the given boundries
- */
-
-void
-ex_Sum(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-        t_symbol *s;
-        t_garray *garray;
-        int size;
-        t_word *wvec;
-        t_float sum;
-        int indx, n1, n2;
-
-        if (argv->ex_type != ET_SYM)
-        {
-                post("expr: sum: need a table name\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                return;
-        }
-
-        s = (fts_symbol_t ) argv->ex_ptr;
-
-        ISTABLE(s, garray, size, wvec);
-
-        if (argv->ex_type != ET_INT || argv[1].ex_type != ET_INT)
-        {
-                post("expr: Sum: boundries have to be fix values\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                return;
-        }
-        n1 = argv->ex_int;
-        n2 = argv[1].ex_int;
-
-        for (indx = n1, sum = 0; indx < n2; indx++)
-                if (indx >= 0 && indx < size)
-                        sum += wvec[indx].w_float;
-
-        optr->ex_type = ET_FLT;
-        optr->ex_flt = sum;
-}
-
-/*
- * ex_avg -- calculate the avarage of a table
- */
-
-void
-ex_avg(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-/* SDY - look into this function */
-#if 0
-        fts_symbol_t s;
-        fts_integer_vector_t *tw = 0;
-
-        if (argv->ex_type != ET_SYM)
-        {
-                post("expr: avg: need a table name\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-        }
-
-        s = (fts_symbol_t ) argv->ex_ptr;
-
-        tw = table_integer_vector_get_by_name(s);
-
-        if (tw)
-        {
-                optr->ex_type = ET_INT;
-
-                if (! fts_integer_vector_get_size(tw))
-                        optr->ex_int = 0;
-                else
-                        optr->ex_int = fts_integer_vector_get_sum(tw) / fts_integer_vector_get_size(tw);
-        }
-        else
-        {
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                post("expr: avg: no such table %s\n", fts_symbol_name(s));
-        }
-#endif
-}
-
-
-/*
- * ex_Avg -- calculate the avarage of table with the given boundries
- */
-
-void
-ex_Avg(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-/* SDY - look into this function */
-#if 0
-        fts_symbol_t s;
-        fts_integer_vector_t *tw = 0;
-
-        if (argv->ex_type != ET_SYM)
-        {
-                post("expr: Avg: need a table name\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-        }
-
-        s = (fts_symbol_t ) (argv++)->ex_ptr;
-
-        tw = table_integer_vector_get_by_name(s);
-
-        if (! tw)
-        {
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                post("expr: Avg: no such table %s\n", fts_symbol_name(s));
-                return;
-        }
-
-        if (argv->ex_type != ET_INT || argv[1].ex_type != ET_INT)
-        {
-                post("expr: Avg: boundries have to be fix values\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                return;
-        }
-
-        optr->ex_type = ET_INT;
-
-        if (argv[1].ex_int - argv->ex_int <= 0)
-                optr->ex_int = 0;
-        else
-                optr->ex_int = (fts_integer_vector_get_sub_sum(tw, argv->ex_int, argv[1].ex_int) /
-                    (argv[1].ex_int - argv->ex_int));
-#endif
-}
-
-/*
- * ex_store -- store a value in a table
- *             if the index is greater the size of the table,
- *             we will make a modulo the size of the table
- */
-
-void
-ex_store(t_expr *e, long int argc, struct ex_ex *argv, struct ex_ex *optr)
-{
-/* SDY - look into this function */
-#if 0
-        fts_symbol_t s;
-        fts_integer_vector_t *tw = 0;
-
-        if (argv->ex_type != ET_SYM)
-        {
-                post("expr: store: need a table name\n");
-        }
-
-        s = (fts_symbol_t ) (argv++)->ex_ptr;
-
-        tw = table_integer_vector_get_by_name(s);
-
-        if (! tw)
-        {
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-                post("expr: store: no such table %s\n", fts_symbol_name(s));
-                return;
-        }
-
-        if (argv->ex_type != ET_INT || argv[1].ex_type != ET_INT)
-        {
-                post("expr: store: arguments have to be integer\n");
-                optr->ex_type = ET_INT;
-                optr->ex_int = 0;
-        }
-
-        fts_integer_vector_set_element(tw, argv->ex_int < 0 ? 0 : argv->ex_int % fts_integer_vector_get_size(tw), argv[1].ex_int);
-        *optr = argv[1];
-#endif
-}
-
-#else /* MSP */
-
-void 
-pd_error(void *object, char *fmt, ...)
-{
-    va_list ap;
-    t_int arg[8];
-    int i;
-    static int saidit = 0;
-    va_start(ap, fmt);
-/* SDY
-    vsprintf(error_string, fmt, ap);
- */ post(fmt, ap);
-        va_end(ap);
-/* SDY
-    fprintf(stderr, "error: %s\n", error_string);
-    error_object = object;
-*/
-    if (!saidit)
-    {
-        post("... you might be able to track this down from the Find menu.");
-        saidit = 1;
-    }
-}
-#endif
diff --git a/extra/fiddle~/fiddle~-help.pd b/extra/fiddle~/fiddle~-help.pd
deleted file mode 100644
index f396725a0..000000000
--- a/extra/fiddle~/fiddle~-help.pd
+++ /dev/null
@@ -1,142 +0,0 @@
-#N canvas 93 26 980 745 10;
-#X obj 262 522 phasor~;
-#X obj 531 616 unpack;
-#X floatatom 531 666 0 0 0 0 - - -;
-#X msg 437 449 print;
-#X obj 262 500 sig~;
-#X floatatom 262 478 0 0 0 0 - - -;
-#X obj 262 456 mtof;
-#X floatatom 262 434 0 0 0 0 - - -;
-#X floatatom 545 643 0 0 0 0 - - -;
-#X obj 531 576 route 1 2 3 4;
-#X obj 614 616 unpack;
-#X floatatom 614 666 0 0 0 0 - - -;
-#X floatatom 628 643 0 0 0 0 - - -;
-#X obj 698 616 unpack;
-#X floatatom 698 666 0 0 0 0 - - -;
-#X floatatom 712 643 0 0 0 0 - - -;
-#X obj 389 616 unpack;
-#X floatatom 389 666 0 0 0 0 - - -;
-#X floatatom 403 643 0 0 0 0 - - -;
-#X obj 334 545 *~;
-#X obj 322 394 loadbang;
-#X obj 353 522 sig~;
-#X floatatom 353 500 0 0 0 0 - - -;
-#X msg 322 478 1;
-#X msg 353 478 0;
-#X floatatom 466 666 0 0 0 0 - - -;
-#X obj 281 666 print attack;
-#X obj 190 666 print pitch;
-#X msg 555 45 \; pd dsp 1;
-#X text 460 39 click here;
-#X text 460 61 to start DSP;
-#X text 226 4 FIDDLE - pitch estimator and sinusoidal peak finder;
-#X text 8 70 The Fiddle object estimates the pitch and amplitude of
-an incoming sound \, both continuously and as a stream of discrete
-"note" events. Fiddle optionally outputs a list of detected sinusoidal
-peaks used to make the pitch determination. Fiddle is described theoretically
-in the 1998 ICMC proceedings \, reprinted on http://man104nfs.ucsd.edu/~mpuckett.
-;
-#X text 8 170 Fiddle's creation arguments specify an analysis window
-size \, the maximum polyphony (i.e. \, the number of simultaneous "pitches"
-to try to find) \, the number of peaks in the spectrum to consider
-\, and the number of peaks \, if any \, to output "raw." The outlets
-give discrete pitch (a number) \, detected attacks in the amplitude
-envelope (a bang) \, one or more voices of continuous pitch and amplitude
-\, overall amplitude \, and optionally a sequence of messages with
-the peaks.;
-#X text 8 296 The analysis hop size is half the window size so in the
-example shown here \, one analysis is done every 512 samples (11.6
-msec at 44K1) \, and the analysis uses the most recent 1024 samples
-(23.2 msec at 44K1). The minimum frequency that Fiddle will report
-is 2-1/2 cycles per analysis windows \, or about 108 Hz. (just below
-MIDI 45.);
-#X text 669 535 number of pitch outlets (1-3 \, default 1);
-#X text 669 557 number of peaks to find (1-100 \, default 20);
-#X text 669 579 number of peaks to output (default 0.);
-#X msg 441 107 amp-range 40 50;
-#X msg 439 227 reattack 100 10;
-#X msg 438 282 npartial 7;
-#X msg 438 170 vibrato 50 0.5;
-#X text 560 91 a low and high amplitude threshold: if signal amplitude
-is below the low threshold \, no pitches or peaks are output. The high
-threshold is a minimum at which "cooked" outputs may appear.;
-#X text 560 152 A period in milliseconds (50) over which the raw pitch
-may not deviate more than an interval in half-tones (0.5) from the
-average pitch to report it as a note to the "cooked" pitch outlet.
-;
-#X text 560 213 A period in milliseconds (100) over which a re-attack
-is reported if the amplitude rises more than (1) dB. The re-attack
-will result in a "bang" in the attack outlet and may give rise to repeated
-notes in the cooked pitch output.;
-#X text 142 432 test input pitch;
-#X text 330 444 test input;
-#X text 330 457 amplitude;
-#X obj 410 545 fiddle~ 1024 1 20 3;
-#X text 538 690 individual sinusoidal components;
-#X text 466 688 amplitude;
-#X text 476 703 (dB);
-#X text 389 688 raw pitch;
-#X text 376 712 and amplitude;
-#X text 364 729 (up to 3 outputs);
-#X text 287 686 bang on;
-#X text 287 708 attack;
-#X text 185 686 cooked pitch;
-#X text 202 703 output;
-#X text 545 545 ------ arguments:;
-#X msg 262 412 57;
-#X msg 440 331 auto 1;
-#X msg 440 353 auto 0;
-#X msg 439 418 bang;
-#X text 561 416 poll current values --- useful if not in auto mode
-\,;
-#X text 560 274 Higher partials are weighed less strongly than lower
-ones in determining the pitch. This specifies the number of the partial
-(7) which will be weighted half as strongly as the fundamental.;
-#X text 560 335 start and stop "auto" mode (on by default.) If off
-\, output only appears on "bang" (poll mode).;
-#X text 561 448 print out all settings;
-#X text 669 513 window size (128-2048 \, default 1024);
-#X msg 440 375 npoints 2048;
-#X text 562 384 number of points in analysis window (power of 2 \,
-128-2048);
-#X msg 439 396 npoints 1024;
-#X connect 0 0 19 0;
-#X connect 1 0 2 0;
-#X connect 1 1 8 0;
-#X connect 3 0 48 0;
-#X connect 4 0 0 0;
-#X connect 5 0 4 0;
-#X connect 6 0 5 0;
-#X connect 7 0 6 0;
-#X connect 9 0 1 0;
-#X connect 9 1 10 0;
-#X connect 9 2 13 0;
-#X connect 10 0 11 0;
-#X connect 10 1 12 0;
-#X connect 13 0 14 0;
-#X connect 13 1 15 0;
-#X connect 16 0 17 0;
-#X connect 16 1 18 0;
-#X connect 19 0 48 0;
-#X connect 20 0 60 0;
-#X connect 20 0 23 0;
-#X connect 21 0 19 1;
-#X connect 22 0 21 0;
-#X connect 23 0 22 0;
-#X connect 24 0 22 0;
-#X connect 38 0 48 0;
-#X connect 39 0 48 0;
-#X connect 40 0 48 0;
-#X connect 41 0 48 0;
-#X connect 48 0 27 0;
-#X connect 48 1 26 0;
-#X connect 48 2 16 0;
-#X connect 48 3 25 0;
-#X connect 48 4 9 0;
-#X connect 60 0 7 0;
-#X connect 61 0 48 0;
-#X connect 62 0 48 0;
-#X connect 63 0 48 0;
-#X connect 69 0 48 0;
-#X connect 71 0 48 0;
diff --git a/extra/fiddle~/fiddle~.c b/extra/fiddle~/fiddle~.c
deleted file mode 100644
index ea4886d90..000000000
--- a/extra/fiddle~/fiddle~.c
+++ /dev/null
@@ -1,1845 +0,0 @@
-/* Copyright (c) 1997-1999 Miller Puckette and Ted Apel.
-* For information on usage and redistribution, and for a DISCLAIMER OF ALL
-* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */
-
-/*
- * Fiddle is a pitch tracker hardwired to have hop size ("H") equal to
- * half its window size ("N").
- *
- * This version should compile for Max "0.26," JMAX, Pd, or Max/MSP.
- *
- * The "lastanalysis" field holds the shifted FT of the previous H
- * samples.  The buffer contains in effect points 1/2,  3/2, ..., (N-1)/2
- * of the DTFT of a real vector of length N, half of whose points are zero,
- * i.e.,  only the first H points are used.  Put another way, we get the
- * the odd-numbered points of the FFT of the H points, zero padded to 4*H in
- * length. The integer points 0, 1, ..., H-1
- * are found by interpolating these others,  using the fact that the
- * half-integer points are band-limited (they only have positive frequencies.)
- * To facilitate the interpolation the "lastanalysis" buffer contains
- * FILTSIZE extra points (1/2-FILTSIZE, ...,  -1/2) at the beginning and
- * FILTSIZE again at the end ((N+1)/2, ..., FILTSIZE+(N-1)/2).  The buffer
- * therefore has N+4*FILTSIZE floating-point numbers in it.
- *
- * after doing this I found out that you can just do a real FFT
- * of the H new points, zero-padded to contain N points, and using a similar
- * but simpler interpolation scheme you can still get 2N points of the DTFT
- * of the N points.  Jean Laroche is a big fat hen.
- *
- */
-
-#ifdef _MSC_VER /* this is only needed with Microsoft's compiler */
-#define flog log
-#define fexp exp
-#define fsqrt sqrt
-#pragma warning (disable: 4305 4244)
-#else
-#define flog log
-#define fexp exp
-#define fsqrt sqrt
-#endif
-
-char fiddle_version[] = "fiddle version 1.1 TEST4";
-
-#ifdef JMAX
-#include "fts.h"
-#include <stdio.h>
-#include <stdlib.h>
-typedef float t_float;
-typedef float t_floatarg;
-typedef fts_symbol_t t_symbol;
-
-static void *getbytes(size_t nbytes)
-{
-    void *ret;
-    if (nbytes < 1) nbytes = 1;
-    ret = (void *)malloc(nbytes);
-    return (ret);
-}
-
-static void *resizebytes(void *old, size_t oldsize, size_t newsize)
-{
-    void *ret;
-    if (newsize < 1) newsize = 1;
-    ret = (void *)realloc((char *)old, newsize);
-    return (ret);
-}
-
-static void freebytes(void *fatso, size_t nbytes)
-{
-    free(fatso);
-}
-
-#define CLASSNAME "fiddle"
-
-#define OUTLETpower 5
-#define OUTLETmicropitch1 4
-#define OUTLETmicropitch2 3
-#define OUTLETmicropitch3 2
-#define OUTLETattack 1
-#define OUTLETpitch 0
-
-static fts_symbol_t *dsp_symbol = 0;
-#define error post
-
-#endif /* FTS */
-
-#ifdef MAX26
-#define t_floatarg double
-#include "m_extern.h"
-#include "d_graph.h"
-#include "d_ugen.h"
-#endif /* MAX26 */
-
-#ifdef PD
-#include "m_pd.h"
-#endif /* PD */
-
-#ifdef MSP
-#define flog log
-#define fexp exp
-#define fsqrt sqrt
-#endif /* MSP */
-
-#ifdef MSP
-#define t_floatarg double
-#include "ext.h"
-#include "z_dsp.h"
-#include "fft_mayer.proto.h"
-
-#endif /* MSP */
-
-#include <math.h>
-
-
-#define MINBIN 3
-#define DEFAMPLO 40
-#define DEFAMPHI 50
-#define DEFATTACKTIME 100
-#define DEFATTACKTHRESH 10
-#define DEFVIBTIME 50
-#define DEFVIBDEPTH 0.5
-#define GLISS 0.7f
-#define DBFUDGE 30.8f
-#define MINFREQINBINS 5     /* minimum frequency in bins for reliable output */
-
-#define MAXNPITCH 3
-#define MAXHIST 3                   /* find N hottest peaks in histogram */
-
-#define MAXPOINTS 8192
-#define MINPOINTS 128
-#define DEFAULTPOINTS 1024
-
-#define HISTORY 20
-#define MAXPEAK 100             /* maximum number of peaks */
-#define DEFNPEAK 20             /* default number of peaks */
-
-#define MAXNPEAK (MAXLOWPEAK + MAXSTRONGPEAK)
-#define MINBW (0.03f)                   /* consider BW >= 0.03 FFT bins */
-
-#define BINPEROCT 48                    /* bins per octave */
-#define BPERO_OVER_LOG2 69.24936196f    /* BINSPEROCT/log(2) */
-#define FACTORTOBINS (float)(4/0.0145453)       /* 4 / (pow(2.,1/48.) - 1) */
-#define BINGUARD 10                     /* extra bins to throw in front */
-#define PARTIALDEVIANCE 0.023f          /* acceptable partial detuning in % */
-#define LOGTODB 4.34294481903f          /* 20/log(10) */
-
-#define KNOCKTHRESH 10.f     /* don't know how to describe this */
-
-
-static float sigfiddle_partialonset[] =
-{
-0,
-48,
-76.0782000346154967102,
-96,
-111.45254855459339269887,
-124.07820003461549671089,
-134.75303625876499715823,
-144,
-152.15640006923099342109,
-159.45254855459339269887,
-166.05271769459026829915,
-172.07820003461549671088,
-177.62110647077242370064,
-182.75303625876499715892,
-187.53074858920888940907,
-192,
-};
-
-#define NPARTIALONSET ((int)(sizeof(sigfiddle_partialonset)/sizeof(float)))
-
-static int sigfiddle_intpartialonset[] =
-{
-0,
-48,
-76,
-96,
-111,
-124,
-135,
-144,
-152,
-159,
-166,
-172,
-178,
-183,
-188,
-192,
-};
-
-/* these coefficients, which come from the "upsamp" subdirectory,
-are a filter kernel for upsampling by a factor of two, assuming
-the sound to be upsampled has no energy above half the Nyquist, i.e.,
-that it's already 2x oversampled compared to the theoretically possible
-sample rate.  I got these by trial and error. */
-
-#define FILT1 ((float)(.5 * 1.227054))
-#define FILT2 ((float)(.5 * -0.302385))
-#define FILT3 ((float)(.5 * 0.095326))
-#define FILT4 ((float)(.5 * -0.022748))
-#define FILT5 ((float)(.5 * 0.002533))
-#define FILTSIZE 5
-
-typedef struct peakout      /* a peak for output */
-{
-    float po_freq;                  /* frequency in hz */
-    float po_amp;                   /* amplitude */
-} t_peakout;
-
-typedef struct peak         /* a peak for analysis */
-{
-    float p_freq;                   /* frequency in bins */
-    float p_width;                  /* peak width in bins */
-    float p_pow;                    /* peak power */
-    float p_loudness;               /* 4th root of power */
-    float *p_fp;                    /* pointer back to spectrum */
-} t_peak;
-
-typedef struct histopeak
-{
-    float h_pitch;                  /* estimated pitch */
-    float h_value;                  /* value of peak */
-    float h_loud;                   /* combined strength of found partials */
-    int h_index;                    /* index of bin holding peak */
-    int h_used;                     /* true if an x_hist entry points here */
-} t_histopeak;
-
-typedef struct pitchhist            /* struct for keeping history by pitch */
-{
-    float h_pitch;                  /* pitch to output */
-    float h_amps[HISTORY];          /* past amplitudes */
-    float h_pitches[HISTORY];       /* past pitches */
-    float h_noted;                  /* last pitch output */
-    int h_age;                      /* number of frames pitch has been there */
-    t_histopeak *h_wherefrom;       /* new histogram peak to incorporate */
-    void *h_outlet;
-} t_pitchhist;
-
-typedef struct sigfiddle                    /* instance struct */
-{
-#ifdef JMAX
-    fts_object_t x_h;               /* object header */
-    fts_alarm_t x_clock;            /* callback for timeouts */
-#endif
-#ifdef MAX26
-    t_head x_h;                     /* header for tilde objects */
-    t_sig *x_io[IN1+OUT0];          /* number of signal inputs and outputs */
-    void *x_clock;                  /* a "clock" object */
-#endif
-#ifdef PD
-    t_object x_ob;                  /* object header */
-    t_clock *x_clock;               /* callback for timeouts */
-#endif
-#ifdef MSP
-        t_pxobject x_obj;
-        void *x_clock;
-        long x_downsample;              /* downsample feature because of
-                                         MSP's large sig vector sizes */
-#endif
-    float *x_inbuf;                 /* buffer to analyze, npoints/2 elems */
-    float *x_lastanalysis;          /* FT of last buffer (see main comment) */
-    float *x_spiral;                /* 1/4-wave complex exponential */
-    t_peakout *x_peakbuf;           /* spectral peaks for output */
-    int x_npeakout;                 /* number of spectral peaks to output */
-    int x_npeakanal;                /* number of spectral peaks to analyze */
-    int x_phase;                    /* number of points since last output */
-    int x_histphase;                /* phase into amplitude history vector */
-    int x_hop;                      /* period of output, npoints/2 */
-    float x_sr;                     /* sample rate */
-    t_pitchhist x_hist[MAXNPITCH];  /* history of current pitches */
-    int x_nprint;                   /* how many periods to print */
-    int x_npitch;                   /* number of simultaneous pitches */
-    float x_dbs[HISTORY];           /* DB history, indexed by "histphase" */
-    float x_peaked;                 /* peak since last attack */
-    int x_dbage;                    /* number of bins DB has met threshold */
-    int x_auto;                     /* true if generating continuous output */
-/* parameters */
-    float x_amplo;
-    float x_amphi;
-    int x_attacktime;
-    int x_attackbins;
-    float x_attackthresh;
-    int x_vibtime;
-    int x_vibbins;
-    float x_vibdepth;
-    float x_npartial;
-/* outlets & clock */
-    void *x_envout;
-    int x_attackvalue;
-    void *x_attackout;
-    void *x_noteout;
-    void *x_peakout;
-} t_sigfiddle;
-
-#if CHECKER
-float fiddle_checker[1024];
-#endif
-
-#ifdef MSP
-/* Mac compiler requires prototypes for everything */
-
-int sigfiddle_ilog2(int n);
-float fiddle_mtof(float f);
-float fiddle_ftom(float f);
-void sigfiddle_doit(t_sigfiddle *x);
-void sigfiddle_debug(t_sigfiddle *x);
-void sigfiddle_print(t_sigfiddle *x);
-void sigfiddle_assist(t_sigfiddle *x, void *b, long m, long a, char *s);
-void sigfiddle_amprange(t_sigfiddle *x, double amplo,  double amphi);
-void sigfiddle_reattack(t_sigfiddle *x, t_floatarg attacktime, t_floatarg
-attackthresh);
-void sigfiddle_vibrato(t_sigfiddle *x, t_floatarg vibtime, t_floatarg
-vibdepth);
-void sigfiddle_npartial(t_sigfiddle *x, double npartial);
-void sigfiddle_auto(t_sigfiddle *x, t_floatarg f);
-void sigfiddle_setnpoints(t_sigfiddle *x, t_floatarg f);
-int sigfiddle_doinit(t_sigfiddle *x, long npoints, long npitch, long
-npeakanal, long npeakout);
-static t_int *fiddle_perform(t_int *w);
-void sigfiddle_dsp(t_sigfiddle *x, t_signal **sp);
-void sigfiddle_tick(t_sigfiddle *x);
-void sigfiddle_bang(t_sigfiddle *x);
-void sigfiddle_ff(t_sigfiddle *x);
-void *sigfiddle_new(long npoints, long npitch,
-    long npeakanal, long npeakout);
-void msp_fft(float *buf, long np, long inv);
-float msp_ffttemp[MAXPOINTS*2];
-int errno;
-#endif
-
-int sigfiddle_ilog2(int n)
-{
-    int ret = -1;
-    while (n)
-    {
-        n >>= 1;
-        ret++;
-    }
-    return (ret);
-}
-
-float fiddle_mtof(float f)
-{
-        return (8.17579891564 * exp(.0577622650 * f));
-}
-
-float fiddle_ftom(float f)
-{
-        return (17.3123405046 * log(.12231220585 * f));
-}
-#define ftom fiddle_ftom
-#define mtof fiddle_mtof
-
-void sigfiddle_doit(t_sigfiddle *x)
-{
-#ifdef MSP
-        /* prevents interrupt-level stack overflow crash with Netscape. */
-    static float spect1[4*MAXPOINTS];
-    static float spect2[MAXPOINTS + 4*FILTSIZE];
-#else
-    float spect1[4*MAXPOINTS];
-    float spect2[MAXPOINTS + 4*FILTSIZE];
-#endif
-#if CHECKER
-    float checker3[4*MAXPOINTS];
-#endif
-
-    t_peak peaklist[MAXPEAK + 1], *pk1;
-    t_peakout *pk2;
-    t_histopeak histvec[MAXHIST], *hp1;
-    int i, j, k, hop = x->x_hop, n = 2*hop, npeak, npitch,
-        logn = sigfiddle_ilog2(n), newphase, oldphase;
-    float *fp, *fp1, *fp2, *fp3, total_power, total_loudness, total_db;
-    float maxbin = BINPEROCT * (logn-2),  *histogram = spect2 + BINGUARD;
-    t_pitchhist *phist;
-    float hzperbin = x->x_sr / (2.0f * n);
-    int npeakout = x->x_npeakout, npeakanal = x->x_npeakanal;
-    int npeaktot = (npeakout > npeakanal ? npeakout : npeakanal);
-
-    oldphase = x->x_histphase;
-    newphase = x->x_histphase + 1;
-    if (newphase == HISTORY) newphase = 0;
-    x->x_histphase = newphase;
-
-        /*
-         * multiply the H points by a 1/4-wave complex exponential,
-         * and take FFT of the result.
-         */
-    for (i = 0, fp1 = x->x_inbuf, fp2 = x->x_spiral, fp3 = spect1;
-        i < hop; i++, fp1++, fp2 += 2, fp3 += 2)
-            fp3[0] = fp1[0] * fp2[0], fp3[1] = fp1[0] * fp2[1];
-
-#ifdef MAX26
-    fft(spect1, hop, 0);
-#endif
-#ifdef PD
-    pd_fft(spect1, hop, 0);
-#endif
-#ifdef JMAX
-    fts_cfft_inplc((complex *)spect1, hop);
-#endif
-#ifdef MSP
-        msp_fft(spect1,hop,0);
-#endif
-        /*
-         * now redistribute the points to get in effect the odd-numbered
-         * points of the FFT of the H points, zero padded to 4*H in length.
-         */
-    for (i = 0, fp1 = spect1, fp2 = spect2 + (2*FILTSIZE);
-        i < (hop>>1); i++, fp1 += 2, fp2 += 4)
-            fp2[0] = fp1[0], fp2[1] = fp1[1];
-    for (i = 0, fp1 = spect1 + n - 2, fp2 = spect2 + (2*FILTSIZE+2);
-        i < (hop>>1); i++, fp1 -= 2, fp2 += 4)
-            fp2[0] = fp1[0], fp2[1] = -fp1[1];
-    for (i = 0, fp1 = spect2 + (2*FILTSIZE), fp2 = spect2 + (2*FILTSIZE-2);
-        i<FILTSIZE; i++, fp1+=2, fp2-=2)
-            fp2[0] = fp1[0],  fp2[1] = -fp1[1];
-    for (i = 0, fp1 = spect2 + (2*FILTSIZE+n-2), fp2 = spect2 + (2*FILTSIZE+n);
-        i<FILTSIZE; i++, fp1-=2, fp2+=2)
-            fp2[0] = fp1[0],  fp2[1] = -fp1[1];
-#if 0
-    {
-        fp = spect2 + 2*FILTSIZE;
-        post("x1 re %12.4f %12.4f %12.4f %12.4f %12.4f",
-            fp[0], fp[2], fp[4], fp[6], fp[8]);
-        post("x1 im %12.4f %12.4f %12.4f %12.4f %12.4f",
-            fp[1], fp[3], fp[5], fp[7], fp[9]);
-    }
-#endif
-        /* spect2 is now prepared; now combine spect2 and lastanalysis into
-         * spect1.  Odd-numbered points of spect1 are the points of "last"
-         * plus (-i, i, -i, ...) times spect1.  Even-numbered points are
-         * the interpolated points of "last" plus (1, -1, 1, ...) times the
-         * interpolated points of spect1.
-         *
-         * To interpolate, take FILT1 exp(-pi/4) times
-         * the previous point,  FILT2*exp(-3*pi/4) times 3 bins before,
-         * etc,  and FILT1 exp(pi/4), FILT2 exp(3pi/4), etc., to weight
-         * the +1, +3, etc., points.
-         *
-         * In this calculation,  we take (1, i, -1, -i, 1) times the
-         * -9, -7, ..., -1 points, and (i, -1, -i, 1, i) times the 1, 3,..., 9
-         * points of the OLD spectrum, alternately adding and subtracting
-         * the new spectrum to the old; then we multiply the whole thing
-         * by exp(-i pi/4).
-         */
-    for (i = 0, fp1 = spect1, fp2 = x->x_lastanalysis + 2*FILTSIZE,
-        fp3 = spect2 + 2*FILTSIZE;
-            i < (hop>>1); i++)
-    {
-        float re,  im;
-
-        re= FILT1 * ( fp2[ -2] -fp2[ 1]  +fp3[ -2] -fp3[ 1]) +
-            FILT2 * ( fp2[ -3] -fp2[ 2]  +fp3[ -3] -fp3[ 2]) +
-            FILT3 * (-fp2[ -6] +fp2[ 5]  -fp3[ -6] +fp3[ 5]) +
-            FILT4 * (-fp2[ -7] +fp2[ 6]  -fp3[ -7] +fp3[ 6]) +
-            FILT5 * ( fp2[-10] -fp2[ 9]  +fp3[-10] -fp3[ 9]);
-
-        im= FILT1 * ( fp2[ -1] +fp2[ 0]  +fp3[ -1] +fp3[ 0]) +
-            FILT2 * (-fp2[ -4] -fp2[ 3]  -fp3[ -4] -fp3[ 3]) +
-            FILT3 * (-fp2[ -5] -fp2[ 4]  -fp3[ -5] -fp3[ 4]) +
-            FILT4 * ( fp2[ -8] +fp2[ 7]  +fp3[ -8] +fp3[ 7]) +
-            FILT5 * ( fp2[ -9] +fp2[ 8]  +fp3[ -9] +fp3[ 8]);
-
-        fp1[0] = 0.7071f * (re + im);
-        fp1[1] = 0.7071f * (im - re);
-        fp1[4] = fp2[0] + fp3[1];
-        fp1[5] = fp2[1] - fp3[0];
-        
-        fp1 += 8, fp2 += 2, fp3 += 2;
-        re= FILT1 * ( fp2[ -2] -fp2[ 1]  -fp3[ -2] +fp3[ 1]) +
-            FILT2 * ( fp2[ -3] -fp2[ 2]  -fp3[ -3] +fp3[ 2]) +
-            FILT3 * (-fp2[ -6] +fp2[ 5]  +fp3[ -6] -fp3[ 5]) +
-            FILT4 * (-fp2[ -7] +fp2[ 6]  +fp3[ -7] -fp3[ 6]) +
-            FILT5 * ( fp2[-10] -fp2[ 9]  -fp3[-10] +fp3[ 9]);
-
-        im= FILT1 * ( fp2[ -1] +fp2[ 0]  -fp3[ -1] -fp3[ 0]) +
-            FILT2 * (-fp2[ -4] -fp2[ 3]  +fp3[ -4] +fp3[ 3]) +
-            FILT3 * (-fp2[ -5] -fp2[ 4]  +fp3[ -5] +fp3[ 4]) +
-            FILT4 * ( fp2[ -8] +fp2[ 7]  -fp3[ -8] -fp3[ 7]) +
-            FILT5 * ( fp2[ -9] +fp2[ 8]  -fp3[ -9] -fp3[ 8]);
-
-        fp1[0] = 0.7071f * (re + im);
-        fp1[1] = 0.7071f * (im - re);
-        fp1[4] = fp2[0] - fp3[1];
-        fp1[5] = fp2[1] + fp3[0];
-        
-        fp1 += 8, fp2 += 2, fp3 += 2;
-    }
-#if 0
-    if (x->x_nprint)
-    {
-        for (i = 0,  fp = spect1; i < 16; i++,  fp+= 4)
-            post("spect %d %f %f --> %f", i, fp[0], fp[1],
-                sqrt(fp[0] * fp[0] + fp[1] * fp[1]));
-    }
-#endif
-         /* copy new spectrum out */
-    for (i = 0, fp1 = spect2, fp2 = x->x_lastanalysis;
-            i < n + 4*FILTSIZE; i++) *fp2++ = *fp1++;
-
-    for (i = 0; i < MINBIN; i++) spect1[4*i + 2] = spect1[4*i + 3] = 0;
-        /* starting at bin MINBIN, compute hanning windowed power spectrum */
-    for (i = MINBIN, fp1 = spect1+4*MINBIN, total_power = 0;
-        i < n-2; i++,  fp1 += 4)
-    {
-        float re = fp1[0] - 0.5f * (fp1[-8] + fp1[8]);
-        float im = fp1[1] - 0.5f * (fp1[-7] + fp1[9]);
-        fp1[3] = (total_power += (fp1[2] = re * re + im * im));
-    }
-
-    if (total_power > 1e-9f)
-    {
-        total_db = (100.f - DBFUDGE) + LOGTODB * log(total_power/n);
-        total_loudness = fsqrt(fsqrt(total_power));
-        if (total_db < 0) total_db = 0;
-    }
-    else total_db = total_loudness = 0;
-        /*  store new db in history vector */
-    x->x_dbs[newphase] = total_db;
-    if (total_db < x->x_amplo) goto nopow;
-#if 1
-    if (x->x_nprint) post("power %f", total_power);
-#endif
-
-#if CHECKER
-        /* verify that our FFT resampling thing is putting out good results */
-    for (i = 0; i < hop; i++)
-    {
-        checker3[2*i] = fiddle_checker[i];
-        checker3[2*i + 1] = 0;
-        checker3[n + 2*i] = fiddle_checker[i] = x->x_inbuf[i];
-        checker3[n + 2*i + 1] = 0;
-    }
-    for (i = 2*n; i < 4*n; i++) checker3[i] = 0;
-    fft(checker3, 2*n, 0);
-    if (x->x_nprint)
-    {
-        for (i = 0,  fp = checker3; i < 16; i++,  fp += 2)
-            post("spect %d %f %f --> %f", i, fp[0], fp[1],
-                sqrt(fp[0] * fp[0] + fp[1] * fp[1]));
-    }
-
-#endif
-    npeak = 0;
-
-         /* search for peaks */
-    for (i = MINBIN, fp = spect1+4*MINBIN, pk1 = peaklist;
-        i < n-2 && npeak < npeaktot; i++, fp += 4)
-    {
-        float height = fp[2], h1 = fp[-2], h2 = fp[6];
-        float totalfreq, pfreq, f1, f2, m, var, stdev;
-        
-        if (height < h1 || height < h2 ||
-            h1 < 0.00001f*total_power || h2 < 0.00001f*total_power)
-                continue;
-
-            /* use an informal phase vocoder to estimate the frequency.
-            Do this for the two adjacent bins too. */
-        pfreq= ((fp[-8] - fp[8]) * (2.0f * fp[0] - fp[8] - fp[-8]) +
-                (fp[-7] - fp[9]) * (2.0f * fp[1] - fp[9] - fp[-7])) /
-                    (2.0f * height);
-        f1=    ((fp[-12] - fp[4]) * (2.0f * fp[-4] - fp[4] - fp[-12]) +
-                (fp[-11] - fp[5]) * (2.0f * fp[-3] - fp[5] - fp[-11])) /
-                    (2.0f * h1) - 1;
-        f2=    ((fp[-4] - fp[12]) * (2.0f * fp[4] - fp[12] - fp[-4]) +
-                (fp[-3] - fp[13]) * (2.0f * fp[5] - fp[13] - fp[-3])) /
-                    (2.0f * h2) + 1;
-
-            /* get sample mean and variance of the three */
-        m = 0.333333f * (pfreq + f1 + f2);
-        var = 0.5f * ((pfreq-m)*(pfreq-m) + (f1-m)*(f1-m) + (f2-m)*(f2-m));
-
-        totalfreq = i + m;
-        if (var * total_power > KNOCKTHRESH * height || var < 1e-30)
-        {
-#if 0
-            if (x->x_nprint)
-                post("cancel: %.2f hz, index %.1f, power %.5f, stdev=%.2f",
-                    totalfreq * hzperbin, BPERO_OVER_LOG2 * log(totalfreq) - 96,
-                     height, sqrt(var));
-#endif
-            continue;
-        }
-        stdev = fsqrt(var);
-        if (totalfreq < 4)
-        {
-            if (x->x_nprint) post("oops: was %d,  freq %f, m %f, stdev %f h %f",
-                i,  totalfreq, m, stdev, height);
-            totalfreq = 4;
-        }
-        pk1->p_width = stdev;
-
-        pk1->p_pow = height;
-        pk1->p_loudness = fsqrt(fsqrt(height));
-        pk1->p_fp = fp;
-        pk1->p_freq = totalfreq;
-        npeak++;
-#if 1
-        if (x->x_nprint)
-        {
-            post("peak: %.2f hz. index %.1f, power %.5f, stdev=%.2f",
-                pk1->p_freq * hzperbin,
-                BPERO_OVER_LOG2 * log(pk1->p_freq) - 96,
-                 height, stdev);
-        }
-#endif
-        pk1++;
-    }
-
-            /* prepare the raw peaks for output */
-    for (i = 0, pk1 = peaklist, pk2 = x->x_peakbuf; i < npeak;
-        i++, pk1++, pk2++)
-    {
-        float loudness = pk1->p_loudness;
-        if (i >= npeakout) break;
-        pk2->po_freq = hzperbin * pk1->p_freq;
-        pk2->po_amp = (2.f / (float)n) * (loudness * loudness);
-    }
-    for (; i < npeakout; i++, pk2++) pk2->po_amp = pk2->po_freq = 0;
-
-        /* now, working back into spect2, make a sort of "liklihood"
-         * spectrum.  Proceeding in 48ths of an octave,  from 2 to
-         * n/2 (in bins), the likelihood of each pitch range is contributed
-         * to by every peak in peaklist that's an integer multiple of it
-         * in frequency.
-         */
-
-    if (npeak > npeakanal) npeak = npeakanal; /* max # peaks to analyze */
-    for (i = 0, fp1 = histogram; i < maxbin; i++) *fp1++ = 0;
-    for (i = 0, pk1 = peaklist; i < npeak; i++, pk1++)
-    {
-        float pit = BPERO_OVER_LOG2 * flog(pk1->p_freq) - 96.0f;
-        float binbandwidth = FACTORTOBINS * pk1->p_width/pk1->p_freq;
-        float putbandwidth = (binbandwidth < 2 ? 2 : binbandwidth);
-        float weightbandwidth = (binbandwidth < 1.0f ? 1.0f : binbandwidth);
-        /* float weightamp = 1.0f + 3.0f * pk1->p_pow / pow; */
-        float weightamp = 4. * pk1->p_loudness / total_loudness;
-        for (j = 0, fp2 = sigfiddle_partialonset; j < NPARTIALONSET; j++, fp2++)
-        {
-            float bin = pit - *fp2;
-            if (bin < maxbin)
-            {
-                float para, pphase, score = 30.0f * weightamp /
-                    ((j+x->x_npartial) * weightbandwidth);
-                int firstbin = bin + 0.5f - 0.5f * putbandwidth;
-                int lastbin = bin + 0.5f + 0.5f * putbandwidth;
-                int ibw = lastbin - firstbin;
-                if (firstbin < -BINGUARD) break;
-                para = 1.0f / (putbandwidth * putbandwidth);
-                for (k = 0, fp3 = histogram + firstbin,
-                    pphase = firstbin-bin; k <= ibw;
-                        k++, fp3++,  pphase += 1.0f)
-                {
-                    *fp3 += score * (1.0f - para * pphase * pphase);
-                }
-            }
-        }
-    }
-#if 1
-    if (x->x_nprint)
-    {
-        for (i = 0; i < 6*5; i++)
-        {
-            float fhz = hzperbin * exp ((8*i + 96) * (1./BPERO_OVER_LOG2));
-            if (!(i % 6)) post("-- bin %d pitch %f freq %f----", 8*i,
-                ftom(fhz), fhz);;
-            post("%3d %3d %3d %3d %3d %3d %3d %3d",
-                (int)(histogram[8*i]),
-                (int)(histogram[8*i+1]),
-                (int)(histogram[8*i+2]),
-                (int)(histogram[8*i+3]),
-                (int)(histogram[8*i+4]),
-                (int)(histogram[8*i+5]),
-                (int)(histogram[8*i+6]),
-                (int)(histogram[8*i+7]));
-        }
-    }
-
-#endif
-
-        /*
-         * Next we find up to NPITCH strongest peaks in the histogram.
-         * if a peak is related to a stronger one via an interval in
-         * the sigfiddle_partialonset array,  we suppress it.
-         */
-
-    for (npitch = 0; npitch < x->x_npitch; npitch++)
-    {
-        int indx;
-        float best;
-        if (npitch)
-        {
-            for (best = 0, indx = -1, j=1; j < maxbin-1; j++)
-            {
-                if (histogram[j] > best && histogram[j] > histogram[j-1] &&
-                    histogram[j] > histogram[j+1])
-                {
-                    for (k = 0; k < npitch; k++)
-                        if (histvec[k].h_index == j)
-                            goto peaknogood;
-                    for (k = 0; k < NPARTIALONSET; k++)
-                    {
-                        if (j - sigfiddle_intpartialonset[k] < 0) break;
-                        if (histogram[j - sigfiddle_intpartialonset[k]]
-                            > histogram[j]) goto peaknogood;
-                    }
-                    for (k = 0; k < NPARTIALONSET; k++)
-                    {
-                        if (j + sigfiddle_intpartialonset[k] >= maxbin) break;
-                        if (histogram[j + sigfiddle_intpartialonset[k]]
-                            > histogram[j]) goto peaknogood;
-                    }
-                    indx = j;
-                    best = histogram[j];
-                }
-            peaknogood: ;
-            }
-        }
-        else
-        {
-            for (best = 0, indx = -1, j=0; j < maxbin; j++)
-                if (histogram[j] > best)
-                    indx = j,  best = histogram[j];
-        }
-        if (indx < 0) break;
-        histvec[npitch].h_value = best;
-        histvec[npitch].h_index = indx;
-    }
-#if 1
-    if (x->x_nprint)
-    {
-        for (i = 0; i < npitch; i++)
-        {
-            post("index %d freq %f --> value %f", histvec[i].h_index,
-                exp((1./BPERO_OVER_LOG2) * (histvec[i].h_index + 96)),
-                histvec[i].h_value);
-            post("next %f , prev %f",
-                exp((1./BPERO_OVER_LOG2) * (histvec[i].h_index + 97)),
-                exp((1./BPERO_OVER_LOG2) * (histvec[i].h_index + 95)) );
-        }
-    }
-#endif
-
-        /* for each histogram peak, we now search back through the
-         * FFT peaks.  A peak is a pitch if either there are several
-         * harmonics that match it,  or else if (a) the fundamental is
-         * present,  and (b) the sum of the powers of the contributing peaks
-         * is at least 1/100 of the total power.
-         *
-         * A peak is a contributor if its frequency is within 25 cents of
-         * a partial from 1 to 16.
-         *
-         * Finally, we have to be at least 5 bins in frequency, which
-         * corresponds to 2-1/5 periods fitting in the analysis window.
-         */
-
-    for (i = 0; i < npitch; i++)
-    {
-        float cumpow = 0, cumstrength = 0, freqnum = 0, freqden = 0;
-        int npartials = 0,  nbelow8 = 0;
-            /* guessed-at frequency in bins */
-        float putfreq = fexp((1.0f / BPERO_OVER_LOG2) *
-            (histvec[i].h_index + 96.0f));
-        for (j = 0; j < npeak; j++)
-        {
-            float fpnum = peaklist[j].p_freq/putfreq;
-            int pnum = fpnum + 0.5f;
-            float fipnum = pnum;
-            float deviation;
-            if (pnum > 16 || pnum < 1) continue;
-            deviation = 1.0f - fpnum/fipnum;
-            if (deviation > -PARTIALDEVIANCE && deviation < PARTIALDEVIANCE)
-            {
-                /*
-                 * we figure this is a partial since it's within 1/4 of
-                 * a halftone of a multiple of the putative frequency.
-                 */
-
-                float stdev, weight;
-                npartials++;
-                if (pnum < 8) nbelow8++;
-                cumpow += peaklist[j].p_pow;
-                cumstrength += fsqrt(fsqrt(peaklist[j].p_pow));
-                stdev = (peaklist[j].p_width > MINBW ?
-                    peaklist[j].p_width : MINBW);
-                weight = 1.0f / ((stdev*fipnum) * (stdev*fipnum));
-                freqden += weight;
-                freqnum += weight * peaklist[j].p_freq/fipnum;          
-#if 1
-                if (x->x_nprint)
-                {
-                    post("peak %d partial %d f=%f w=%f",
-                        j, pnum, peaklist[j].p_freq/fipnum, weight);
-                }
-#endif
-            }
-#if 1
-            else if (x->x_nprint) post("peak %d partial %d dev %f",
-                        j, pnum, deviation);
-#endif
-        }
-        if ((nbelow8 < 4 || npartials < 7) && cumpow < 0.01f * total_power)
-            histvec[i].h_value = 0;
-        else
-        {
-            float pitchpow = (cumstrength * cumstrength) *
-                (cumstrength * cumstrength);
-            float freqinbins = freqnum/freqden;
-                /* check for minimum output frequency */
-
-            if (freqinbins < MINFREQINBINS)
-                histvec[i].h_value = 0;
-            else
-            {
-                    /* we passed all tests... save the values we got */
-                histvec[i].h_pitch = ftom(hzperbin * freqnum/freqden);
-                histvec[i].h_loud = (100.0f -DBFUDGE) +
-                    (LOGTODB) * log(pitchpow/n);
-            }
-        }
-    }
-#if 1
-    if (x->x_nprint)
-    {
-        for (i = 0; i < npitch; i++)
-        {
-            if (histvec[i].h_value > 0)
-                post("index %d pit %f loud %f", histvec[i].h_index,
-                histvec[i].h_pitch, histvec[i].h_loud);
-            else post("-- cancelled --");
-        }
-    }
-#endif
-
-        /* now try to find continuous pitch tracks that match the new
-         * pitches.  First mark each peak unmatched.
-         */
-    for (i = 0, hp1 = histvec; i < npitch; i++, hp1++)
-        hp1->h_used = 0;
-
-        /* for each old pitch, try to match a new one to it. */
-    for (i = 0, phist = x->x_hist; i < x->x_npitch; i++,  phist++)
-    {
-        float thispitch = phist->h_pitches[oldphase];
-        phist->h_pitch = 0;         /* no output, thanks */
-        phist->h_wherefrom = 0;
-        if (thispitch == 0.0f) continue;
-        for (j = 0, hp1 = histvec; j < npitch; j++, hp1++)
-            if ((hp1->h_value > 0) && hp1->h_pitch > thispitch - GLISS
-                && hp1->h_pitch < thispitch + GLISS)
-        {
-            phist->h_wherefrom = hp1;
-            hp1->h_used = 1;
-        }
-    }
-    for (i = 0, hp1 = histvec; i < npitch; i++, hp1++)
-        if ((hp1->h_value > 0) && !hp1->h_used)
-    {
-        for (j = 0, phist = x->x_hist; j < x->x_npitch; j++,  phist++)
-            if (!phist->h_wherefrom)
-        {
-            phist->h_wherefrom = hp1;
-            phist->h_age = 0;
-            phist->h_noted = 0;
-            hp1->h_used = 1;
-            goto happy;
-        }
-        break;
-    happy: ;
-    }
-        /* copy the pitch info into the history vector */
-    for (i = 0, phist = x->x_hist; i < x->x_npitch; i++,  phist++)
-    {
-        if (phist->h_wherefrom)
-        {
-            phist->h_amps[newphase] = phist->h_wherefrom->h_loud;
-            phist->h_pitches[newphase] =
-                phist->h_wherefrom->h_pitch;
-            (phist->h_age)++;
-        }
-        else
-        {
-            phist->h_age = 0;
-            phist->h_amps[newphase] = phist->h_pitches[newphase] = 0;
-        }
-    }
-#if 1
-    if (x->x_nprint)
-    {
-        post("vibrato %d %f", x->x_vibbins, x->x_vibdepth);
-        for (i = 0, phist = x->x_hist; i < x->x_npitch; i++,  phist++)
-        {
-            post("noted %f, age %d", phist->h_noted,  phist->h_age);
-#ifndef I860
-            post("values %f %f %f %f %f",
-                phist->h_pitches[newphase],
-                phist->h_pitches[(newphase + HISTORY-1)%HISTORY],
-                phist->h_pitches[(newphase + HISTORY-2)%HISTORY],
-                phist->h_pitches[(newphase + HISTORY-3)%HISTORY],
-                phist->h_pitches[(newphase + HISTORY-4)%HISTORY]);
-#endif
-        }
-    }
-#endif
-        /* look for envelope attacks */
-
-    x->x_attackvalue = 0;
-
-    if (x->x_peaked)
-    {
-        if (total_db > x->x_amphi)
-        {
-            int binlook = newphase - x->x_attackbins;
-            if (binlook < 0) binlook += HISTORY;
-            if (total_db > x->x_dbs[binlook] + x->x_attackthresh)
-            {
-                x->x_attackvalue = 1;
-                x->x_peaked = 0;
-            }
-        }
-    }
-    else
-    {
-        int binlook = newphase - x->x_attackbins;
-        if (binlook < 0) binlook += HISTORY;
-        if (x->x_dbs[binlook] > x->x_amphi && x->x_dbs[binlook] > total_db)
-            x->x_peaked = 1;
-    }
-
-        /* for each current frequency track, test for a new note using a
-         * stability criterion.  Later perhaps we should also do as in
-         * pitch~ and check for unstable notes a posteriori when
-         * there's a new attack with no note found since the last onset;
-         * but what's an attack &/or onset when we're polyphonic?
-         */
-
-    for (i = 0, phist = x->x_hist; i < x->x_npitch; i++,  phist++)
-    {
-            /*
-             * if we've found a pitch but we've now strayed from it turn
-             * it off.
-             */
-        if (phist->h_noted)
-        {
-            if (phist->h_pitches[newphase] > phist->h_noted + x->x_vibdepth
-                || phist->h_pitches[newphase] < phist->h_noted - x->x_vibdepth)
-                    phist->h_noted = 0;
-        }
-        else
-        {
-            if (phist->h_wherefrom && phist->h_age >= x->x_vibbins)
-            {
-                float centroid = 0;
-                int not = 0;
-                for (j = 0, k = newphase; j < x->x_vibbins; j++)
-                {
-                    centroid += phist->h_pitches[k];
-                    k--;
-                    if (k < 0) k = HISTORY-1;
-                }
-                centroid /= x->x_vibbins;
-                for (j = 0, k = newphase; j < x->x_vibbins; j++)
-                {
-                        /* calculate deviation from norm */
-                    float dev = centroid - phist->h_pitches[k];
-                    k--;
-                    if (k < 0) k = HISTORY-1;
-                    if (dev > x->x_vibdepth ||
-                        -dev > x->x_vibdepth) not = 1;
-                }
-                if (!not)
-                {
-                    phist->h_pitch = phist->h_noted = centroid;
-                }
-            }
-        }
-    }
-    return;
-
-nopow:
-    for (i = 0; i < x->x_npitch; i++)
-    {
-        x->x_hist[i].h_pitch = x->x_hist[i].h_noted =
-            x->x_hist[i].h_pitches[newphase] =
-            x->x_hist[i].h_amps[newphase] = 0;
-        x->x_hist[i].h_age = 0;
-    }
-    x->x_peaked = 1;
-    x->x_dbage = 0;
-}
-
-void sigfiddle_debug(t_sigfiddle *x)
-{
-    x->x_nprint = 1;
-}
-
-void sigfiddle_print(t_sigfiddle *x)
-{
-    post("npoints %d,",  2 * x->x_hop);
-    post("amp-range %f %f,",  x->x_amplo, x->x_amphi);
-    post("reattack %d %f,",  x->x_attacktime, x->x_attackthresh);
-    post("vibrato %d %f",  x->x_vibtime, x->x_vibdepth);
-    post("npartial %f",  x->x_npartial);
-    post("auto %d",  x->x_auto);
-}
-
-void sigfiddle_amprange(t_sigfiddle *x, t_floatarg amplo, t_floatarg amphi)
-{
-    if (amplo < 0) amplo = 0;
-    if (amphi < amplo) amphi = amplo + 1;
-    x->x_amplo = amplo;
-    x->x_amphi = amphi;
-}
-
-void sigfiddle_reattack(t_sigfiddle *x,
-    t_floatarg attacktime, t_floatarg attackthresh)
-{
-    if (attacktime < 0) attacktime = 0;
-    if (attackthresh <= 0) attackthresh = 1000;
-    x->x_attacktime = attacktime;
-    x->x_attackthresh = attackthresh;
-    x->x_attackbins = (x->x_sr * 0.001 * attacktime) / x->x_hop;
-    if (x->x_attackbins >= HISTORY) x->x_attackbins = HISTORY - 1;
-}
-
-void sigfiddle_vibrato(t_sigfiddle *x, t_floatarg vibtime, t_floatarg vibdepth)
-{
-    if (vibtime < 0) vibtime = 0;
-    if (vibdepth <= 0) vibdepth = 1000;
-    x->x_vibtime = vibtime;
-    x->x_vibdepth = vibdepth;
-    x->x_vibbins = (x->x_sr * 0.001  * vibtime) / x->x_hop;
-    if (x->x_vibbins >= HISTORY) x->x_vibbins = HISTORY - 1;
-    if (x->x_vibbins < 1) x->x_vibbins = 1;
-}
-
-void sigfiddle_npartial(t_sigfiddle *x, t_floatarg npartial)
-{
-    if (npartial < 0.1) npartial = 0.1;
-    x->x_npartial = npartial;
-}
-
-void sigfiddle_auto(t_sigfiddle *x, t_floatarg f)
-{
-    x->x_auto = (f != 0);
-}
-
-static void sigfiddle_freebird(t_sigfiddle *x)
-{
-    if (x->x_inbuf)
-    {
-        freebytes(x->x_inbuf, sizeof(float) * x->x_hop);
-        x->x_inbuf = 0;
-    }
-    if (x->x_lastanalysis)
-    {
-        freebytes(x->x_lastanalysis,
-            sizeof(float) * (2 * x->x_hop + 4 * FILTSIZE));
-        x->x_lastanalysis = 0;
-    }
-    if (x->x_spiral)
-    {
-        freebytes(x->x_spiral, sizeof(float) * 2 * x->x_hop);
-        x->x_spiral = 0;
-    }
-    x->x_hop = 0;
-}
-
-int sigfiddle_setnpoints(t_sigfiddle *x, t_floatarg fnpoints)
-{
-    int i, npoints = fnpoints;
-    sigfiddle_freebird(x);
-    if (npoints < MINPOINTS || npoints > MAXPOINTS)
-    {
-        error("fiddle~: npoints out of range; using %d",
-            npoints = DEFAULTPOINTS);
-    }
-    if (npoints != (1 << sigfiddle_ilog2(npoints)))
-    {
-        error("fiddle~: npoints not a power of 2; using %d", 
-            npoints = (1 << sigfiddle_ilog2(npoints)));
-    }
-    x->x_hop = npoints >> 1;
-    if (!(x->x_inbuf = (float *)getbytes(sizeof(float) * x->x_hop)))
-        goto fail;
-    if (!(x->x_lastanalysis = (float *)getbytes(
-        sizeof(float) * (2 * x->x_hop + 4 * FILTSIZE))))
-            goto fail;
-    if (!(x->x_spiral = (float *)getbytes(sizeof(float) * 2 * x->x_hop)))
-        goto fail;
-    for (i = 0; i < x->x_hop; i++)
-        x->x_inbuf[i] = 0;
-    for (i = 0; i < npoints + 4 * FILTSIZE; i++)
-        x->x_lastanalysis[i] = 0;
-    for (i = 0; i < x->x_hop; i++)
-        x->x_spiral[2*i] =    cos((3.14159*i)/(npoints)),
-        x->x_spiral[2*i+1] = -sin((3.14159*i)/(npoints));
-    x->x_phase = 0;
-    return (1);
-fail:
-    sigfiddle_freebird(x);
-    return (0);
-}
-
-int sigfiddle_doinit(t_sigfiddle *x, long npoints, long npitch,
-    long npeakanal, long npeakout)
-{
-    float *buf1, *buf2,  *buf3;
-    t_peakout *buf4;
-    int i;
-
-    if (!npeakanal && !npeakout) npeakanal = DEFNPEAK, npeakout = 0;
-    if (!npeakanal < 0) npeakanal = 0;
-    else if (npeakanal > MAXPEAK) npeakanal = MAXPEAK;
-    if (!npeakout < 0) npeakout = 0;
-    else if (npeakout > MAXPEAK) npeakout = MAXPEAK;
-    if (npitch <= 0) npitch = 0;
-    else if (npitch > MAXNPITCH) npitch = MAXNPITCH;
-    if (npeakanal && !npitch) npitch = 1;
-    if (!npoints)
-        npoints = DEFAULTPOINTS;
-    if (!sigfiddle_setnpoints(x, npoints))
-    {
-        error("fiddle~: out of memory");
-        return (0);
-    }
-    if (!(buf4 = (t_peakout *)getbytes(sizeof(*buf4) * npeakout)))
-    {
-        sigfiddle_freebird(x);
-        error("fiddle~: out of memory");
-        return (0);
-    }
-    for (i = 0; i < npeakout; i++)
-        buf4[i].po_freq = buf4[i].po_amp = 0;
-    x->x_peakbuf = buf4;
-
-    x->x_npeakout = npeakout;
-    x->x_npeakanal = npeakanal;
-    x->x_phase = 0;
-    x->x_histphase = 0;
-    x->x_sr = 44100;            /* this and the next are filled in later */
-    for (i = 0; i < MAXNPITCH; i++)
-    {
-        int j;
-        x->x_hist[i].h_pitch = x->x_hist[i].h_noted = 0;
-        x->x_hist[i].h_age = 0;
-        x->x_hist[i].h_wherefrom = 0;
-        x->x_hist[i].h_outlet = 0;
-        for (j = 0; j < HISTORY; j++)
-            x->x_hist[i].h_amps[j] = x->x_hist[i].h_pitches[j] = 0;
-    }
-    x->x_nprint = 0;
-    x->x_npitch = npitch;
-    for (i = 0; i < HISTORY; i++) x->x_dbs[i] = 0;
-    x->x_dbage = 0;
-    x->x_peaked = 0;
-    x->x_auto = 1;
-    x->x_amplo = DEFAMPLO;
-    x->x_amphi = DEFAMPHI;
-    x->x_attacktime = DEFATTACKTIME;
-    x->x_attackbins = 1;                /* real value calculated afterward */
-    x->x_attackthresh = DEFATTACKTHRESH;
-    x->x_vibtime = DEFVIBTIME;
-    x->x_vibbins = 1;                   /* real value calculated afterward */
-    x->x_vibdepth = DEFVIBDEPTH;
-    x->x_npartial = 7;
-    x->x_attackvalue = 0;
-    return (1);
-}
-
-    /* formalities for JMAX */
-
-#ifdef JMAX
-
-void sigfiddle_debug13(fts_object_t *o, int winlet, fts_symbol_t s, int ac, const fts_atom_t *at)
-{
-  t_sigfiddle *x = (t_sigfiddle *)o;
-  sigfiddle_debug(x);
-}
-
-void sigfiddle_print13(fts_object_t *o, int winlet, fts_symbol_t s,
-    int ac, const fts_atom_t *at)
-{
-  t_sigfiddle *x = (t_sigfiddle *)o;
-  sigfiddle_print(x);
-}
-
-void sigfiddle_amprange13(fts_object_t *o, int winlet, fts_symbol_t s,
-    int ac, const fts_atom_t *at)
-{
-    t_sigfiddle *x = (t_sigfiddle *)o;
-    float lo =  (float) fts_get_float_arg(ac, at, 0, 0);
-    float hi =  (float) fts_get_float_arg(ac, at, 1, 0);
-    sigfiddle_amprange(x, lo, hi);
-}
-
-void sigfiddle_reattack13(fts_object_t *o, int winlet, fts_symbol_t s,
-    int ac, const fts_atom_t *at)
-{
-    t_sigfiddle *x = (t_sigfiddle *)o;
-    long msec =  fts_get_float_arg(ac, at, 0, 0);
-    float db =  (float) fts_get_float_arg(ac, at, 1, 0);
-    sigfiddle_reattack(x, msec, db);
-}
-
-void sigfiddle_vibrato13(fts_object_t *o, int winlet, fts_symbol_t s,
-    int ac, const fts_atom_t *at)
-{
-    t_sigfiddle *x = (t_sigfiddle *)o;
-    long msec =  fts_get_float_arg(ac, at, 0, 0);
-    float halftones =  (float) fts_get_float_arg(ac, at, 1, 0);
-    sigfiddle_vibrato(x, msec, halftones);
-}
-
-void sigfiddle_npartial13(fts_object_t *o, int winlet, fts_symbol_t s,
-    int ac, const fts_atom_t *at)
-{
-    t_sigfiddle *x = (t_sigfiddle *)o;
-    float npartial =  (float) fts_get_float_arg(ac, at, 0, 0);
-    sigfiddle_npartial(x, npartial);
-}
-
-
-void ftl_sigfiddle(fts_word_t *a)
-{
-    t_sigfiddle *x = (t_sigfiddle *)fts_word_get_long(a);
-    float *in = (float *)fts_word_get_long(a + 1);
-    long n_tick = fts_word_get_long(a + 2);
-
-    int count;
-    float *fp,  *fp2;
-    for (count = 0, fp = x->x_inbuf + x->x_phase;
-            count < n_tick; count++) *fp++ = *in++;
-    if (fp == x->x_inbuf + x->x_hop)
-    {
-        sigfiddle_doit(x);
-        x->x_phase = 0;
-        fts_alarm_set_delay(&x->x_clock, 0L);        /* output bang */
-        fts_alarm_arm(&x->x_clock);
-
-        if (x->x_nprint) x->x_nprint--;
-    }
-    else x->x_phase += n_tick;
-}
-
-void sigfiddle_put(fts_object_t *o, int winlet, fts_symbol_t *s, int ac, const fts_atom_t *at)
-{
-    t_sigfiddle *x = (t_sigfiddle *)o;
-    fts_dsp_descr_t *dsp = (fts_dsp_descr_t *)fts_get_long_arg(ac, at, 0, 0);
-    fts_atom_t a[3];
-
-    x->x_sr = fts_dsp_get_input_srate(dsp, 0);
-    sigfiddle_reattack(x, x->x_attacktime, x->x_attackthresh);
-    sigfiddle_vibrato(x, x->x_vibtime, x->x_vibdepth);
-
-    fts_set_long(a, (long)x);
-    fts_set_symbol(a+1, fts_dsp_get_input_name(dsp, 0));
-    fts_set_long(a+2, fts_dsp_get_input_size(dsp, 0));
-    dsp_add_funcall(dsp_symbol, 3, a);
-}
-
-void sigfiddle_tick(fts_alarm_t *alarm, void *p)
-{
-    fts_object_t *o = (fts_object_t *)p;
-    t_sigfiddle *x = (t_sigfiddle *)p;
-
-    int i;
-    t_pitchhist *ph;
-    fts_outlet_float(o, OUTLETpower, x->x_dbs[x->x_histphase]);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-    {
-        fts_atom_t at[2];
-        fts_set_float(at, ph->h_pitches[x->x_histphase]);
-        fts_set_float(at+1, ph->h_amps[x->x_histphase]);
-        fts_outlet_list(o, OUTLETmicropitch3 - i, 2, at);
-    }
-    if (x->x_attackvalue) fts_outlet_bang(o, OUTLETattack);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-        if (ph->h_pitch) fts_outlet_float(o, OUTLETpitch, ph->h_pitch);
-}
-
-static void sigfiddle_delete(fts_object_t *o, int winlet, fts_symbol_t *s, int ac,
- const fts_atom_t *at)
-{
-  t_sigfiddle *x = (t_sigfiddle *)o;
-
-  fts_free(x->x_inbuf);
-  fts_free(x->x_lastanalysis);
-  fts_free(x->x_spiral);
-  dsp_list_remove(o);
-}
-
-static void sigfiddle_init(fts_object_t *o, int winlet, fts_symbol_t *s, int ac, const fts_atom_t *at)
-{
-    t_sigfiddle *x = (t_sigfiddle *)o;
-    float *buf1, *buf2,  *buf3;
-    int i, hop;
-    long npoints    = fts_get_long_arg(ac, at, 1, 0);
-    long npitch    = fts_get_long_arg(ac, at, 2, 0);
-    long npeakanal    = fts_get_long_arg(ac, at, 3, 0);
-    long npeakout    = fts_get_long_arg(ac, at, 4, 0);
-
-    if (!sigfiddle_doinit(x, npoints, npitch, npeakanal, npeakout))
-    {
-        post("fiddle~: initialization failed");
-        return;
-    }
-    hop = npoints>>1;
-    if (fts_fft_declaresize(hop) != fts_Success)
-        post("fiddle~: bad FFT size");
-
-    fts_alarm_init(&(x->x_clock), 0, sigfiddle_tick, x);
-    dsp_list_insert(o);
-}
-
-static fts_status_t sigfiddle_instantiate(fts_class_t *cl, int ac,
-    const fts_atom_t *at)
-{
-  int i;
-  fts_type_t a[5];
-
-  fts_class_init(cl, sizeof(t_sigfiddle), 1, 6, 0);  /* 1 inlet + 6 outlets */
-
-  /* the system methods */
-
-  a[0] = fts_Symbol;
-  a[1] = fts_Long | fts_OptArg;
-  a[2] = fts_Long | fts_OptArg;
-  fts_method_define(cl, fts_SystemInlet, fts_s_init, sigfiddle_init, 3, a);
-
-  fts_method_define(cl, fts_SystemInlet, fts_s_delete, sigfiddle_delete, 0, a);
-  a[0] = fts_Object;
-  fts_method_define(cl, fts_SystemInlet, fts_s_put, sigfiddle_put, 1, a);
-
-  /* class' own methods */
-  fts_method_define(cl, 0, fts_new_symbol("print"), sigfiddle_print13, 0, a);
-  fts_method_define(cl, 0, fts_new_symbol("debug"), sigfiddle_debug13, 0, a);
-  fts_method_define(cl, 0, fts_new_symbol("amp-range"), sigfiddle_amprange13,
-        0, a);
-  fts_method_define(cl, 0, fts_new_symbol("reattack"), sigfiddle_reattack13,
-        0, a);
-  fts_method_define(cl, 0, fts_new_symbol("vibrato"), sigfiddle_vibrato13,
-        0, a);
-  fts_method_define(cl, 0, fts_new_symbol("npartial"), sigfiddle_npartial13,
-        0, a);
-
-  /* classes signal inlets */
-  dsp_sig_inlet(cl, 0);                    /* declare signal input #0 */
-
-  /* classes outlets */
-  a[0] = fts_Float;
-  fts_outlet_type_define(cl, OUTLETpitch, fts_s_float, 1, a); /* declare outlet #0 */
-  fts_outlet_type_define(cl, OUTLETattack, fts_s_bang, 0, a); /* declare outlet #1 */
-  a[0] = fts_VarArgs;
-  fts_outlet_type_define(cl, OUTLETmicropitch1, fts_s_list, 1, a); /* declare outlet #2 */
-  fts_outlet_type_define(cl, OUTLETmicropitch2, fts_s_list, 1, a); /* declare outlet #3 */
-  fts_outlet_type_define(cl, OUTLETmicropitch3, fts_s_list, 1, a); /* declare outlet #4 */
-  a[0] = fts_Float;
-  fts_outlet_type_define(cl, OUTLETpower, fts_s_float, 1, a); /* declare outlet #5 */
-
-  dsp_symbol = fts_new_symbol("fiddle");
-  dsp_declare_function(dsp_symbol, ftl_sigfiddle);
-
-  /* DSP properties  */
-
-  fts_class_put_prop(cl, fts_s_dsp_is_sink, fts_true);
-
-  return(fts_Success);
-}
-
-void fiddle_config(void)
-{
-  sys_log(fiddle_version);
-  fts_metaclass_create(fts_new_symbol(CLASSNAME), sigfiddle_instantiate, fts_always_equiv);
-}
-
-fts_module_t fiddle_module =
-  {"fiddle", "sonic meat fiddle", fiddle_config, 0};
-
-#endif  /* JMAX */
-
-#ifdef PD
-
-static t_int *fiddle_perform(t_int *w)
-{
-    t_float *in = (t_float *)(w[1]);
-    t_sigfiddle *x = (t_sigfiddle *)(w[2]);
-    int n = (int)(w[3]);
-    int count;
-    float *fp;
-    if (!x->x_hop)
-        goto nono;
-    for (count = 0, fp = x->x_inbuf + x->x_phase; count < n; count++)
-        *fp++ = *in++;
-    if (fp == x->x_inbuf + x->x_hop)
-    {
-        sigfiddle_doit(x);
-        x->x_phase = 0;
-        if (x->x_auto) clock_delay(x->x_clock, 0L);
-        if (x->x_nprint) x->x_nprint--;
-    }
-    else x->x_phase += n;
-nono:
-    return (w+4);
-}
-
-void sigfiddle_dsp(t_sigfiddle *x, t_signal **sp)
-{
-    x->x_sr = sp[0]->s_sr;
-    sigfiddle_reattack(x, x->x_attacktime, x->x_attackthresh);
-    sigfiddle_vibrato(x, x->x_vibtime, x->x_vibdepth);
-    dsp_add(fiddle_perform, 3, sp[0]->s_vec, x, sp[0]->s_n);
-}
-
-    /* This is the callback function for the clock, but also acts as
-    the "bang" method; you can leave "auto" on to get this called
-    automatically (the default) or turn auto off and bang it yourself. */
-
-void sigfiddle_bang(t_sigfiddle *x)
-{
-    int i;
-    t_pitchhist *ph;
-    if (x->x_npeakout)
-    {
-        int npeakout = x->x_npeakout;
-        t_peakout *po;
-        for (i = 0, po = x->x_peakbuf; i < npeakout; i++, po++)
-        {
-            t_atom at[3];
-            SETFLOAT(at, i+1);
-            SETFLOAT(at+1, po->po_freq);
-            SETFLOAT(at+2, po->po_amp);
-            outlet_list(x->x_peakout, 0, 3, at);
-        }
-    }
-    outlet_float(x->x_envout, x->x_dbs[x->x_histphase]);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-    {
-        t_atom at[2];
-        SETFLOAT(at, ph->h_pitches[x->x_histphase]);
-        SETFLOAT(at+1, ph->h_amps[x->x_histphase]);
-        outlet_list(ph->h_outlet, 0, 2, at);
-    }
-    if (x->x_attackvalue) outlet_bang(x->x_attackout);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-        if (ph->h_pitch) outlet_float(x->x_noteout, ph->h_pitch);
-}
-
-void sigfiddle_ff(t_sigfiddle *x)               /* cleanup on free */
-{
-    if (x->x_inbuf)
-    {
-        freebytes(x->x_inbuf, sizeof(float) * x->x_hop);
-        freebytes(x->x_lastanalysis, sizeof(float) * (2*x->x_hop + 4 * FILTSIZE));
-        freebytes(x->x_spiral, sizeof(float) * 2*x->x_hop);
-        freebytes(x->x_peakbuf, sizeof(*x->x_peakbuf) * x->x_npeakout);
-        clock_free(x->x_clock);
-    }
-}
-
-static t_class *sigfiddle_class;
-
-void *sigfiddle_new(t_floatarg npoints, t_floatarg npitch,
-    t_floatarg fnpeakanal, t_floatarg fnpeakout)
-{
-    t_sigfiddle *x = (t_sigfiddle *)pd_new(sigfiddle_class);
-    int i;
-    int npeakanal = fnpeakanal, npeakout = fnpeakout;
-
-
-    if (!sigfiddle_doinit(x, npoints, npitch,
-        npeakanal, npeakout))
-    {
-        x->x_inbuf = 0;     /* prevent the free routine from cleaning up */
-        pd_free(&x->x_ob.ob_pd);
-        return (0);
-    }
-    x->x_noteout = outlet_new(&x->x_ob, gensym("float"));
-    x->x_attackout = outlet_new(&x->x_ob, gensym("bang"));
-    for (i = 0; i < x->x_npitch; i++)
-        x->x_hist[i].h_outlet = outlet_new(&x->x_ob, gensym("list"));
-    x->x_envout = outlet_new(&x->x_ob, gensym("float"));
-    if (x->x_npeakout)
-        x->x_peakout = outlet_new(&x->x_ob, gensym("list"));
-    else x->x_peakout = 0;
-    x->x_clock = clock_new(&x->x_ob.ob_pd, (t_method)sigfiddle_bang);
-    return (x);
-}
-
-void fiddle_tilde_setup(void)
-{
-    sigfiddle_class = class_new(gensym("fiddle~"), (t_newmethod)sigfiddle_new,
-        (t_method)sigfiddle_ff, sizeof(t_sigfiddle), 0,
-            A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_dsp,
-        gensym("dsp"), 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_debug,
-        gensym("debug"), 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_setnpoints,
-        gensym("npoints"), A_FLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_amprange,
-        gensym("amp-range"), A_FLOAT, A_FLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_reattack,
-        gensym("reattack"), A_FLOAT, A_FLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_vibrato,
-        gensym("vibrato"), A_FLOAT, A_FLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_npartial,
-        gensym("npartial"), A_FLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_auto,
-        gensym("auto"), A_FLOAT, 0);
-    class_addmethod(sigfiddle_class, (t_method)sigfiddle_print,
-        gensym("print"), 0);
-    class_addmethod(sigfiddle_class, nullfn, gensym("signal"), 0);
-    class_addbang(sigfiddle_class, sigfiddle_bang);
-    class_addcreator((t_newmethod)sigfiddle_new, gensym("fiddle"),
-        A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);
-    post(fiddle_version);
-}
-
-void fiddle_setup(void)
-{
-    fiddle_tilde_setup();
-}
-#endif /* PD */
-
-#ifdef MAX26
-
-void cu_fiddle(float *in1, t_sigfiddle *x, int n)
-{
-    int count;
-    float *fp,  *fp2;
-    for (count = 0, fp = x->x_inbuf + x->x_phase;
-            count < n; count++) *fp++ = *in1++;
-    if (fp == x->x_inbuf + x->x_hop)
-    {
-        sigfiddle_doit(x);
-        x->x_phase = 0;
-        if (x->x_auto) clock_delay(x->x_clock, 0L);
-        if (x->x_nprint) x->x_nprint--;
-    }
-    else x->x_phase += n;
-}
-
-void sigfiddle_put(t_sigfiddle *x, long whether)
-{
-    if (whether)
-    {
-        u_stdout(x);
-        x->x_sr = x->x_io[0]->s_sr;
-        sigfiddle_reattack(x, x->x_attacktime, x->x_attackthresh);
-        sigfiddle_vibrato(x, x->x_vibtime, x->x_vibdepth);
-        dspchain_addc(cu_fiddle, 3,
-            x->x_io[0]->s_shit, x, x->x_io[0]->s_n);
-    }
-}
-
-void sigfiddle_tick(t_sigfiddle *x)     /* callback function for the clock */
-{
-    int i;
-    t_pitchhist *ph;
-    outlet_float(x->x_envout, x->x_dbs[x->x_histphase]);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-    {
-        t_atom at[2];
-        SETFLOAT(at, ph->h_pitches[x->x_histphase]);
-        SETFLOAT(at+1, ph->h_amps[x->x_histphase]);
-        outlet_list(ph->h_outlet, NIL, 2, at);
-    }
-    if (x->x_attackvalue) outlet_bang(x->x_attackout);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-        if (ph->h_pitch) outlet_float(x->x_noteout, ph->h_pitch);
-}
-
-void sigfiddle_ff(t_sigfiddle *x)               /* cleanup on free */
-{
-    if (x->x_inbuf)
-    {
-        freebytes(x->x_inbuf, sizeof(float) * x->x_hop);
-        freebytes(x->x_lastanalysis, sizeof(float) * (2*x->x_hop + 4 * FILTSIZE));
-        freebytes(x->x_spiral, sizeof(float) * 2*x->x_hop);
-        clock_free(x->x_clock);
-        u_clean(x);
-    }
-}
-
-t_externclass *sigfiddle_class;
-
-void *sigfiddle_new(long npoints, long npitch,
-    long npeakanal, long npeakout)
-{
-    t_sigfiddle *x = (t_sigfiddle *)obj_new(&sigfiddle_class, 0);
-    int i;
-
-    if (!sigfiddle_doinit(x, npoints, npitch, npeakanal, npeakout))
-    {
-        x->x_inbuf = 0;     /* prevent the free routine from cleaning up */
-        obj_free(x);
-        return (0);
-    }
-    u_setup(x, IN1, OUT0);
-    x->x_envout = outlet_new(x, gensym("float"));
-    for (i = 0; i < x->x_npitch; i++)
-        x->x_hist[i].h_outlet = outlet_new(x, gensym("list"));
-    x->x_attackout = outlet_new(x, gensym("bang"));
-    x->x_noteout = outlet_new(x, gensym("float"));
-    x->x_clock = clock_new(x, sigfiddle_tick);
-    return (x);
-}
-
-void fiddle_setup()
-{
-    c_extern(&sigfiddle_class, sigfiddle_new, sigfiddle_ff,
-        gensym("fiddle"), sizeof(t_sigfiddle), 0, A_DEFLONG, A_DEFLONG,
-            A_DEFLONG, A_DEFLONG, 0);
-    c_addmess(sigfiddle_put, gensym("put"), A_CANT, 0);
-    c_addmess(sigfiddle_debug, gensym("debug"), 0);
-    c_addmess(sigfiddle_amprange, gensym("amp-range"), A_FLOAT, A_FLOAT, 0);
-    c_addmess(sigfiddle_reattack, gensym("reattack"), A_FLOAT, A_FLOAT, 0);
-    c_addmess(sigfiddle_vibrato, gensym("vibrato"), A_LONG, A_FLOAT, 0);
-    c_addmess(sigfiddle_npartial, gensym("npartial"), A_FLOAT, 0);
-    c_addmess(sigfiddle_print, gensym("print"), 0);
-    u_inletmethod(0);   /* one signal input */
-#ifdef MAX
-    post(fiddle_version);
-#endif
-}
-
-#endif /* MAX26 */
-
-/************* Beginning of MSP Code ******************************/
-
-#ifdef MSP
-
-static t_int *fiddle_perform(t_int *w)
-{
-    t_float *in = (t_float *)(w[1]);
-    t_sigfiddle *x = (t_sigfiddle *)(w[2]);
-    int n = (int)(w[3]);
-    int count,inc = x->x_downsample;
-    float *fp;
-
-    if (x->x_obj.z_disabled)
-        goto skip;
-    for (count = 0, fp = x->x_inbuf + x->x_phase; count < n; count+=inc) {
-        *fp++ = *in;
-        in += inc;
-    }
-    if (fp == x->x_inbuf + x->x_hop)
-    {
-                sigfiddle_doit(x);
-                x->x_phase = 0;
-                if (x->x_auto) clock_delay(x->x_clock, 0L);
-                if (x->x_nprint) x->x_nprint--;
-    }
-    else x->x_phase += n;
-skip:
-    return (w+4);
-}
-
-void sigfiddle_dsp(t_sigfiddle *x, t_signal **sp)
-{
-     if (sp[0]->s_n > x->x_hop) {
-        x->x_downsample = sp[0]->s_n / x->x_hop;
-        post("* warning: fiddle~: will downsample input by %ld",x->x_downsample);
-        x->x_sr = sp[0]->s_sr / x->x_downsample;
-    } else {
-        x->x_downsample = 1;
-                x->x_sr = sp[0]->s_sr;
-        }
-        sigfiddle_reattack(x, x->x_attacktime, x->x_attackthresh);
-    sigfiddle_vibrato(x, x->x_vibtime, x->x_vibdepth);
-    dsp_add(fiddle_perform, 3, sp[0]->s_vec, x, sp[0]->s_n);
-}
-
-void sigfiddle_tick(t_sigfiddle *x)     /* callback function for the clock MSP*/
-{
-    int i;
-    t_pitchhist *ph;
-    if (x->x_npeakout)
-    {
-        int npeakout = x->x_npeakout;
-        t_peakout *po;
-        for (i = 0, po = x->x_peakbuf; i < npeakout; i++, po++)
-        {
-                t_atom at[3];
-                SETINT(at, i+1);
-                SETFLOAT(at+1, po->po_freq);
-                SETFLOAT(at+2, po->po_amp);
-                outlet_list(x->x_peakout, 0, 3, at);
-                }
-    }
-    outlet_float(x->x_envout, x->x_dbs[x->x_histphase]);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-    {
-        t_atom at[2];
-        SETFLOAT(at, ph->h_pitches[x->x_histphase]);
-        SETFLOAT(at+1, ph->h_amps[x->x_histphase]);
-        outlet_list(ph->h_outlet, 0, 2, at);
-    }
-    if (x->x_attackvalue) outlet_bang(x->x_attackout);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-        if (ph->h_pitch) outlet_float(x->x_noteout, ph->h_pitch);
-}
-
-void sigfiddle_bang(t_sigfiddle *x)             
-{
-    int i;
-    t_pitchhist *ph;
-    if (x->x_npeakout)
-    {
-        int npeakout = x->x_npeakout;
-        t_peakout *po;
-        for (i = 0, po = x->x_peakbuf; i < npeakout; i++, po++)
-        {
-            t_atom at[3];
-            SETLONG(at, i+1);
-            SETFLOAT(at+1, po->po_freq);
-            SETFLOAT(at+2, po->po_amp);
-            outlet_list(x->x_peakout, 0, 3, at);
-        }
-    }
-    outlet_float(x->x_envout, x->x_dbs[x->x_histphase]);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-    {
-        t_atom at[2];
-        SETFLOAT(at, ph->h_pitches[x->x_histphase]);
-        SETFLOAT(at+1, ph->h_amps[x->x_histphase]);
-        outlet_list(ph->h_outlet, 0, 2, at);
-    }
-    if (x->x_attackvalue) outlet_bang(x->x_attackout);
-    for (i = 0,  ph = x->x_hist; i < x->x_npitch; i++,  ph++)
-        if (ph->h_pitch) outlet_float(x->x_noteout, ph->h_pitch);
-}
-
-
-void sigfiddle_ff(t_sigfiddle *x)               /* cleanup on free  MSP  */
-{
-
-    if (x->x_inbuf)
-    {
-        t_freebytes(x->x_inbuf, sizeof(float) * x->x_hop);
-        t_freebytes(x->x_lastanalysis, sizeof(float) * (2*x->x_hop + 4 *
-FILTSIZE));
-        t_freebytes(x->x_spiral, sizeof(float) * 2*x->x_hop);
-        t_freebytes(x->x_peakbuf, sizeof(*x->x_peakbuf) * x->x_npeakout);
-    }
-     dsp_free((t_pxobject *)x);
-}
-
-void *sigfiddle_class;
-
-void *sigfiddle_new(long npoints, long npitch,
-    long npeakanal, long npeakout)
-{
-    t_sigfiddle *x = (t_sigfiddle *)newobject(sigfiddle_class);
-    int i;
-
-    if (!sigfiddle_doinit(x, npoints, npitch, npeakanal, npeakout))
-    {
-        x->x_inbuf = 0;     /* prevent the free routine from cleaning up */
-        return (0);
-    }
-    dsp_setup((t_pxobject *)x,1);
-
-    x->x_clock = clock_new(x, (method)sigfiddle_tick);
-     if (x->x_npeakout)
-        x->x_peakout = listout((t_object *)x);
-    else x->x_peakout = 0;
-    x->x_envout = floatout((t_object *)x);
-    for (i = 0; i < x->x_npitch; i++)
-                x->x_hist[i].h_outlet = listout((t_object *)x);
-        x->x_attackout = bangout((t_object *)x);
-        x->x_noteout = floatout((t_object *)x);
-          return (x);
-
-
-}
-
-void main()
-{
-        setup(&sigfiddle_class, sigfiddle_new, (method)sigfiddle_ff,
-                (short)sizeof(t_sigfiddle), 0L, A_DEFLONG, A_DEFLONG,
-A_DEFLONG, A_DEFLONG, 0);
-        addmess((method)sigfiddle_dsp,          "dsp",
-        A_CANT, 0);
-    addmess((method)sigfiddle_debug,    "debug",                0);
-    addmess((method)sigfiddle_setnpoints, "npoints",    A_FLOAT, 0);
-    addmess((method)sigfiddle_amprange, "amp-range",    A_FLOAT, A_FLOAT, 0);
-    addmess((method)sigfiddle_reattack, "reattack",     A_FLOAT, A_FLOAT, 0);
-    addmess((method)sigfiddle_vibrato,  "vibrato",              A_FLOAT,
-A_FLOAT, 0);
-    addmess((method)sigfiddle_npartial, "npartial",     A_FLOAT, 0);
-    addmess((method)sigfiddle_auto,             "auto",
-        A_FLOAT, 0);
-    addmess((method)sigfiddle_print,    "print",                0);
-        addmess((method)sigfiddle_assist,       "assist",
-        A_CANT, 0);
-        addbang((method)sigfiddle_bang);
-    dsp_initclass();
-    rescopy('STR#',3748);
-    post(fiddle_version);
-}
-
-void sigfiddle_assist(t_sigfiddle *x, void *b, long m, long a, char *s)
-{
-        assist_string(3748,m,a,1,2,s);
-}
-
-void msp_fft(float *buf, long np, long inv)
-{
-        float *src,*real,*rp,*imag,*ip;
-        long i;
-
-        /*
-        // because this fft algorithm uses separate real and imaginary
-        // buffers
-        // we must split the real and imaginary parts into two buffers,
-        // then do the opposite on output
-        // a more ambitious person would either do an in-place conversion
-        // or rewrite the fft algorithm
-        */
-    
-        real = rp = msp_ffttemp;
-        imag = ip = real + MAXPOINTS;
-        src = buf;
-        for (i = 0; i < np; i++) {
-                *rp++ = *src++;
-                *ip++ = *src++;
-        }
-        if (inv)
-                ifft(np,real,imag);
-        else
-                fft(np,real,imag);
-        rp = real;
-        ip = imag;
-        src = buf;
-        for (i = 0; i < np; i++) {
-                *src++ = *rp++;
-                *src++ = *ip++;
-        }
-}
-
-#endif /* MSP */
diff --git a/extra/fiddle~/makefile b/extra/fiddle~/makefile
deleted file mode 100644
index 247c905e6..000000000
--- a/extra/fiddle~/makefile
+++ /dev/null
@@ -1,4 +0,0 @@
-NAME=fiddle~
-CSYM=fiddle_tilde
-
-include ../makefile
diff --git a/extra/loop~/loop~-help.pd b/extra/loop~/loop~-help.pd
deleted file mode 100644
index a445b805e..000000000
--- a/extra/loop~/loop~-help.pd
+++ /dev/null
@@ -1,74 +0,0 @@
-#N canvas 33 0 647 662 12;
-#X floatatom 41 204 0 0 0 0 - - -;
-#X obj 254 382 print~;
-#X msg 254 347 bang;
-#X obj 41 338 loop~;
-#X floatatom 66 279 0 0 0 0 - - -;
-#X msg 55 252 bang;
-#X obj 183 382 print~;
-#X msg 183 347 bang;
-#N canvas 0 0 450 300 graph1 0;
-#X array array2 150000 float 0;
-#X coords 0 1 150000 -1 200 150 1;
-#X restore 393 464 graph;
-#X msg 393 622 \; array2 resize 150000;
-#X obj 25 613 soundfiler;
-#X obj 16 453 tabread4~ array2;
-#X obj 16 407 *~;
-#X obj 16 522 dac~;
-#X obj 16 499 hip~ 5;
-#X obj 62 411 samphold~;
-#X obj 16 430 +~;
-#X floatatom 96 303 0 0 0 0 - - -;
-#X obj 96 326 *~ 1000;
-#X msg 43 568 read ../doc/sound/bell.aiff array2;
-#X msg 43 591 read ../doc/sound/vocal.aiff array2;
-#X msg 47 229 set 0.5;
-#X text 95 196 left signal input is transposition (1 is normal \, 2
-is up an octave \, etc);
-#X text 82 4 loop~ - phase generator for looping samplers;
-#X text 116 228 set phase (0 to 1);
-#X text 104 253 reset phase to 0;
-#X text 104 278 right signal input is window size in samples;
-#X text 134 302 here's how to handle onsets;
-#X obj 16 476 *~;
-#X floatatom 167 432 0 0 0 0 - - -;
-#X obj 167 501 line~;
-#X obj 167 455 dbtorms;
-#X obj 167 478 pack 0 50;
-#X text 201 431 output level 0-100;
-#X text 187 326 print outputs;
-#X text 33 32 loop~ takes input signals to set a window size and transposition
-\, and outputs a phase and a sampled window size. The window size only
-changes at phase zero crossings and the phase output is adjusted so
-that changing window size doesn't change the transposition.;
-#X text 33 112 You can send "bang" or "set" message to force the phase
-to zero--you should mute the output before doing so. This may be desirable
-if you've set a large window size but then want to decrease it without
-waiting for the next phase crossing.;
-#X connect 0 0 3 0;
-#X connect 2 0 1 0;
-#X connect 3 0 6 0;
-#X connect 3 0 12 0;
-#X connect 3 0 15 1;
-#X connect 3 1 1 0;
-#X connect 3 1 12 1;
-#X connect 4 0 3 1;
-#X connect 5 0 3 0;
-#X connect 7 0 6 0;
-#X connect 11 0 28 0;
-#X connect 12 0 16 0;
-#X connect 14 0 13 0;
-#X connect 14 0 13 1;
-#X connect 15 0 16 1;
-#X connect 16 0 11 0;
-#X connect 17 0 18 0;
-#X connect 18 0 15 0;
-#X connect 19 0 10 0;
-#X connect 20 0 10 0;
-#X connect 21 0 3 0;
-#X connect 28 0 14 0;
-#X connect 29 0 31 0;
-#X connect 30 0 28 1;
-#X connect 31 0 32 0;
-#X connect 32 0 30 0;
diff --git a/extra/loop~/loop~.c b/extra/loop~/loop~.c
deleted file mode 100644
index 2f4400307..000000000
--- a/extra/loop~/loop~.c
+++ /dev/null
@@ -1,164 +0,0 @@
-/* loop~ -- loop generator for sampling */
-
-/*  Copyright 1997-1999 Miller Puckette.
-Permission is granted to use this software for any purpose provided you
-keep this copyright notice intact.
-
-THE AUTHOR AND HIS EMPLOYERS MAKE NO WARRANTY, EXPRESS OR IMPLIED,
-IN CONNECTION WITH THIS SOFTWARE.
-
-This file is downloadable from http://www.crca.ucsd.edu/~msp .
-
-*/
-
-#ifdef PD
-#include "m_pd.h"
-#endif
-
-typedef struct _loopctl
-{
-    double l_phase;
-    float l_invwindow;
-    float l_window;
-    int l_resync;
-} t_loopctl;
-
-static void loopctl_run(t_loopctl *x, float *transposein,
-        float *windowin, float *rawout, float *windowout, int n)
-{
-    float window, invwindow;
-    double phase = x->l_phase;
-    if (x->l_resync)
-    {
-        window = *windowin;
-        if (window < 0)
-        {
-            if (window > -1)
-                window = -1;
-            invwindow = -1/window;
-        }
-        else
-        {
-            if (window < 1)
-                window = 1;
-            invwindow = 1/window;
-        }
-        x->l_resync = 0;
-    }
-    else
-    {
-        window = x->l_window;
-        phase = x->l_phase;
-        invwindow = x->l_invwindow;
-    }
-    while (n--)
-    {
-        double phaseinc = invwindow * *transposein++;
-        double newphase;
-        float nwind = *windowin++;
-        if (phaseinc >= 1 || phaseinc < 0)
-            phaseinc = 0;
-        newphase = phase + phaseinc;
-        if (newphase >= 1)
-        {
-            window = nwind;
-            if (window < 0)
-            {
-                if (window > -1)
-                    window = -1;
-                invwindow = -1/window;
-            }
-            else
-            {
-                if (window < 1)
-                    window = 1;
-                invwindow = 1/window;
-            }
-            newphase -= 1.;
-        }
-        phase = newphase;
-        *rawout++ = (float)phase;
-        *windowout++ = window;
-    }
-    x->l_invwindow = invwindow;
-    x->l_window = window;
-    x->l_phase = phase;
-}
-
-static void loopctl_init(t_loopctl *x)
-{
-    x->l_window = 1;
-    x->l_invwindow = 1;
-    x->l_phase = 0;
-}
-
-static void loopctl_set(t_loopctl *x, float val)
-{
-    if (val < 0 || val > 1)
-        val = 0;
-    x->l_phase = val;
-    x->l_resync = 1;
-}
-
-#ifdef PD
-
-typedef struct _loop
-{
-    t_object x_obj;
-    t_float x_f;
-    t_loopctl x_loopctl;
-} t_loop;
-
-static t_class *loop_class;
-
-static void *loop_new(void)
-{
-    t_loop *x = (t_loop *)pd_new(loop_class);
-    loopctl_init(&x->x_loopctl);
-    inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
-    outlet_new(&x->x_obj, gensym("signal"));
-    outlet_new(&x->x_obj, gensym("signal"));
-    return (x);
-}
-
-static t_int *loop_perform(t_int *w)
-{
-    t_loopctl *ctl = (t_loopctl *)(w[1]);
-    t_float *in1 = (t_float *)(w[2]);
-    t_float *in2 = (t_float *)(w[3]);
-    t_float *out1 = (t_float *)(w[4]);
-    t_float *out2 = (t_float *)(w[5]);
-    int n = (int)(w[6]);
-    loopctl_run(ctl, in1, in2, out1, out2, n);
-    return (w+7);
-}
-
-static void loop_dsp(t_loop *x, t_signal **sp)
-{
-    dsp_add(loop_perform, 6,
-        &x->x_loopctl, sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[3]->s_vec,
-            sp[0]->s_n);
-}
-
-static void loop_set(t_loop *x, t_floatarg val)
-{
-    loopctl_set(&x->x_loopctl, val);
-}
-
-static void loop_bang(t_loop *x)
-{
-    loopctl_set(&x->x_loopctl, 0);
-}
-
-void loop_tilde_setup(void)
-{
-    loop_class = class_new(gensym("loop~"), (t_newmethod)loop_new, 0,
-        sizeof(t_loop), 0, 0);
-    class_addmethod(loop_class, (t_method)loop_dsp, gensym("dsp"), A_CANT, 0);
-    CLASS_MAINSIGNALIN(loop_class, t_loop, x_f);
-    class_addmethod(loop_class, (t_method)loop_set, gensym("set"),
-        A_DEFFLOAT, 0);
-    class_addbang(loop_class, loop_bang);
-}
-
-#endif /* PD */
diff --git a/extra/loop~/makefile b/extra/loop~/makefile
deleted file mode 100644
index fd21f2b4c..000000000
--- a/extra/loop~/makefile
+++ /dev/null
@@ -1,4 +0,0 @@
-NAME=loop~
-CSYM=loop_tilde
-
-include ../makefile
diff --git a/extra/loop~/test-loop~.pd b/extra/loop~/test-loop~.pd
deleted file mode 100644
index 9966483df..000000000
--- a/extra/loop~/test-loop~.pd
+++ /dev/null
@@ -1,58 +0,0 @@
-#N canvas 33 0 680 609 12;
-#X floatatom 52 262 0 0 0 0 - - -;
-#X obj 261 346 print~;
-#X msg 47 373 bang;
-#X msg 274 313 bang;
-#X obj 52 306 loop~;
-#X floatatom 102 245 0 0 0 0 - - -;
-#N canvas 0 0 450 300 graph1 0;
-#X array array1 44100 float 0;
-#X coords 0 10 44100 0 200 150 1;
-#X restore 65 17 graph;
-#X msg 43 204 \; array1 resize 44100;
-#X obj 25 401 tabwrite~ array1;
-#X msg 208 371 bang;
-#X obj 176 402 tabwrite~ array1;
-#X msg 194 261 bang;
-#X obj 204 347 print~;
-#X msg 217 314 bang;
-#N canvas 0 0 450 300 graph1 0;
-#X array array2 150000 float 0;
-#X coords 0 1 150000 -1 200 150 1;
-#X restore 332 398 graph;
-#X msg 326 274 \; array2 resize 150000;
-#X obj 103 529 tabread4~ array2;
-#X obj 64 481 *~;
-#X obj 107 581 dac~;
-#X obj 105 552 hip~ 5;
-#X obj 123 482 samphold~;
-#X obj 102 506 +~;
-#X floatatom 106 430 0 0 0 0 - - -;
-#X obj 108 453 *~ 1000;
-#X obj 312 215 soundfiler;
-#X msg 330 170 read ../doc/sound/bell.aiff array2;
-#X msg 330 193 read ../doc/sound/vocal.aiff array2;
-#X connect 0 0 4 0;
-#X connect 2 0 8 0;
-#X connect 3 0 1 0;
-#X connect 4 0 12 0;
-#X connect 4 0 17 0;
-#X connect 4 0 8 0;
-#X connect 4 0 20 1;
-#X connect 4 1 10 0;
-#X connect 4 1 1 0;
-#X connect 4 1 17 1;
-#X connect 5 0 4 1;
-#X connect 9 0 10 0;
-#X connect 11 0 4 0;
-#X connect 13 0 12 0;
-#X connect 16 0 19 0;
-#X connect 17 0 21 0;
-#X connect 19 0 18 0;
-#X connect 19 0 18 1;
-#X connect 20 0 21 1;
-#X connect 21 0 16 0;
-#X connect 22 0 23 0;
-#X connect 23 0 20 0;
-#X connect 25 0 24 0;
-#X connect 26 0 24 0;
diff --git a/extra/lrshift~/lrshift~-help.pd b/extra/lrshift~/lrshift~-help.pd
deleted file mode 100644
index fdf7b0c53..000000000
--- a/extra/lrshift~/lrshift~-help.pd
+++ /dev/null
@@ -1,33 +0,0 @@
-#N canvas 143 0 673 325 12;
-#X msg 268 277 bang;
-#X obj 244 303 print~;
-#X msg 185 278 bang;
-#X obj 161 304 print~;
-#X text 53 117 click here first;
-#X msg 72 270 bang;
-#X obj 48 296 print~;
-#X text 162 222 shift left;
-#X text 243 224 shift right;
-#X obj 161 252 lrshift~ 1;
-#X obj 244 251 lrshift~ -1;
-#X text 39 37 Acting at whatever vector size the window is running
-at \, lrshift~ shifts samples to the left (toward the beginning sample)
-or to the right. The argument gives the direction and the amount of
-the shift. The rightmost (or leftmost) samples are set to zero.;
-#N canvas 0 0 450 300 (subpatch) 0;
-#X array shiftin 64 float 0;
-#X coords 0 1 63 0 200 140 1;
-#X restore 448 118 graph;
-#X text 115 11 -- shift signal vector elements left or right;
-#X msg 54 138 \; pd dsp 1 \; shiftin 1 1;
-#X obj 48 204 tabreceive~ shiftin;
-#X text 525 308 Updated for Pd 0.31.;
-#X obj 47 11 lrshift~;
-#X connect 0 0 1 0;
-#X connect 2 0 3 0;
-#X connect 5 0 6 0;
-#X connect 9 0 3 0;
-#X connect 10 0 1 0;
-#X connect 15 0 6 0;
-#X connect 15 0 9 0;
-#X connect 15 0 10 0;
diff --git a/extra/lrshift~/lrshift~.c b/extra/lrshift~/lrshift~.c
deleted file mode 100644
index 166facc16..000000000
--- a/extra/lrshift~/lrshift~.c
+++ /dev/null
@@ -1,76 +0,0 @@
-#include "m_pd.h"
-
-/* ------------------------ lrshift~ ----------------------------- */
-
-static t_class *lrshift_tilde_class;
-
-typedef struct _lrshift_tilde
-{
-    t_object x_obj;
-    int x_n;
-    float x_f;
-} t_lrshift_tilde;
-
-static t_int *leftshift_perform(t_int *w)
-{
-    t_float *in = (t_float *)(w[1]);
-    t_float *out= (t_float *)(w[2]);
-    int n = (int)(w[3]);
-    int shift = (int)(w[4]);
-    in += shift;
-    n -= shift;
-    while (n--)
-        *out++ = *in++;
-    while (shift--)
-        *out++ = 0;
-    return (w+5);
-}
-
-static t_int *rightshift_perform(t_int *w)
-{
-    t_float *in = (t_float *)(w[1]);
-    t_float *out= (t_float *)(w[2]);
-    int n = (int)(w[3]);
-    int shift = (int)(w[4]);
-    n -= shift;
-    in -= shift;
-    while (n--)
-        *--out = *--in;
-    while (shift--)
-        *--out = 0;
-    return (w+5);
-}
-
-static void lrshift_tilde_dsp(t_lrshift_tilde *x, t_signal **sp)
-{
-    int n = sp[0]->s_n;
-    int shift = x->x_n;
-    if (shift > n)
-        shift = n;
-    if (shift < -n)
-        shift = -n;
-    if (shift < 0)
-        dsp_add(rightshift_perform, 4,
-            sp[0]->s_vec + n, sp[1]->s_vec + n, n, -shift);
-    else dsp_add(leftshift_perform, 4,
-            sp[0]->s_vec, sp[1]->s_vec, n, shift);
-}
-
-static void *lrshift_tilde_new(t_floatarg f)
-{
-    t_lrshift_tilde *x = (t_lrshift_tilde *)pd_new(lrshift_tilde_class);
-    x->x_n = f;
-    x->x_f = 0;
-    outlet_new(&x->x_obj, gensym("signal"));
-    return (x);
-}
-
-void lrshift_tilde_setup(void)
-{
-    lrshift_tilde_class = class_new(gensym("lrshift~"),
-        (t_newmethod)lrshift_tilde_new, 0, sizeof(t_lrshift_tilde), 0, 
-            A_DEFFLOAT, 0);
-    CLASS_MAINSIGNALIN(lrshift_tilde_class, t_lrshift_tilde, x_f);
-    class_addmethod(lrshift_tilde_class, (t_method)lrshift_tilde_dsp,
-        gensym("dsp"), 0);
-}
diff --git a/extra/lrshift~/makefile b/extra/lrshift~/makefile
deleted file mode 100644
index d6a24cfe3..000000000
--- a/extra/lrshift~/makefile
+++ /dev/null
@@ -1,4 +0,0 @@
-NAME=lrshift~
-CSYM=lrshift_tilde
-
-include ../makefile
diff --git a/extra/makefile b/extra/makefile
index a844eaa65..ee028616a 100644
--- a/extra/makefile
+++ b/extra/makefile
@@ -49,7 +49,7 @@ d_fat: $(NAME).d_fat
 .SUFFIXES: .d_ppc .d_fat
 
 DARWINCFLAGS = -DPD -O2 -Wall -W -Wshadow -Wstrict-prototypes \
-    -Wno-unused -Wno-parentheses -Wno-switch $(OPT_CFLAGS)
+    -Wno-unused -Wno-parentheses -Wno-switch
 
 .c.d_ppc:
 	$(CC) $(DARWINCFLAGS) $(LINUXINCLUDE) -o $*.o -c $*.c
@@ -59,7 +59,7 @@ DARWINCFLAGS = -DPD -O2 -Wall -W -Wshadow -Wstrict-prototypes \
 .c.d_fat:
 	$(CC) -arch i386 -arch ppc $(DARWINCFLAGS) $(LINUXINCLUDE) -o $*.o -c $*.c
 	$(CC) -arch i386 -arch ppc -bundle -undefined suppress -flat_namespace \
-	    -o $*.pd_darwin $*.o 
+	    -o $*.d_fat $*.o 
 	rm -f $*.o
 
 # ----------------------------------------------------------
diff --git a/extra/output~-help.pd b/extra/output~-help.pd
deleted file mode 100644
index cd4883646..000000000
--- a/extra/output~-help.pd
+++ /dev/null
@@ -1,11 +0,0 @@
-#N canvas 103 48 450 300 10;
-#X obj 104 118 osc~ 200;
-#X obj 241 122 noise~;
-#X text 38 28 a GUI replacement for [dac~] with controls for "compute
-audio" \, volume \, and a mute button.;
-#X obj 91 166 output~;
-#X obj 220 165 output~;
-#X connect 0 0 3 0;
-#X connect 0 0 3 1;
-#X connect 1 0 4 1;
-#X connect 1 0 4 0;
diff --git a/extra/output~.pd b/extra/output~.pd
deleted file mode 100644
index ee2df2d58..000000000
--- a/extra/output~.pd
+++ /dev/null
@@ -1,124 +0,0 @@
-#N canvas 508 22 548 407 10;
-#X obj 13 107 hsl 42 23 0.01 1 1 0 \$0-v \$0-v volume 7 13 1 9 -245500
--13381 -1 0 0;
-#X obj 57 94 tgl 18 0 THIS_IS_HERE_TO_GET_RID_OF_THE_OUTLET \$0-dsp-toggle
-dsp 2 9 1 9 -225271 -195568 -33289 1 1;
-#N canvas 366 514 482 356 dsp 0;
-#X obj 11 7 inlet;
-#X obj 92 226 select 0 1;
-#X msg 125 248 6;
-#X obj 92 57 route dsp;
-#X obj 92 36 receive pd;
-#X obj 206 138 loadbang;
-#X msg 11 220 dsp \$1;
-#X obj 11 245 send pd;
-#X msg 206 278 set \$1;
-#X obj 206 174 value GLOBAL_PDDP_DSP;
-#X msg 109 278 color \$1 20 12;
-#X obj 180 309 send \$0-dsp-toggle;
-#X obj 92 115 change;
-#X msg 92 247 0;
-#X connect 0 0 6 0;
-#X connect 0 0 12 0;
-#X connect 1 0 13 0;
-#X connect 1 1 2 0;
-#X connect 2 0 10 0;
-#X connect 3 0 12 0;
-#X connect 4 0 3 0;
-#X connect 5 0 9 0;
-#X connect 6 0 7 0;
-#X connect 8 0 11 0;
-#X connect 9 0 8 0;
-#X connect 9 0 1 0;
-#X connect 10 0 11 0;
-#X connect 12 0 8 0;
-#X connect 12 0 1 0;
-#X connect 12 0 9 0;
-#X connect 13 0 10 0;
-#X restore 112 128 pd dsp logic;
-#X obj 315 12 inlet;
-#X obj 57 112 bng 18 1000 50 0 THIS_IS_HERE_TO_GET_RID_OF_THE_OUTLET
-\$0-MUTE_TOGGLE empty 0 9 2 8 -261689 -258699 -195568;
-#X obj 191 12 inlet~;
-#X obj 86 283 line~;
-#X obj 186 343 *~;
-#X obj 206 373 dac~;
-#X text 203 32 audio in;
-#X obj 254 12 inlet~;
-#X obj 248 342 *~;
-#X obj 201 83 hip~ 3;
-#X obj 263 83 hip~ 3;
-#X obj 12 298 send pd;
-#X msg 12 277 dsp 1;
-#X obj 248 372 outlet~;
-#X obj 148 372 outlet~;
-#X obj 330 372 outlet;
-#N canvas 679 297 361 328 mute 0;
-#X obj 23 20 inlet;
-#X obj 173 20 inlet;
-#X obj 222 208 float;
-#X obj 265 121 tgl 15 1 empty empty empty 17 7 0 10 -262144 -1 -1 0
-1;
-#X obj 222 162 spigot;
-#X obj 172 41 trigger bang bang;
-#X obj 254 263 outlet;
-#X msg 274 208 0;
-#X obj 274 163 select 0;
-#X obj 127 64 bang;
-#X msg 127 85 set 1;
-#X obj 65 304 send \$0-MUTE_TOGGLE;
-#X msg 65 283 color \$1 13 20;
-#X obj 65 235 bang;
-#X msg 65 255 0;
-#X msg 98 255 3;
-#X connect 0 0 2 1;
-#X connect 0 0 9 0;
-#X connect 1 0 5 0;
-#X connect 2 0 6 0;
-#X connect 2 0 13 0;
-#X connect 3 0 4 1;
-#X connect 3 0 8 0;
-#X connect 4 0 2 0;
-#X connect 5 0 4 0;
-#X connect 5 1 3 0;
-#X connect 7 0 6 0;
-#X connect 8 0 7 0;
-#X connect 8 0 15 0;
-#X connect 9 0 10 0;
-#X connect 9 0 13 0;
-#X connect 10 0 3 0;
-#X connect 12 0 11 0;
-#X connect 13 0 14 0;
-#X connect 14 0 12 0;
-#X connect 15 0 12 0;
-#X restore 86 156 pd mute;
-#X obj 86 262 pack 0 50;
-#X text 153 261 <-- make a ramp to avoid clicks or zipper noise;
-#X msg 86 227 0;
-#X obj 86 204 moses 0.011;
-#X text 307 84 filter out DC;
-#X connect 0 0 15 0;
-#X connect 0 0 19 0;
-#X connect 0 0 18 0;
-#X connect 0 0 23 0;
-#X connect 1 0 2 0;
-#X connect 3 0 0 0;
-#X connect 4 0 19 1;
-#X connect 5 0 12 0;
-#X connect 6 0 11 0;
-#X connect 6 0 7 0;
-#X connect 7 0 8 0;
-#X connect 7 0 17 0;
-#X connect 10 0 13 0;
-#X connect 11 0 8 1;
-#X connect 11 0 16 0;
-#X connect 12 0 7 1;
-#X connect 13 0 11 1;
-#X connect 15 0 14 0;
-#X connect 19 0 0 0;
-#X connect 19 0 23 0;
-#X connect 20 0 6 0;
-#X connect 22 0 20 0;
-#X connect 23 0 22 0;
-#X connect 23 1 20 0;
-#X coords 0 0 1 1 65 44 1 10 90;
diff --git a/extra/pd~/makefile b/extra/pd~/makefile
deleted file mode 100644
index d069c73dc..000000000
--- a/extra/pd~/makefile
+++ /dev/null
@@ -1,15 +0,0 @@
-NAME=pd~
-CSYM=pd_tilde
-
-include ../makefile
-
-pd_linux: pdsched.pd_linux
-
-d_fat: pdsched.d_fat
-d_ppc: pdsched.d_ppc
-
-pdsched.pd_linux: pdsched.c
-	$(CC) $(LINUXCFLAGS) $(LINUXINCLUDE) -o $*.o -c $*.c
-	$(CC) -shared -o $*.pd_linux $*.o -lc -lm
-	strip --strip-unneeded $*.pd_linux
-	rm -f $*.o
diff --git a/extra/pd~/notes.txt b/extra/pd~/notes.txt
deleted file mode 100644
index 59129d5ab..000000000
--- a/extra/pd~/notes.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-pd -schedlib `pwd`/pdsched
-
-dolist:
-pd~ to delay starting subproc until asked
-figure out about setting nchannels from command line
-fix maximum nchannels in and out
-
-
diff --git a/extra/pd~/pdsched.c b/extra/pd~/pdsched.c
deleted file mode 100644
index 7efe49a95..000000000
--- a/extra/pd~/pdsched.c
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Copyright 2008 Miller Puckette.  Berkeley license; see the
-file LICENSE.txt in this distribution. */
-
-/* A plug-in scheduler that turns Pd into a filter that inputs and
-outputs audio and messages. */
-
-/* todo: 
-    fix schedlib code to use extent2
-    figure out about  if (sys_externalschedlib) { return; } in s_audio.c
-    make buffer size ynamically growable
-
-*/    
-#include "m_pd.h"
-#include "s_stuff.h"
-#include <stdio.h>
-
-#define BUFSIZE 65536
-static char inbuf[BUFSIZE];
-
-int pd_extern_sched(char *flags)
-{
-    int naudioindev, audioindev[MAXAUDIOINDEV], chindev[MAXAUDIOINDEV];
-    int naudiooutdev, audiooutdev[MAXAUDIOOUTDEV], choutdev[MAXAUDIOOUTDEV];
-    int i, j, rate, advance, callback, chin, chout, fill = 0, c;
-    t_binbuf *b = binbuf_new();
-
-    sys_get_audio_params(&naudioindev, audioindev, chindev,
-        &naudiooutdev, audiooutdev, choutdev, &rate, &advance, &callback);
-
-    chin = (naudioindev < 1 ? 0 : chindev[0]);
-    chout = (naudiooutdev < 1 ? 0 : choutdev[0]);
-
-    fprintf(stderr, "Pd plug-in scheduler called, chans %d %d, sr %d\n",
-        chin, chout, (int)rate);
-    sys_setchsr(chin, chout, rate);
-    sys_audioapi = API_NONE;
-    while ((c = getchar()) != EOF)
-    {
-        if (c == ';')
-        {
-            int n;
-            t_atom *ap;
-            binbuf_text(b, inbuf, fill);
-            n = binbuf_getnatom(b);
-            ap = binbuf_getvec(b);
-            fill = 0;
-            if (n > 0 && ap[0].a_type == A_FLOAT)
-            {
-                /* a list -- take it as incoming signals. */
-                int chan, nchan = n/DEFDACBLKSIZE;
-                t_sample *fp;
-                for (i = chan = 0, fp = sys_soundin; chan < nchan; chan++)
-                    for (j = 0; j < DEFDACBLKSIZE; j++)
-                        *fp++ = atom_getfloat(ap++);
-                for (; chan < chin; chan++)
-                    for (j = 0; j < DEFDACBLKSIZE; j++)
-                        *fp++ = 0;
-                sched_tick(sys_time+sys_time_per_dsp_tick);
-                sys_pollgui();
-                printf(";\n");
-                for (i = chout*DEFDACBLKSIZE, fp = sys_soundout; i--; fp++)
-                {
-                    printf("%g\n", *fp);
-                    *fp = 0;
-                }
-                printf(";\n");
-                fflush(stdout);
-            }
-            else if (n > 1 && ap[0].a_type == A_SYMBOL)
-            {
-                t_pd *whom = ap[0].a_w.w_symbol->s_thing;
-                if (!whom)
-                    error("%s: no such object", ap[0].a_w.w_symbol->s_name);
-                else if (ap[1].a_type == A_SYMBOL)
-                    typedmess(whom, ap[1].a_w.w_symbol, n-2, ap+2);
-                else pd_list(whom, 0, n-1, ap+1);
-            }
-        }
-        else if (fill < BUFSIZE)
-            inbuf[fill++] = c;
-        else if (fill == BUFSIZE)
-            fprintf(stderr, "pd-extern: input buffer overflow\n");
-    }
-    return (0);
-}
diff --git a/extra/pd~/pd~-help.pd b/extra/pd~/pd~-help.pd
deleted file mode 100644
index 8bc357e0c..000000000
--- a/extra/pd~/pd~-help.pd
+++ /dev/null
@@ -1,75 +0,0 @@
-#N canvas 12 0 566 872 12;
-#X msg 31 406 foo bar baz;
-#X obj 189 466 osc~ 440;
-#X obj 127 645 env~ 8192;
-#X floatatom 127 694 5 0 0 0 - - -;
-#X msg 434 807 \; pd dsp 1;
-#X msg 24 332 pd~ stop;
-#X obj 127 670 i;
-#X obj 241 643 env~ 8192;
-#X floatatom 241 693 5 0 0 0 - - -;
-#X obj 241 669 i;
-#X obj 123 489 *~;
-#X obj 158 490 tgl 15 0 empty empty empty 17 7 0 10 -262144 -1 -1 0
-1;
-#X obj 189 490 *~;
-#X obj 224 491 tgl 15 0 empty empty empty 17 7 0 10 -262144 -1 -1 0
-1;
-#X obj 434 781 loadbang;
-#X obj 14 691 print x;
-#X msg 15 309 pd~ start pd~-subprocess.pd;
-#X obj 14 532 pd~ -ninsig 2 -noutsig 2 -fifo 20;
-#X obj 37 20 pd~;
-#X text 69 22 - run a pd sub-process;
-#X text 27 57 The pd~ object starts and manages a Pd sub-process that
-can communicate with the super-process (this one) via audio channels
-and/or Pd messages. In this way you can take advantage of multi-core
-CPUs \, and/or use Pd features from within Max (if you're using the
-Max version of pd~).;
-#X text 24 251 Sending a new "start" message will stop the sub-process
-and start a new one. If you just want to stop the sub-process \, send
-"stop".;
-#X text 33 353 Any message besides "pd~" is sent to the sub-process.
-For instance \, the message below sends "bar baz" to any object in
-the sub-process named "foo" \, such as a "receive" object.;
-#X text 43 430 Audio signals appear in adc~ objects in the sub-process.
-The sub-process doesn't open real audio devices.;
-#X text 281 473 Creation args:;
-#X text 265 490 -insig <n> sets input audio channels;
-#X text 266 508 -outsig <n> sets output channels;
-#X text 269 542 -fifo <n> sets round-trip delay in blocks;
-#X text 272 559 -pddir <s> sets Pd directory \, e.g. \,;
-#X text 299 574 .../Pd-0.42.app/Contents/Resources;
-#X text 272 590 -scheddir <s> sets scheduler dir \, e.g. \,;
-#X text 297 607 .../.../Resources/extra/pd~;
-#X text 267 524 -sr <n> sets sample rate;
-#X text 20 716 The first outlet reports messages the sub-process sends
-us via "stdout" objects. Any other outlets are signals corresponding
-to "dac~" objects in the sub-process.;
-#X text 10 784 ATTENTION: DSP must be running in this process for the
-sub-process to run. This is because its clock is slaved to audio I/O
-it gets from us!;
-#X text 359 849 Updated for Pd version 0.42.;
-#X text 24 138 Messages with "pd~" selector control the sub-process.
-"pd~ start" takes as arguments any startup arguments you wish to send
-the sub-process. For example \, specify "-nogui" to stop the sub-process's
-GUI from appearing. You don't have to specify the number of channels
-in and out \, since that's set by creation arguments below. Audio config
-arguments arguments (-audiobuf \, -audiodev \, etc.) are ignored.;
-#X connect 0 0 17 0;
-#X connect 1 0 10 0;
-#X connect 1 0 12 0;
-#X connect 2 0 6 0;
-#X connect 5 0 17 0;
-#X connect 6 0 3 0;
-#X connect 7 0 9 0;
-#X connect 9 0 8 0;
-#X connect 10 0 17 0;
-#X connect 11 0 10 1;
-#X connect 12 0 17 1;
-#X connect 13 0 12 1;
-#X connect 14 0 4 0;
-#X connect 16 0 17 0;
-#X connect 17 0 15 0;
-#X connect 17 1 2 0;
-#X connect 17 2 7 0;
diff --git a/extra/pd~/pd~-subprocess.pd b/extra/pd~/pd~-subprocess.pd
deleted file mode 100644
index 1d883ab18..000000000
--- a/extra/pd~/pd~-subprocess.pd
+++ /dev/null
@@ -1,60 +0,0 @@
-#N canvas 577 21 563 559 12;
-#X obj 202 395 r foo;
-#X obj 202 423 print foo;
-#X obj 87 174 adc~;
-#X obj 72 442 stdout;
-#X msg 72 364 a b c;
-#X msg 455 441 \; pd dsp 1;
-#X obj 87 201 env~ 8192;
-#X floatatom 87 250 5 0 0 0 - - -;
-#X obj 87 226 i;
-#X obj 263 253 dac~;
-#X obj 262 185 osc~ 440;
-#X obj 262 219 *~;
-#X obj 297 220 tgl 15 0 empty empty empty 17 7 0 10 -262144 -1 -1 0
-1;
-#X obj 332 186 osc~ 440;
-#X obj 332 220 *~;
-#X obj 367 221 tgl 15 0 empty empty empty 17 7 0 10 -262144 -1 -1 0
-1;
-#X msg 86 411 bang;
-#X obj 455 417 loadbang;
-#X obj 160 201 env~ 8192;
-#X floatatom 160 250 5 0 0 0 - - -;
-#X obj 160 226 i;
-#X msg 86 388 4;
-#X text 62 8 This is a test patch to demonstrate the Pd~ object. It's
-intended as the patch to run in the sub-process. The sub-process (which
-is a separate instance of Pd) can be called from a Max or Pd super-process.
-;
-#X text 63 73 Audio inlets and outlets on the Pd~ object (in the super-process)
-talk to adc~ and dac~ objects here - so \, for instance \, the first
-adc~ here is the first inlet of the pd~ object \, and the first chanel
-of dac~ goes to the second outlet of pd~ (because the first one is
-for messages \, as shown further below.);
-#X text 58 283 Any message sent to a stdout object in this sub-process
-(below) appears on the first \, message outlet of the pd~ object in
-the super-process. The super-process can send messages to any "receive"
-object in this sub-process.;
-#X text 137 478 We turn DSP on at load for convenience - control objects
-in this patch will still work without it (unlike in the super-process
-\, where DSP must be on for time to move forward in the sub-process.)
-;
-#X text 351 538 Updated for Pd version 0.42.;
-#X connect 0 0 1 0;
-#X connect 2 0 6 0;
-#X connect 2 1 18 0;
-#X connect 4 0 3 0;
-#X connect 6 0 8 0;
-#X connect 8 0 7 0;
-#X connect 10 0 11 0;
-#X connect 11 0 9 0;
-#X connect 12 0 11 1;
-#X connect 13 0 14 0;
-#X connect 14 0 9 1;
-#X connect 15 0 14 1;
-#X connect 16 0 3 0;
-#X connect 17 0 5 0;
-#X connect 18 0 20 0;
-#X connect 20 0 19 0;
-#X connect 21 0 3 0;
diff --git a/extra/pd~/pd~.c b/extra/pd~/pd~.c
deleted file mode 100644
index c6ff72cf2..000000000
--- a/extra/pd~/pd~.c
+++ /dev/null
@@ -1,765 +0,0 @@
-/*
-  pd~.c - embed a Pd process within Pd or Max.
-
-  Copyright 2008 Miller Puckette
-  BSD license; see README.txt in this distribution for details.
-*/
-
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <ctype.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/wait.h>
-
-#ifdef NT
-#pragma warning (disable: 4305 4244)
-#endif
-
-#ifdef MSP
-#include "ext.h"
-#include "z_dsp.h"
-#include "math.h"
-#include "ext_support.h"
-#include "ext_proto.h"
-#include "ext_obex.h"
-
-typedef double t_floatarg;
-#define w_symbol w_sym
-#define A_SYMBOL A_SYM
-#define getbytes t_getbytes
-#define freebytes t_freebytes
-#define ERROR error(
-void *pd_tilde_class;
-#define MAXPDSTRING 4096
-#define DEFDACBLKSIZE 64
-#endif /* MSP */
-
-#ifdef PD
-#include "m_pd.h"
-#include "s_stuff.h"
-static t_class *pd_tilde_class;
-char *class_gethelpdir(t_class *c);
-#define ERROR pd_error(x, 
-
-#endif
-
-#ifdef __linux__
-#ifdef __x86_64__
-static char pd_tilde_dllextent[] = ".l_ia64",
-    pd_tilde_dllextent2[] = ".pd_linux";
-#else
-static char pd_tilde_dllextent[] = ".l_i386",
-    pd_tilde_dllextent2[] = ".pd_linux";
-#endif
-#endif
-#ifdef __APPLE__
-static char pd_tilde_dllextent[] = ".d_fat",
-    pd_tilde_dllextent2[] = ".pd_darwin";
-#endif
-
-/* ------------------------ pd_tilde~ ----------------------------- */
-
-#define MSGBUFSIZE 65536
-
-typedef struct _pd_tilde
-{
-#ifdef PD
-    t_object x_obj;
-    t_clock *x_clock;
-    t_outlet *x_outlet1;        /* for messages back from subproc */
-    t_canvas *x_canvas;
-#endif /* PD */
-#ifdef MSP
-    t_pxobject x_obj;
-    void *x_outlet1;
-    void *x_clock;
-#endif /* MSP */
-    FILE *x_infd;
-    FILE *x_outfd;
-    char *x_msgbuf;
-    int x_msgbufsize;
-    int x_infill;
-    int x_childpid;
-    int x_ninsig;
-    int x_noutsig;
-    int x_fifo;
-    float x_sr;
-    t_symbol *x_pddir;
-    t_symbol *x_schedlibdir;
-    t_sample **x_insig;
-    t_sample **x_outsig;
-} t_pd_tilde;
-
-#ifdef MSP
-static void *pd_tilde_new(t_symbol *s, long ac, t_atom *av);
-static void pd_tilde_tick(t_pd_tilde *x);
-static t_int *pd_tilde_perform(t_int *w);
-static void pd_tilde_dsp(t_pd_tilde *x, t_signal **sp);
-void pd_tilde_assist(t_pd_tilde *x, void *b, long m, long a, char *s);
-static void pd_tilde_free(t_pd_tilde *x);
-void pd_tilde_setup(void);
-int main();
-void pd_tilde_minvel_set(t_pd_tilde *x, void *attr, long ac, t_atom *av);
-char *strcpy(char *s1, const char *s2);
-#endif
-
-static void pd_tilde_tick(t_pd_tilde *x);
-static void pd_tilde_close(t_pd_tilde *x)
-{
-    if (x->x_outfd)
-        fclose(x->x_outfd);
-    if (x->x_infd)
-        fclose(x->x_infd);
-    if (x->x_childpid > 0)
-        waitpid(x->x_childpid, 0, 0);
-    if (x->x_msgbuf)
-        free(x->x_msgbuf);
-    x->x_infd = x->x_outfd = 0;
-    x->x_childpid = -1;
-    x->x_msgbuf = 0;
-    x->x_msgbufsize = 0;
-}
-
-static void pd_tilde_readmessages(t_pd_tilde *x)
-{
-    int gotsomething = 0, setclock = 0, wasempty = (x->x_infill == 0);
-    FILE *infd = x->x_infd;
-    while (1)
-    {
-        int c = getc(infd);
-        if (c == EOF)
-        {
-            ERROR "pd~: %s", strerror(errno));
-            pd_tilde_close(x);
-            break;
-        }
-        if (x->x_infill >= x->x_msgbufsize)
-        {
-            char *z = realloc(x->x_msgbuf, x->x_msgbufsize+MSGBUFSIZE);
-            if (!z)
-            {
-                ERROR "pd~: failed to grow input buffer");
-                pd_tilde_close(x);
-                break;
-            }
-            x->x_msgbuf = z;
-            x->x_msgbufsize += MSGBUFSIZE;
-        }
-        x->x_msgbuf[x->x_infill++] = c;
-        if (c == ';')
-        {
-            if (!gotsomething)
-                break;
-            gotsomething = 0;
-        }
-        else if (!isspace(c))
-            gotsomething = setclock = 1;
-    }
-    if (setclock)
-        clock_delay(x->x_clock, 0);
-    else if (wasempty)
-        x->x_infill = 0;
-}
-
-static void pd_tilde_donew(t_pd_tilde *x, char *pddir, char *schedlibdir,
-    char *patchdir, char *pdargs, int ninsig, int noutsig, int fifo,
-    float samplerate)
-{
-    int i, pid, pipe1[2], pipe2[2];
-    char cmdbuf[MAXPDSTRING], pdexecbuf[MAXPDSTRING], schedbuf[MAXPDSTRING];
-    struct stat statbuf;
-    x->x_infd = x->x_outfd = 0;
-    x->x_childpid = -1;
-    snprintf(pdexecbuf, MAXPDSTRING, "%s/bin/pd", pddir);
-    if (stat(pdexecbuf, &statbuf) < 0)
-    {
-        snprintf(pdexecbuf, MAXPDSTRING, "%s/../../../bin/pd", pddir);
-        if (stat(pdexecbuf, &statbuf) < 0)
-        {
-            snprintf(pdexecbuf, MAXPDSTRING, "%s/pd", pddir);
-            if (stat(pdexecbuf, &statbuf) < 0)
-            {
-                ERROR "pd~: can't stat %s", pdexecbuf);
-                goto fail1;
-            }
-        }
-    }
-    snprintf(schedbuf, MAXPDSTRING, "%s/pdsched%s", schedlibdir, 
-        pd_tilde_dllextent);
-    if (stat(schedbuf, &statbuf) < 0)
-    {
-        snprintf(schedbuf, MAXPDSTRING, "%s/pdsched%s", schedlibdir, 
-            pd_tilde_dllextent2);
-        if (stat(schedbuf, &statbuf) < 0)
-        {
-            ERROR "pd~: can't stat %s", schedbuf);
-            goto fail1;
-        }       
-    }
-    snprintf(cmdbuf, MAXPDSTRING,
-"%s -schedlib %s/pdsched -path %s -inchannels %d -outchannels %d -r %g %s\n",
-        pdexecbuf, schedlibdir, patchdir, ninsig, noutsig, samplerate, pdargs);
-#if 0
-#ifdef PD
-    fprintf(stderr, "%s", cmdbuf);
-#endif
-    post("cmd: %s", cmdbuf);
-#endif
-    if (pipe(pipe1) < 0)   
-    {
-        ERROR "pd~: can't create pipe");
-        goto fail1;
-    }
-    if (pipe(pipe2) < 0)   
-    {
-        ERROR "pd~: can't create pipe");
-        goto fail2;
-    }
-    if ((pid = fork()) < 0)
-    {
-        ERROR "pd~: can't fork");
-        goto fail3;
-    }
-    else if (pid == 0)
-    {
-        /* child process */
-        if (pipe2[1] == 0)
-        {
-            dup2(pipe2[1], 20);
-            close(pipe2[1]);
-            pipe2[1] = 20;
-        }
-        dup2(pipe1[0], 0);
-        dup2(pipe2[1], 1);
-        if (pipe1[0] >= 2)
-            close(pipe1[0]);
-        if (pipe1[1] >= 2)
-            close(pipe1[1]);
-        if (pipe2[0] >= 2)
-            close(pipe2[0]);
-        if (pipe2[1] >= 2)
-            close(pipe2[1]);
-        execl("/bin/sh", "sh", "-c", cmdbuf, (char*)0);
-        _exit(1);
-    }
-        /* OK, we're parent */
-    close(pipe1[0]);
-    close(pipe2[1]);
-    x->x_outfd = fdopen(pipe1[1], "w");
-    x->x_infd = fdopen(pipe2[0], "r");
-    x->x_childpid = pid;
-    for (i = 0; i < fifo; i++)
-        fprintf(x->x_outfd, "%s", ";\n0;\n");
-    fflush(x->x_outfd);
-    if (!(x->x_msgbuf = calloc(MSGBUFSIZE, 1)))
-    {
-        ERROR "pd~: can't allocate message buffer");
-        goto fail3;
-    }
-    x->x_msgbufsize = MSGBUFSIZE;
-    x->x_infill = 0;
-    /* fprintf(stderr, "read...\n"); */
-    pd_tilde_readmessages(x);
-    /* fprintf(stderr, "... done.\n"); */
-    return;
-fail3:
-    close(pipe2[0]);
-    close(pipe2[1]);
-    if (x->x_childpid > 0)
-        waitpid(x->x_childpid, 0, 0);
-fail2:
-    close(pipe1[0]);
-    close(pipe1[1]);
-fail1:
-    x->x_infd = x->x_outfd = 0;
-    x->x_childpid = -1;
-    return;
-}
-
-static t_int *pd_tilde_perform(t_int *w)
-{
-    t_pd_tilde *x = (t_pd_tilde *)(w[1]);
-    int n = (int)(w[2]), i, j, numbuffill = 0, c;
-    char numbuf[80];
-    FILE *infd = x->x_infd;
-    if (!infd)
-        goto zeroit;
-    fprintf(x->x_outfd, ";\n");
-    if (!x->x_ninsig)
-        fprintf(x->x_outfd, "0\n");
-    else for (i = 0; i < x->x_ninsig; i++)
-    {
-        t_sample *fp = x->x_insig[i];
-        for (j = 0; j < n; j++)
-            fprintf(x->x_outfd, "%g\n", *fp++);
-        for (; j < DEFDACBLKSIZE; j++)
-            fprintf(x->x_outfd, "0\n");
-    }
-    fprintf(x->x_outfd, ";\n");
-    fflush(x->x_outfd);
-    i = j = 0;
-    while (1)
-    {
-        while (1)
-        {
-            c = getc(infd);
-            if (c == EOF)
-            {
-                if (errno)
-                    ERROR "pd~: %s", strerror(errno));
-                else ERROR "pd~: subprocess exited");
-                pd_tilde_close(x);
-                goto zeroit;
-            }
-            else if (!isspace(c) && c != ';')
-            {
-                if (numbuffill < (80-1))
-                    numbuf[numbuffill++] = c;
-            }
-            else
-            {
-                t_sample z;
-                if (numbuffill)
-                {
-                    numbuf[numbuffill] = 0;
-                    if (sscanf(numbuf, "%f", &z) < 1)
-                        continue;
-                    if (i < x->x_noutsig)
-                        x->x_outsig[i][j] = z;
-                    if (++j >= DEFDACBLKSIZE)
-                        j = 0, i++;
-                }
-                numbuffill = 0;
-                break;
-            }
-        }
-        /* message terminated */
-        if (c == ';')
-            break;
-    }
-    for (; i < x->x_noutsig; i++, j = 0)
-    {
-        for (; j < DEFDACBLKSIZE; j++)
-            x->x_outsig[i][j] = 0;
-    }
-    pd_tilde_readmessages(x);
-    return (w+3);
-zeroit:
-    for (i = 0; i < x->x_noutsig; i++)
-    {
-        for (j = 0; j < DEFDACBLKSIZE; j++)
-            x->x_outsig[i][j] = 0;
-    }
-    return (w+3);
-}
-
-static void pd_tilde_dsp(t_pd_tilde *x, t_signal **sp)
-{
-    int i, n = (x->x_ninsig || x->x_noutsig ? sp[0]->s_n : 1);
-    t_sample **g;
-        
-    for (i = 0, g = x->x_insig; i < x->x_ninsig; i++, g++)
-        *g = (*(sp++))->s_vec;
-    
-    for (i = 0, g = x->x_outsig; i < x->x_noutsig; i++, g++)
-        *g = (*(sp++))->s_vec;
-    
-    dsp_add(pd_tilde_perform, 2, x, n);
-}
-
-static void pd_tilde_pdtilde(t_pd_tilde *x, t_symbol *s,
-    int argc, t_atom *argv)
-{
-    t_symbol *sel = ((argc > 0 && argv->a_type == A_SYMBOL) ?
-        argv->a_w.w_symbol : gensym("?")), *schedlibdir;
-    char *patchdir;
-    if (sel == gensym("start"))
-    {
-        char pdargstring[MAXPDSTRING];
-        if (x->x_infd)
-            pd_tilde_close(x);
-        pdargstring[0] = 0;
-        argc--; argv++;
-#ifdef PD
-        while (argc--)
-        {
-            atom_string(argv++, pdargstring + strlen(pdargstring), 
-                MAXPDSTRING - strlen(pdargstring));
-            if (strlen(pdargstring) < MAXPDSTRING-1)
-                strcat(pdargstring, " ");
-        }
-        patchdir = canvas_getdir(x->x_canvas)->s_name;
-#endif
-#ifdef MSP
-        while (argc--)
-        {
-                /* because Mac pathnames sometimes have an evil preceeding
-                colon character, we test for and silently eat them */
-            if (argv->a_type == A_SYM)
-                strncat(pdargstring, (*argv->a_w.w_sym->s_name == ':'?
-                    argv->a_w.w_sym->s_name+1 : argv->a_w.w_sym->s_name),
-                    MAXPDSTRING - strlen(pdargstring)-3);
-            else if (argv->a_type == A_LONG)
-                snprintf(pdargstring+strlen(pdargstring),
-                    MAXPDSTRING - strlen(pdargstring)-3, "%ld",
-                        argv->a_w.w_long);
-            else if (argv->a_type == A_FLOAT)
-                snprintf(pdargstring+strlen(pdargstring),
-                    MAXPDSTRING - strlen(pdargstring)-3, "%f",
-                        argv->a_w.w_float);
-            strcat(pdargstring, " ");
-            argv++;
-        }
-        patchdir = ".";
-#endif
-        schedlibdir = x->x_schedlibdir;
-        if (schedlibdir == gensym(".") && x->x_pddir != gensym("."))
-        {
-            char *pds = x->x_pddir->s_name, scheddirstring[MAXPDSTRING];
-            int l = strlen(pds);
-            if (l >= 4 && (!strcmp(pds+l-3, "bin") || !strcmp(pds+l-4, "bin/")))
-                snprintf(scheddirstring, MAXPDSTRING, "%s/../extra/pd~", pds);
-            else snprintf(scheddirstring, MAXPDSTRING, "%s/extra/pd~", pds);
-            schedlibdir = gensym(scheddirstring);
-        }
-        pd_tilde_donew(x, x->x_pddir->s_name, schedlibdir->s_name,
-            patchdir, pdargstring, x->x_ninsig, x->x_noutsig, x->x_fifo,
-                x->x_sr);
-    }
-    else if (sel == gensym("stop"))
-    {
-        if (x->x_infd)
-            pd_tilde_close(x);
-    }
-    else if (sel == gensym("pddir"))
-    {
-        if ((argc > 1) && argv[1].a_type == A_SYMBOL)
-        {
-            t_symbol *sym = argv[1].a_w.w_symbol;
-#ifdef MSP
-            if (sym->s_name[0] == ':')
-                sym = gensym(s->s_name+1);
-#endif
-            x->x_pddir = sym;
-        }
-        else ERROR "pd~ pddir: needs symbol argument");
-    }
-    else ERROR "pd~: unknown control message: %s", sel->s_name);
-}
-
-static void pd_tilde_free(t_pd_tilde *x)
-{
-#ifdef MSP
-    dsp_free((t_pxobject *)x);
-#endif
-    pd_tilde_close(x);
-    clock_free(x->x_clock);
-}
-
-/* -------------------------- Pd glue ------------------------- */
-#ifdef PD
-
-static void pd_tilde_tick(t_pd_tilde *x)
-{
-    int messstart = 0, i, n;
-    t_atom *vec;
-    t_binbuf *b;
-    if (!x->x_msgbuf)
-        return;
-    b = binbuf_new();
-    binbuf_text(b, x->x_msgbuf, x->x_infill);
-    /* binbuf_print(b); */
-    n = binbuf_getnatom(b);
-    vec = binbuf_getvec(b);
-    for (i = 0; i < n; i++)
-    {
-        if (vec[i].a_type == A_SEMI)
-        {
-            if (i > messstart && vec[messstart].a_type == A_SYMBOL)
-                outlet_anything(x->x_outlet1, vec[messstart].a_w.w_symbol,
-                    i-(messstart+1), vec+(messstart+1));
-            else if (i > messstart)
-                outlet_list(x->x_outlet1, 0, i-messstart, vec+messstart);
-            messstart = i+1;
-        }
-    }
-    binbuf_free(b);
-    x->x_infill = 0;
-}
-
-static void pd_tilde_anything(t_pd_tilde *x, t_symbol *s,
-    int argc, t_atom *argv)
-{
-    char msgbuf[MAXPDSTRING];
-    if (!x->x_outfd)
-        return;
-    fprintf(x->x_outfd, "%s ", s->s_name);
-    while (argc--)
-    {
-        atom_string(argv++, msgbuf, MAXPDSTRING);
-        fprintf(x->x_outfd, "%s ", msgbuf);
-    }
-    fprintf(x->x_outfd, ";\n");
-}
-
-static void *pd_tilde_new(t_symbol *s, int argc, t_atom *argv)
-{
-    t_pd_tilde *x = (t_pd_tilde *)pd_new(pd_tilde_class);
-    int ninsig = 2, noutsig = 2, j, fifo = 5;
-    float sr = sys_getsr();
-    t_sample **g;
-    t_symbol *pddir = sys_libdir,
-        *scheddir = gensym(class_gethelpdir(pd_tilde_class));
-    /* fprintf(stderr, "pd %s, sched %s\n", pddir->s_name, scheddir->s_name); */
-    while (argc > 0)
-    {
-        t_symbol *firstarg = atom_getsymbolarg(0, argc, argv);
-        if (!strcmp(firstarg->s_name, "-sr") && argc > 1)
-        {
-            sr = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-ninsig") && argc > 1)
-        {
-            ninsig = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-noutsig") && argc > 1)
-        {
-            noutsig = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-fifo") && argc > 1)
-        {
-            fifo = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-pddir") && argc > 1)
-        {
-            pddir = atom_getsymbolarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-scheddir") && argc > 1)
-        {
-            scheddir = atom_getsymbolarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else break;
-    }
-
-    if (argc)
-    {
-        pd_error(x,
-"usage: pd~ [-sr #] [-ninsig #] [-noutsig #] [-fifo #] [-pddir <>]");
-        post(
-"... [-scheddir <>]");
-    }
-
-    x->x_clock = clock_new(x, (t_method)pd_tilde_tick);
-    x->x_insig = (t_sample **)getbytes(ninsig * sizeof(*x->x_insig));
-    x->x_outsig = (t_sample **)getbytes(noutsig * sizeof(*x->x_outsig));
-    x->x_ninsig = ninsig;
-    x->x_noutsig = noutsig;
-    x->x_fifo = fifo;
-    x->x_sr = sr;
-    x->x_pddir = pddir;
-    x->x_schedlibdir = scheddir;
-    x->x_infd = 0;
-    x->x_outfd = 0;
-    x->x_outfd = 0;
-    x->x_childpid = -1;
-    x->x_msgbuf = 0;
-    x->x_canvas = canvas_getcurrent();
-    for (j = 1, g = x->x_insig; j < ninsig; j++, g++)
-        inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
-    x->x_outlet1 = outlet_new(&x->x_obj, 0);
-    for (j = 0, g = x->x_outsig; j < noutsig; j++, g++)
-        outlet_new(&x->x_obj, &s_signal);
-    signal(SIGPIPE, SIG_IGN);
-
-    return (x);
-}
-
-void pd_tilde_setup(void)
-{
-    pd_tilde_class = class_new(gensym("pd~"), (t_newmethod)pd_tilde_new,
-        (t_method)pd_tilde_free, sizeof(t_pd_tilde), 0, A_GIMME, 0);
-    class_addmethod(pd_tilde_class, nullfn, gensym("signal"), 0);
-    class_addmethod(pd_tilde_class, (t_method)pd_tilde_dsp, gensym("dsp"), 0);
-    class_addmethod(pd_tilde_class, (t_method)pd_tilde_pdtilde, gensym("pd~"), A_GIMME, 0);
-    class_addanything(pd_tilde_class, pd_tilde_anything);
-    post("pd~ version 0.2");
-}
-#endif
-
-/* -------------------------- MSP glue ------------------------- */
-#ifdef MSP
-
-#define LOTS 10000
-
-static void pd_tilde_tick(t_pd_tilde *x)
-{
-    int messstart = 0, i, n = 0;
-    t_atom vec[LOTS];
-    long z1 = 0, z2 = 0;
-    void *b;
-    if (!x->x_msgbuf)
-        return;
-    b = binbuf_new();
-    binbuf_text(b, &x->x_msgbuf, x->x_infill);
-    /* binbuf_print(b); */
-    while (!binbuf_getatom(b, &z1, &z2, vec+n))
-    if (++n >= LOTS)
-        break;
-    for (i = 0; i < n; i++)
-    {
-        if (vec[i].a_type == A_SEMI)
-        {
-            if (i > messstart + 1)
-            {
-                void *whom;
-                if (vec[messstart].a_type == A_SYM)
-                    outlet_anything(x->x_outlet1, vec[messstart].a_w.w_sym,
-                        i-messstart-1, vec+(messstart+1));
-                else if (vec[messstart].a_type == A_FLOAT && i == messstart+1)
-                    outlet_float(x->x_outlet1, vec[messstart].a_w.w_float);
-                else if (vec[messstart].a_type == A_LONG && i == messstart+1)
-                    outlet_int(x->x_outlet1, vec[messstart].a_w.w_long);
-                else outlet_list(x->x_outlet1, gensym("list"),
-                    i-messstart, vec+(messstart));
-            }
-            messstart = i+1;
-        }
-    }
-    binbuf_free(b);
-    x->x_infill = 0;
-}
-
-static void pd_tilde_anything(t_pd_tilde *x, t_symbol *s,
-    long ac, t_atom *av)
-{
-    char msgbuf[MAXPDSTRING], *sp, *ep = msgbuf+MAXPDSTRING;
-    if (!x->x_outfd)
-        return;
-    msgbuf[0] = 0;
-    strncpy(msgbuf, s->s_name, MAXPDSTRING);
-    msgbuf[MAXPDSTRING-1] = 0;
-    sp = msgbuf + strlen(msgbuf);
-    while (ac--)
-    {
-        if (sp < ep-1)
-            sp[0] = ' ', sp[1] = 0, sp++;
-        if (sp < ep - 80)
-        {
-            if (av->a_type == A_SYM && strlen(av->a_w.w_sym->s_name) < ep - sp-20)
-                strcpy(sp, av->a_w.w_sym->s_name);
-            else if (av->a_type == A_LONG)
-                sprintf(sp, "%ld" ,av->a_w.w_long);
-            else if (av->a_type == A_FLOAT)
-                sprintf(sp, "%g" ,av->a_w.w_float);
-        }
-        sp += strlen(sp);
-        av++;
-    }
-    fprintf(x->x_outfd, "%s;\n", msgbuf);
-}
-
-int main()
-{       
-    t_class *c;
-
-    c = class_new("pd_tilde~", (method)pd_tilde_new, (method)pd_tilde_free, sizeof(t_pd_tilde), (method)0L, A_GIMME, 0);
-
-    class_addmethod(c, (method)pd_tilde_dsp, "dsp", A_CANT, 0);
-    class_addmethod(c, (method)pd_tilde_assist, "assist", A_CANT, 0);
-    class_addmethod(c, (method)pd_tilde_pdtilde, "pd~", A_GIMME, 0);
-    class_addmethod(c, (method)pd_tilde_anything, "anything", A_GIMME, 0);
-    class_dspinit(c);
-
-    class_register(CLASS_BOX, c);
-    pd_tilde_class = c;
-    post("pd~ version 0.2");
-    return (0);
-}
-
-static void *pd_tilde_new(t_symbol *s, long ac, t_atom *av)
-{
-    int ninsig = 2, noutsig = 2, fifo = 5, j;
-    float sr = sys_getsr();
-    t_symbol *pddir = gensym("."), *scheddir = gensym(".");
-    t_pd_tilde *x;
-
-    if (x = (t_pd_tilde *)object_alloc(pd_tilde_class))
-    {
-        while (ac > 0 && av[0].a_type == A_SYM)
-        {
-            char *flag = av[0].a_w.w_sym->s_name;
-            if (!strcmp(flag, "-sr") && ac > 1)
-            {
-                sr = (av[1].a_type == A_FLOAT ? av[1].a_w.w_float :
-                    (av[1].a_type == A_LONG ? av[1].a_w.w_long : 0));
-                ac -= 2; av += 2;
-            }
-            else if (!strcmp(flag, "-ninsig") && ac > 1)
-            {
-                ninsig = (av[1].a_type == A_FLOAT ? av[1].a_w.w_float :
-                    (av[1].a_type == A_LONG ? av[1].a_w.w_long : 0));
-                ac -= 2; av += 2;
-            }
-            else if (!strcmp(flag, "-noutsig") && ac > 1)
-            {
-                noutsig = (av[1].a_type == A_FLOAT ? av[1].a_w.w_float :
-                    (av[1].a_type == A_LONG ? av[1].a_w.w_long : 0));
-                ac -= 2; av += 2;
-            }
-            else if (!strcmp(flag, "-fifo") && ac > 1)
-            {
-                fifo = (av[1].a_type == A_FLOAT ? av[1].a_w.w_float :
-                    (av[1].a_type == A_LONG ? av[1].a_w.w_long : 0));
-                ac -= 2; av += 2;
-            }
-            else if (!strcmp(flag, "-pddir") && ac > 1)
-            {
-                pddir = (av[1].a_type == A_SYM ? av[1].a_w.w_sym : gensym("."));
-                ac -= 2; av += 2;
-            }
-            else if (!strcmp(flag, "-scheddir") && ac > 1)
-            {
-                scheddir = (av[1].a_type == A_SYM ? av[1].a_w.w_sym : gensym("."));
-                ac -= 2; av += 2;
-            }
-            else break;
-        }
-        if (ac)
-            post("pd~: warning: ignoring extra arguments");
-        dsp_setup((t_pxobject *)x, ninsig);
-        x->x_outlet1 = outlet_new(&x->x_obj, 0);
-        for (j = 0; j < noutsig; j++)
-            outlet_new((t_pxobject *)x, "signal");
-        x->x_clock = clock_new(x, (method)pd_tilde_tick);
-        x->x_insig = (t_sample **)getbytes(ninsig * sizeof(*x->x_insig));
-        x->x_outsig = (t_sample **)getbytes(noutsig * sizeof(*x->x_outsig));
-        x->x_ninsig = ninsig;
-        x->x_noutsig = noutsig;
-        x->x_fifo = fifo;
-        x->x_sr = sr;
-        x->x_pddir = pddir;
-        x->x_schedlibdir = scheddir;
-        x->x_infd = 0;
-        x->x_outfd = 0;
-        x->x_outfd = 0;
-        x->x_childpid = -1;
-        x->x_msgbuf = 0;
-    }
-    return (x);
-}
-
-void pd_tilde_assist(t_pd_tilde *x, void *b, long m, long a, char *s)
-{
-}
-
-#endif /* MSP */
diff --git a/extra/pd~/z.pd b/extra/pd~/z.pd
deleted file mode 100644
index 373201dae..000000000
--- a/extra/pd~/z.pd
+++ /dev/null
@@ -1,15 +0,0 @@
-#N canvas 686 241 450 300 10;
-#X obj 65 58 r foo;
-#X obj 62 100 print foo;
-#X obj 244 59 adc~;
-#X obj 238 102 env~ 8192;
-#X floatatom 236 140 5 0 0 0 - - -;
-#X obj 155 234 dac~;
-#X obj 155 191 osc~ 440;
-#X obj 287 204 stdout;
-#X msg 307 153 a b c;
-#X connect 0 0 1 0;
-#X connect 2 0 3 0;
-#X connect 3 0 4 0;
-#X connect 6 0 5 0;
-#X connect 8 0 7 0;
diff --git a/extra/pique/pique.c b/extra/pique/pique.c
index 2d14a5533..a53ad765c 100644
--- a/extra/pique/pique.c
+++ b/extra/pique/pique.c
@@ -7,7 +7,8 @@ combustible materiel, or as part of any life support system or weapon. */
 #include "m_pd.h"
 #include <math.h>
 #include <stdio.h>
-#ifdef _MSC_VER /* this is only needed with Microsoft's compiler */
+/* These pragmas are only used for MSVC, not MinGW or Cygwin <hans@at.or.at> */
+#ifdef _MSC_VER
 #pragma warning( disable : 4244 )
 #pragma warning( disable : 4305 )
 #endif
diff --git a/extra/pique/pique.pd_linux b/extra/pique/pique.pd_linux
new file mode 100755
index 0000000000000000000000000000000000000000..ea98c524e70dbbdfef4a28fdbbe825535ad5e0f3
GIT binary patch
literal 9552
zcmeHNe{fXSb$${LB<c;jP&t;#7H^yvM~>x<u+<E*HAV*gfLNgd<U}2WR}xyWa->~(
zcZGp^2<lscH&4qbMed{>YBOU`h8dHLTjMmbDXfqJ2ozgQf9<Q;wHQ0j3dvZwq(!#E
z_WSO8Pg*Ht(wY8|{E@3Ud+s^+oO92;_uO;udr#l2s;$n+$&swGNLnP3YRZ?SQs9cu
z8ZD)gOIjioNh_s0MY|<W+~71|F$sqx+Gkct(u~`H1{iDwEHT@2DRvj&O9qUBCa_&L
z;X1Gd3hD%_ZS&8=tssA`So&Mgp54EUz6C%7Rbi(9coCpx)8kU(NAc<_zxW@2?a<x7
zEV|=`;@-fPPcKIsh9KDhcK}E)1$-KiUH%xvX8^Rf5^y`95b#F;`g^Oweyt+r1caD7
zU`(a(k#mG45XFw)Wq?ls{sgcBz>){JQ`F{uF#V$3hF|tWUucW{JS(|!q@hP|Bagna
zuh-xGt7q0%{o7>XsRrkdW7n2l`Iirum6hiFHJav?y;&6d*s_3rX93N5wu%dt`z!*O
z^lMo(?F}uUznMjIyp35j<qs~PA6r1rWYN^0%A%?N<N`WB%VD-JUqI_w^0ap>i>7?`
zgpqbG&>vqQpS9(<WyD%oB6p+mRp>XB7#xRmE%OlQ`Yig<1vG6W%wSr9=wqDv7?>z4
z5IJjEK~SC&G@{z$+1VNJdqUynVA$i4JnjDWu;gh2Leq}j&8#+ewD0vwp0DikZ1L`F
z4~4zK^&QQjkT)cCwLjJE^@P0P?k;Jk*B{!`DeYjB$M1dGtTnf`c0gy2>hy+vfmW$2
z0A{G&zatQ8lbXYUPR~wnxZMvwcFvNp*AnO;XJ>OT*u2Lhj7wdu^s2RGk3pJkP;cu9
zG{XQSC2ueo2uh(nA({=L<`G^5y2Bmbuu%^^6%5lBeT7iVo-jsa3Xs<p^m+|uM|;Z-
zcPQZgvV>ZvQS*3P(HADE1;Z87CwaX7R;i|T<GS^p2i&XO56;$0W^1cC|MLoWCCgkk
z$j%pwkp<@dm=kiPd$8tQXNE!Ou6CrO#nKj&=V)(7dXS|jK(kQ3#B3vNv@a6vw6R>s
z=Sn_Pz79s2Z^n?5m%x$th>?`i#0dCFVkEaIVkSh$=RsE{#!&K!F%%my^c}>A#{yy`
zszPFP;3S6UE@H%^LX2cpM2xU3CdNogh>`S4iS3fKhS(uV<-|zF6~susmBdKC8;B9~
zwZ!o6@#xRDs*`dWo=V$#1|9cGl6H79lgS+TS$J`J6S(Qia6erP-G*($gPB)3`<WLx
z2P~NvnfZOJj*met^P+<^o5x25&5Z9Ob386+W>p`5#$ORMv#ZZV`lz5;^%ars6SP7a
z-b&;91<fYk8q!^YE+$<;x=GL!^=%+sC+Jerb)+i<O;uk5=@LPglWrpI5_AP=A8Ci6
zD@k{emIO`HzTKp!Zi4Y*E$RKF#{|u;e9w{|6?8r6KGJbPvuodXNxuRbSQM<o*S4m=
zk9yDGx4$4s>ZD`;8%=EL-ma-L=;%N^yi8M>-=ngUJ^_xVwt|YiT7Y`&FulF^-v@5y
zs#kN$rb4dR52>xjbD}~l)2~v(&?%b=zJFG2LVJ!n<k<Ga_Cdx$8ut)%f1BvOKs#Ir
zd4$33nmWZ=JbYVB@S+7uW>g(2*tUI8b1H*<Ea^`WY&`>S-9y)9y;8{s*z|#9&&)(7
zlN^6%?D<`{CwpXsmOh-k{LWZXf8KuZTj(&^W6Ngl`c$%~01Tn>bVIVoIZHg4Oz82%
zM|w{^6$TRniBI&A)aBI2`i0a$BH93MYCv}?x~!-}@?c*qd=IQE6dwLh;Xyo^NG2wh
z#&$`pz+6uqS}APOY1XNy)hqd0r6Nb`T!P-3UXD5F8NB*=4zMVu_G4IF2<=yxd~I@^
zOK|cEc(qW1^0`W-5TlcT3wYiDJ51WfkfiQgSl8I$<8MQ&9$G4+j{G}lQ~g`BhkHS3
zhuId>W^|*6Y-`L+Sdu8_Jbk~=e96@Gz`i<Ev~94hPo1odHY(-m#}IQpgGCrcv_sjT
zbtrYwuu>5{8+}Hpj8!Vd(f^3mD@7at?8(t$CA}9$fU%s#I=s{y6-Rm*tUz}InDu~$
zM6FT;>;N<-hEr$s;lxF~T255Y=qi`x(y%_Pq5H%V4ZS5sV1x#h)D@vY?TfI{kea|!
zj_5UVqGl#_0ao%f_{Ex~p$^rit|ZQ*>3nKn5DOVQiEu?8`#QFdAEWOXd<+?*XR;U5
zq8(R`5uH$u1D%tZN;qyAW6n<xe1bvrizf2WEM}5JKbKZ8YOOcBk>?N=H$QqdoyRFL
zRCp>yBg!!#En<js9lWr8AZ|bOci^j;Jo}-33iK*R(FMd`A+_0AHo7k_+HX)VU+3<u
zlA@(tNjd%Q$70Jp5bIZ-fl{nj*-c$K(677%eGxJUmJ5d9(uYq9!F`Ww?${fb7y;!9
zolI|pFB5r)`$fq_U(XOHX4?~<?Z*Cyy&R`#L}7;Fa({-iVvysH!KK&<Y-xB~#cAX)
zMO>6B>2*fG_hAa@4jc?y4$2ChOP4J0>^{?i;hyHU96ScOg??e_I9D((&<O*5RngWJ
zY5rmu60^~(oTP8F^Ln0C#F*vd%8y7L7j9{rOY{ntend%thY36Zlx~{F$WJOf{{NYk
zAuu5_0`zu7uoG|8GJEtZqil+Zrqr-0qc5>XzK4wvonHMjbv!3JrN`CFdHPj*#1D%}
zU9Xa2)v`LBqn~*l3<+C8L@jcZWRGkGOP$WON4|q5b$U@atWL|}udCCGMcxYksXDzR
zT&Pz*C+Wj#TvpHISW!>?-xYuS2)t!})GLtWWAH7@s|w`&=kn*XY+%{uvydg8bIfNI
zfK@P`#i19@XF1il3tT5A<V=26ztY4~eb|gsw8N>`SHx^R+$+|UsUkICKd=GeoK%ak
zqN!okSneFG<-cM`_CsUX)B05e52Hr?z=lN^o4QxT3Md9S!jU1S$7B1hBL*3K`hb2$
zAH)W_MB<1tMKltNC~L65(G$vhq#G6IDTY9_S4jgQU>R$O!!e+95hV`90yC39<98t0
z80WV>k{D2L%CW<ha66fs8ctLyPIOZaa|lQivD3s)MDy7Njk616KeV4Z7n1MdEViqR
zKN#Ssl9Ph7(co~@CTDH7!aAdwvt=|N<i^o!@?$mm=+i+W4;33LRb+9D*aWB*2uV3<
zPEQqU5_uPs{YoJ!7&x<U40;h^A@P#12!0Xx$%vTOL>z3|H(OJ~utR^L#4f;QpOB_;
zA)Uoe4PP=6wW$O#cAd}~c|x5u3>{Hs40}YDpjyhwH<gXM%hO*>s^#E{dxia5H*gN<
z7bia3r(c+Giv4k6qQJy9+%qmtEWsHzf^+z6j(Sd3e<GJ%+xHFq0_Mi_p9>*qQ5ivl
zh$OByk4pqSS}y`>9O}&+y~<%fFoxqUdC6=rmJ+f@#F}D8gkc_?BNNd+<9=iOPOQkL
zj5yOyiXc3Yu^-Zr77?Kg?$~jq7E^=>tpj4g202gk#tj}<Cxnu=9OB$IkfS(7aS26u
zH=wFH)c13+5&FOtn*dVvrWC4;W);#+ls0m+mSZM$NVLugcUZy^g%4y}E)F;w?n3!|
zErctKjCko{!)6<9L}@$DRP!u**l^Vz`vi{TWRAQJ4Rpp)q7P$u``4mZ4i6k_AgEg2
zYC#zq=0GjKvmC@A#eg4`VTLCR+Oj+r!xJWs!bJ#+Av`MorZEI<xC@*@CXmwA|CPzi
zj-U)9h#oic(Q#unjMak45?D6RE(8KcrOAK)>#LJBD9o5}y8bn~dy7$J4`Tir3Cj#u
z*brlp{{izO23MQ4EXI;>b+mOhUT=4QG#6miIZ&q8>e*cMbc<QPwO0!US<o{#$k{13
z<FEbzGp(3?AtpTTH#|0@P5#UOljEna%`HRkK^*<#-~Vr%8WEAIkn&40j)alFcpJxM
zt(Z9(X-Dkk*}Xo5IfEQ?6Wh@@vp(-k5S75i+OZLqnT8UYc;M+btl;_PA`(IuQbD6q
z0Vu&1Z&aF~vme5!)}_zlfep&^2kc_Q)Ec6GBR@CdB5!)-RMKm?AaK^a?wFZ7B5pm%
zqQ+?jLv+o|n)=7Mxpx67040DX*c1I%Ds}ps$uS%$dsl=Tvoj5@pv&gdrm-Y^*b0~F
z15DM;nQAhvvzIRYr}~>rXJ*E`0LRS9au_3I#skwFFJ};x4Jb7Zlav*gH%>ojQ=07<
z8!0eNC7Qqrnao*DL0^R!uaQRTKllQwvFcx85#K}2jAmq=OQ5W4q_K{wanR?$Dc&*l
zmCzYu#RwpMB`U(VLa3*W2GJwwIOsCt$-y2e$BmgYp`MXpl>HL3M`EhV=H+5sLpF!q
zQShQyqBjz8My0uy;0ybWcv3gJZp4GT8H0=wRYab7`if`kpCZ7zL<CldxGNEd7L&Um
z=Y`=x>=(GslO03lL5_~aeE-&tjVBPe!kv@4tRq6oXpPPrI}F!gW8QGRn-<~m8-meT
zE&Z+Jhj{Cd!dr(R66p9wY+oMG=JTUES*|~$tb&~iJSP{YKldRYCHZ>T{*U#_Dm*Zj
zAWyGB7AyUsO%qS*ZP>6*y+d)n-KZ1-ufh{?A@f`QRU9!NM9=PfGFHwvI#Sf{JXh@!
zwQ?o>Hy<E>S1Wk>Ngoo`B34yVEoOB$s+z_FHd<Z6=fPS$OoiA!g@@>3JVKXf@B`hg
zQHRQn=eW~-nB9MBMIRI2;jq+6Cwwk|tPA6D!0*EJpTV!5!D76f)b=?Cevu2Ntichu
zTt(|7Hx)%~O8Uzd`L$x6qhGK{xC7xrkZ{BS;{|Y}P#tm(YBuvlka!!^*Jr%XN<y+{
z@bv=psODol>WxhJ&e*H0n)h|}s+<|smY|{gy7e9^>wV;YsHVqo&-!z`d*lR)7wUX@
z9rgviA)i6JO5CemZGoVxuF|#38w|Av{H_NcG}<0=wKTW7{9OUOIuE%Z<L~k|e?$6w
z=pk2UdkF8>caljN<GnaLLHUb<AJkml8(C}O({~-1*!-haODj&ju<}buWod;;$4xqZ
z&G+uJuibd>kv37@Uu)vihP5%^{cBNQJ8Iup0Zf|s59JRt@OwW4*sU2lX<^opZNzsL
zVqV{D!2GU;PZHvLnhabB{x5H40+)b!LFYpfUxgOpPK!?(QV@K6(h%Qj&?H^QHxpiW
zj{>mo#kXXBLRkYPyj_;^f%#3b1i<gf`2b|`z%dwyZvpD!77=(7G!DoB%>Ta%zq?yy
zRh}fd0gnJS0iFQ(0s8=l0M7${05}DB6OaO21>6KIgQKeeZongeO#psJs#(AOAy?7k
zE#3Zbx2x1$>Rx?+X}6%t?loxWgnXfJFx=cCx&48#*S*u<?QZFA?`XZhy;TyFuNi63
z-MUA7TogDQG+NA5IFIn4E$Ho_oKflO2up79QPUmv?nYgF+H?m4;_IE;>+`e)n>)Rd
zdq+4B451?fJ-GvhV5GUTeFr)SKoLJ~Va?FQXFn(fIy=4our-Un9Wx#<Wg-r)0}~X0
zRTx(+cLNwxTyw@5VF-1rotVJ?O~4&p#0KM#P<{)!BJkL^u!kSU=on<#2avGk0A}nl
zRw>7LCNPezVpZ3GVZ|ilk&xXl^$Aq~#xU!QV?q<^K%(6mPd#XS4ir4@0|I@q+KCZX
z(sqC)$9+RM3Le`zK1;3*b^3~Cv2VF|Y0oN_-DWT>xqK`Pq0Sm4+9*fp$dYS<BZPcz
zQnPUGSb_k{9>2R2oTA0}vHIO@%5h$vg$#k0W~*?lEc*epN4a_!B3L%Snyr5ub;@z=
z#Q)nMFf1Ej&C2m@tR*L7|I2sXTJF19ayH1>Aa|>N`2m1)%znlH@jz}Ab*?W9b?C?U
z09L>Jwmb&80`ROtIl{{TOOE;SI^-HHAybBOC$i+2YwBFL_K&YY*gyT_|4r0Gj=9__
iw8e57z<wbj3gtd$)`{3=0c~03X_q9Ow+LX$u>3F2){*%D

literal 0
HcmV?d00001

diff --git a/extra/sigmund~/makefile b/extra/sigmund~/makefile
deleted file mode 100644
index 3dc176b3b..000000000
--- a/extra/sigmund~/makefile
+++ /dev/null
@@ -1,4 +0,0 @@
-NAME=sigmund~
-CSYM=sigmund_tilde
-
-include ../makefile
diff --git a/extra/sigmund~/sigmund~-help.pd b/extra/sigmund~/sigmund~-help.pd
deleted file mode 100644
index 5ddbf6d1b..000000000
--- a/extra/sigmund~/sigmund~-help.pd
+++ /dev/null
@@ -1,194 +0,0 @@
-#N canvas 167 -7 580 617 12;
-#X text 42 4 sigmund~ - sinusoidal analysis and pitch tracking;
-#N canvas 432 117 573 597 using-with-tables 0;
-#X obj 29 368 print peak;
-#N canvas 0 0 450 300 (subpatch) 0;
-#X array insignal 1024 float 2;
-#X coords 0 1 1023 -1 200 140 1;
-#X restore 83 426 graph;
-#X obj 314 513 phasor~;
-#X obj 294 429 loadbang;
-#X obj 314 461 440;
-#X floatatom 313 488 5 0 0 0 - - -;
-#X obj 305 544 tabwrite~ insignal;
-#X obj 290 516 bng 15 250 50 0 empty empty empty 17 7 0 10 -262144
--1 -1;
-#X text 114 11 Using sigmund~ on arrays;
-#X text 42 33 If invoked with the "-t" flag (as a creation argument)
-\, sigmund~ analyzes waveforms stored in arrays. Instead of an incoming
-signal \, feed it "list" messages with the following arguments:;
-#X text 37 118 table name (a symbol);
-#X text 38 137 number of points;
-#X obj 29 342 sigmund~ -t -npeak 10 -maxfreq 5000 peaks;
-#X msg 29 316 list insignal 1024 0 44100 0;
-#X text 37 158 index of first point;
-#X text 39 179 sample rate;
-#X text 38 200 debug flag (print debugging info if nonzero);
-#X text 23 232 In this mode \, only the "env" \, "pitch" \, and "peaks"
-outputs are meaningful.;
-#X text 31 294 click here to test:;
-#X connect 2 0 6 0;
-#X connect 3 0 4 0;
-#X connect 4 0 5 0;
-#X connect 5 0 2 0;
-#X connect 5 0 7 0;
-#X connect 7 0 6 0;
-#X connect 12 0 0 0;
-#X connect 13 0 12 0;
-#X restore 330 553 pd using-with-tables;
-#X obj 40 512 phasor~;
-#X obj 40 425 loadbang;
-#X floatatom 40 471 5 0 120 0 - - -;
-#X floatatom 39 561 5 0 0 0 - - -;
-#X floatatom 245 563 5 0 0 0 - - -;
-#X obj 40 490 mtof;
-#X obj 40 448 69;
-#X text 38 579 pitch;
-#X text 222 582 envelope;
-#X text 13 28 Sigmund~ analyzes an incoming sound into sinusoidal components
-\, which may be reported individually or combined to form a pitch estimate.
-Possible outputs are specified as creation arguments:;
-#X text 56 95 pitch - output pitch continuously;
-#N canvas 518 74 588 728 setting-parameters 0;
-#X msg 182 66 print;
-#X floatatom 192 92 5 0 0 0 - - -;
-#X msg 192 113 minpower \$1;
-#X obj 182 139 sigmund~ -minpower 40;
-#X text 39 14 You can set parameters either by creation arguments \,
-or else using messages. The "print" message gives you the current values
-of all the parameters:;
-#X text 28 169 npts: number of points used in an analysis. Must be
-a power of two \, at least 128 The minimum frequency that can be tracked
-is about 2(sample_rate)/npts.;
-#X text 26 219 hop: number of points between analyses. Must be a power
-of two \, at least the DSP vector size (usually 64). This regulates
-the number of analyses done per unit of time.;
-#X text 28 271 npeak: maximum number of sinusoidal peaks to look for.
-The computation time is quadratic in the number of peaks actually found
-(this number only sets an upper limit). Use it to balance CPU time
-with quality of results.;
-#X text 30 336 maxfreq: maximum frequency of sinusoidal peaks to look
-for. This can be useful in situations where background noise creates
-high-frequency \, spurious peaks..;
-#X text 37 388 vibrato: maximum deviation from "pitch" to accept as
-normal vibrato (affects "notes" output only). If the value is too small.
-vibratos will appear as trills. If too large \, very small melodic
-intervals may not be reported as new notes.;
-#X text 33 457 stabletime: time period to wait before reporting a note
-(affects "notes" output only). The "pitch" must be present and must
-not vary more than "vibrato" for this entire period to report a note.
-If too large \, the "notes" will be unnecessarily delayed. If too small
-\, spurious notes get output.;
-#X text 31 551 minpower: minimum measured RMS level to report a pitch
-(affects "pitch" and "notes" output only). Signals quieter than this
-will be assumed to be crosstalk and ignored.;
-#X text 32 602 growth: minimum measured RMS growth to report a new
-note (affects "notes" output only). The RMS level must rise by this
-many dB (within a time period given by "stabletime") to report a repetition
-of a note at or near the previously output pitch.;
-#X connect 0 0 3 0;
-#X connect 1 0 2 0;
-#X connect 2 0 3 0;
-#X restore 330 531 pd setting-parameters;
-#N canvas 67 29 641 815 sinusoid-tracking 0;
-#X obj 124 267 sigmund~ -npeak 10 peaks;
-#X obj 124 214 phasor~;
-#X obj 124 144 loadbang;
-#X floatatom 124 190 5 0 120 0 - - -;
-#X obj 124 295 route 0 1 2 3 4 5 6 7 8 9;
-#X obj 82 339 unpack 0 0 0 0;
-#X floatatom 82 461 5 0 0 0 - - -;
-#X floatatom 122 431 5 0 0 0 - - -;
-#X floatatom 162 406 5 0 0 0 - - -;
-#X obj 124 167 440;
-#X floatatom 203 380 5 0 0 0 - - -;
-#X obj 322 349 unpack 0 0 0 0;
-#X floatatom 322 471 5 0 0 0 - - -;
-#X floatatom 362 441 5 0 0 0 - - -;
-#X floatatom 402 416 5 0 0 0 - - -;
-#X floatatom 443 390 5 0 0 0 - - -;
-#X text 385 475 frequency (Hz.);
-#X text 419 442 peak amplitude (linear);
-#X text 464 416 cosine component;
-#X text 499 390 sine component;
-#X text 79 505 loudest partial;
-#X text 332 508 quietest partial;
-#X text 36 4 You can ask for sinusoidal peaks in decreasing order of
-amplitude or arranged into maximally continuous tracks for resynthesis.
-(Or you can ask for both.) If you ask for peaks \, out come lists of
-five numbers \, one for each sinusoid at each analysis period. The
-first is the index number of the sinusoid (so you can use "route" to
-claw them apart). The other four are as shown:;
-#X obj 204 611 osc~ 440;
-#X obj 204 635 *~;
-#X obj 205 689 unpack 0 0 0 0;
-#X floatatom 205 782 5 0 0 0 - - -;
-#X floatatom 245 760 5 0 0 0 - - -;
-#X floatatom 285 737 5 0 0 0 - - -;
-#X floatatom 326 713 5 0 0 0 - - -;
-#X obj 246 638 tgl 15 0 empty empty empty 17 7 0 10 -262144 -1 -1 0
-1;
-#X text 43 535 If you ask for "tracks" \, the output is four numbers:
-index \, frequency \, and amplitude as before \, and finally a flag
-which is one for a new track \, zero for a continuation \, minus one
-for an empty track.;
-#X obj 205 662 sigmund~ -npts 16384 -hop 8192 -npeak 1 tracks;
-#X connect 0 0 4 0;
-#X connect 1 0 0 0;
-#X connect 2 0 9 0;
-#X connect 3 0 1 0;
-#X connect 4 0 5 0;
-#X connect 4 9 11 0;
-#X connect 5 0 6 0;
-#X connect 5 1 7 0;
-#X connect 5 2 8 0;
-#X connect 5 3 10 0;
-#X connect 9 0 3 0;
-#X connect 11 0 12 0;
-#X connect 11 1 13 0;
-#X connect 11 2 14 0;
-#X connect 11 3 15 0;
-#X connect 23 0 24 0;
-#X connect 24 0 32 0;
-#X connect 25 0 26 0;
-#X connect 25 1 27 0;
-#X connect 25 2 28 0;
-#X connect 25 3 29 0;
-#X connect 30 0 24 1;
-#X connect 32 0 25 0;
-#X restore 330 508 pd sinusoid-tracking;
-#X text 52 165 tracks - output sinusoidal peaks organized into tracks
-;
-#X text 56 111 notes - output pitch at the beginning of notes;
-#X text 339 485 more details:;
-#X text 10 184 Parameters you may set (in creation arguments or messages):
-;
-#X text 60 207 npts - number of points in each analysis window (1024)
-;
-#X text 60 225 hop - number of points between each analysis (512);
-#X text 60 242 npeak - number of sinusoidal peaks (20);
-#X text 61 279 vibrato - depth of vibrato to expect in 1/2-tones (1)
-;
-#X text 60 298 stabletime - time (msec) to wait to report notes (50)
-;
-#X obj 39 535 sigmund~ -hop 4096 pitch env;
-#X text 62 316 minpower - minimum power (dB) to report a pitch (50)
-;
-#X text 62 335 growth - growth (dB) to report a new note (7);
-#X text 54 147 peaks - output all sinusoidal peaks in order of amplitude
-;
-#X text 11 356 The npts and hop parameters are in samples \, and are
-powers of two. The example below specifies a huge hop of 4096 (to slow
-the output down) and to output "pitch" and "env". (Those are the default
-outputs.);
-#X text 61 260 maxfreq - maximum sinusoid frequency in Hz. (1000000)
-;
-#X text 55 128 env - output amplitude continuously;
-#X text 380 596 updated for Pd v0.41;
-#X connect 2 0 24 0;
-#X connect 3 0 8 0;
-#X connect 4 0 7 0;
-#X connect 7 0 2 0;
-#X connect 8 0 4 0;
-#X connect 24 0 5 0;
-#X connect 24 1 6 0;
diff --git a/extra/sigmund~/sigmund~.c b/extra/sigmund~/sigmund~.c
deleted file mode 100644
index c63967660..000000000
--- a/extra/sigmund~/sigmund~.c
+++ /dev/null
@@ -1,1651 +0,0 @@
-/* Copyright (c) 2005 Miller Puckette.  BSD licensed.  No warranties. */
-
-/*
-    fix parameter settings
-    not to report pitch if evidence too scanty?
-    note-on detection triggered by falling envelope (a posteriori)
-    reentrancy bug setting loud flag (other parameters too?)
-    tweaked freqs still not stable enough
-    implement block ("-b") mode
-*/
-
-/* From here to the first "#ifdef PD" or "#ifdef Max" should be extractable
-and usable in other contexts.  The one external requirement is a real
-single-precision FFT, invoked as in the Mayer one: */
-
-#ifdef _MSC_VER /* this is only needed with Microsoft's compiler */
-__declspec(dllimport) extern
-#endif
-void mayer_realfft(int npoints, float *buf);
-
-/* this routine is passed a buffer of npoints values, and returns the
-N/2+1 real parts of the DFT (frequency zero through Nyquist), followed
-by the N/2-1 imaginary points, in order of decreasing frequency.  Pd 0.41,
-for example, defines this in the file d_fft_mayer.c or d_fft_fftsg.c. */
-
-#include <math.h>
-#include <stdio.h>
-#include <string.h>
-#ifdef _WIN32
-#include <malloc.h>
-#else
-#include <alloca.h>
-#endif
-#include <stdlib.h>
-#ifdef _MSC_VER /* this is only needed with Microsoft's compiler */
-#pragma warning( disable : 4244 )
-#pragma warning( disable : 4305 )
-#endif
-
-typedef struct peak
-{
-    float p_freq;
-    float p_amp;
-    float p_ampreal;
-    float p_ampimag;
-    float p_pit;
-    float p_db;
-    float p_salience;
-    float p_tmp;
-} t_peak;
-
-/********************** service routines **************************/
-
-/* these three are dapted from elsewhere in Pd but included here for
-cmolpeteness */
-static int sigmund_ilog2(int n)
-{
-    int ret = -1;
-    while (n)
-    {
-        n >>= 1;
-        ret++;
-    }
-    return (ret);
-}
-
-static float sigmund_ftom(float f)
-{
-    return (f > 0 ? 17.3123405046 * log(.12231220585 * f) : -1500);
-}
-
-#define LOGTEN 2.302585092994
-static float sigmund_powtodb(float f)
-{
-    if (f <= 0) return (0);
-    else
-    {
-        float val = 100 + 10./LOGTEN * log(f);
-        return (val < 0 ? 0 : val);
-    }
-}
-
-/* parameters for von Hann window (change these to get Hamming if desired) */
-#define W_ALPHA 0.5
-#define W_BETA 0.5
-#define NEGBINS 4   /* number of bins of negative frequency we'll need */
-
-#define PI 3.14159265
-#define LOG2  0.69314718
-#define LOG10 2.30258509
-
-static float sinx(float theta, float sintheta)
-{
-    if (theta > -0.003 && theta < 0.003)
-        return (1);
-    else return (sintheta/theta);
-}
-
-static float window_hann_mag(float pidetune, float sinpidetune)
-{
-    return (W_ALPHA * sinx(pidetune, sinpidetune)
-        - 0.5 * W_BETA *
-            (sinx(pidetune+PI, sinpidetune) + sinx(pidetune-PI, sinpidetune)));
-}
-
-static float window_mag(float pidetune, float cospidetune)
-{
-    return (sinx(pidetune + (PI/2), cospidetune)
-        + sinx(pidetune - (PI/2), -cospidetune));
-}
-
-/*********** Routines to analyze a window into sinusoidal peaks *************/
-
-static int sigmund_cmp_freq(const void *p1, const void *p2)
-{
-    if ((*(t_peak **)p1)->p_freq > (*(t_peak **)p2)->p_freq)
-        return (1);
-    else if ((*(t_peak **)p1)->p_freq < (*(t_peak **)p2)->p_freq)
-        return (-1);
-    else return (0);
-}
-
-static void sigmund_tweak(int npts, float *ftreal, float *ftimag,
-    int npeak, t_peak *peaks, float fperbin, int loud)
-{
-    t_peak **peakptrs = (t_peak **)alloca(sizeof (*peakptrs) * (npeak+1));
-    t_peak negpeak;
-    int peaki, j, k;
-    float ampreal[3], ampimag[3];
-    float binperf = 1./fperbin;
-    float phaseperbin = (npts-0.5)/npts, oneovern = 1./npts;
-    if (npeak < 1)
-        return;
-    for (peaki = 0; peaki < npeak; peaki++)
-        peakptrs[peaki+1] = &peaks[peaki];
-    qsort(peakptrs+1, npeak, sizeof (*peakptrs), sigmund_cmp_freq);
-    peakptrs[0] = &negpeak;
-    negpeak.p_ampreal = peakptrs[1]->p_ampreal;
-    negpeak.p_ampimag = -peakptrs[1]->p_ampimag;
-    negpeak.p_freq = -peakptrs[1]->p_freq;
-    for (peaki = 1; peaki <= npeak; peaki++)
-    {
-        int cbin = peakptrs[peaki]->p_freq*binperf + 0.5;
-        int nsub = (peaki == npeak ? 1:2);
-        float windreal, windimag, windpower, detune, pidetune, sinpidetune,
-            cospidetune, ampcorrect, ampout, ampoutreal, ampoutimag, freqout;
-        /* post("3 nsub %d amp %f freq %f", nsub,
-            peakptrs[peaki]->p_amp, peakptrs[peaki]->p_freq); */
-        if (cbin < 0 || cbin > 2*npts - 3)
-            continue;
-        for (j = 0; j < 3; j++)
-            ampreal[j] = ftreal[cbin+2*j-2], ampimag[j] = ftimag[cbin+2*j-2];
-        /* post("a %f %f", ampreal[1], ampimag[1]); */
-        for (j = 0; j < nsub; j++)
-        {
-            t_peak *neighbor = peakptrs[(peaki-1) + 2*j];
-            float neighborreal = npts * neighbor->p_ampreal;
-            float neighborimag = npts * neighbor->p_ampimag;
-            for (k = 0; k < 3; k++)
-            {
-                float freqdiff = (0.5*PI) * ((cbin + 2*k-2)
-                    -binperf * neighbor->p_freq);
-                float sx = sinx(freqdiff, sin(freqdiff));
-                float phasere = cos(freqdiff * phaseperbin);
-                float phaseim = sin(freqdiff * phaseperbin);
-                ampreal[k] -=
-                    sx * (phasere * neighborreal - phaseim * neighborimag);
-                ampimag[k] -=
-                    sx * (phaseim * neighborreal + phasere * neighborimag);
-            }       
-            /* post("b %f %f", ampreal[1], ampimag[1]); */
-        }
-
-        windreal = W_ALPHA * ampreal[1] -
-            (0.5 * W_BETA) * (ampreal[0] + ampreal[2]);
-        windimag = W_ALPHA * ampimag[1] -
-            (0.5 * W_BETA) * (ampimag[0] + ampimag[2]);
-        windpower = windreal * windreal + windimag * windimag;
-        detune = (
-            W_BETA*(ampreal[0] - ampreal[2]) * 
-                (2.0*W_ALPHA * ampreal[1] - W_BETA * (ampreal[0] + ampreal[2]))
-                    +
-            W_BETA*(ampimag[0] - ampimag[2]) *
-                (2.0*W_ALPHA * ampimag[1] - W_BETA * (ampimag[0] + ampimag[2]))
-                        ) / (4.0 * windpower);
-        if (detune > 0.5)
-            detune = 0.5;
-        else if (detune < -0.5)
-            detune = -0.5;
-        /* if (loud > 0)
-            post("tweak: windpower %f, bin %d, detune %f",
-                windpower, cbin, detune); */
-        pidetune = PI * detune;
-        sinpidetune = sin(pidetune);
-        cospidetune = cos(pidetune);
-
-        ampcorrect = 1.0 / window_hann_mag(pidetune, sinpidetune);
-
-        ampout = oneovern * ampcorrect *sqrt(windpower);
-        ampoutreal = oneovern * ampcorrect *
-            (windreal * cospidetune - windimag * sinpidetune);
-        ampoutimag = oneovern * ampcorrect *
-            (windreal * sinpidetune + windimag * cospidetune);
-        freqout = (cbin + 2*detune) * fperbin;
-        /* if (loud > 1)
-            post("amp %f, freq %f", ampout, freqout); */
-        
-        peakptrs[peaki]->p_freq = freqout;
-        peakptrs[peaki]->p_amp = ampout;
-        peakptrs[peaki]->p_ampreal = ampoutreal;
-        peakptrs[peaki]->p_ampimag = ampoutimag;
-    }
-}
-
-static void sigmund_remask(int maxbin, int bestindex, float powmask, 
-    float maxpower, float *maskbuf)
-{
-    int bin;
-    int bin1 = (bestindex > 52 ? bestindex-50:2);
-    int bin2 = (maxbin < bestindex + 50 ? bestindex + 50 : maxbin);
-    for (bin = bin1; bin < bin2; bin++)
-    {
-        float bindiff = bin - bestindex;
-        float mymask;
-        mymask = powmask/ (1. + bindiff * bindiff * bindiff * bindiff);
-        if (bindiff < 2 && bindiff > -2)
-            mymask = 2*maxpower;
-        if (mymask > maskbuf[bin])
-            maskbuf[bin] = mymask;
-    } 
-}
-
-static void sigmund_getrawpeaks(int npts, float *insamps,
-    int npeak, t_peak *peakv, int *nfound, float *power, float srate, int loud,
-    float param1, float param2, float param3, float hifreq)
-{
-    float oneovern = 1.0/ (float)npts;
-    float fperbin = 0.5 * srate * oneovern;
-    int npts2 = 2*npts, i, bin;
-    int peakcount = 0;
-    float *fp1, *fp2;
-    float *rawreal, *rawimag, *maskbuf, *powbuf;
-    float *bigbuf = alloca(sizeof (float ) * (2*NEGBINS + 6*npts));
-    int maxbin = hifreq/fperbin;
-    int tweak = (param3 == 0);
-    if (maxbin > npts - NEGBINS)
-        maxbin = npts - NEGBINS;
-    /* if (loud) post("tweak %d", tweak); */
-    maskbuf = bigbuf + npts2;
-    powbuf = maskbuf + npts;
-    rawreal = powbuf + npts+NEGBINS;
-    rawimag = rawreal+npts+NEGBINS;
-    for (i = 0; i < npts; i++)
-        maskbuf[i] = 0;
-
-    for (i = 0; i < npts; i++)
-        bigbuf[i] = insamps[i];
-    for (i = npts; i < 2*npts; i++)
-        bigbuf[i] = 0;
-    mayer_realfft(npts2, bigbuf);
-    for (i = 0; i < npts; i++)
-        rawreal[i] = bigbuf[i];
-    for (i = 1; i < npts-1; i++)
-        rawimag[i] = bigbuf[npts2-i];
-    rawreal[-1] = rawreal[1];
-    rawreal[-2] = rawreal[2];
-    rawreal[-3] = rawreal[3];
-    rawreal[-4] = rawreal[4];
-    rawimag[0] = rawimag[npts-1] = 0;
-    rawimag[-1] = -rawimag[1];
-    rawimag[-2] = -rawimag[2];
-    rawimag[-3] = -rawimag[3];
-    rawimag[-4] = -rawimag[4];
-#if 1
-    for (i = 0, fp1 = rawreal, fp2 = rawimag; i < npts-1; i++, fp1++, fp2++)
-    {
-        float x1 = fp1[1] - fp1[-1], x2 = fp2[1] - fp2[-1]; 
-        powbuf[i] = x1*x1+x2*x2;
-    }
-    powbuf[npts-1] = 0;
-#endif
-    for (peakcount = 0; peakcount < npeak; peakcount++)
-    {
-        float pow1, maxpower = 0, totalpower = 0, windreal, windimag, windpower,
-            detune, pidetune, sinpidetune, cospidetune, ampcorrect, ampout,
-            ampoutreal, ampoutimag, freqout, powmask;
-        int bestindex = -1;
-
-        for (bin = 2, fp1 = rawreal+2, fp2 = rawimag+2;
-            bin < maxbin; bin++, fp1++, fp2++)
-        {
-            pow1 = powbuf[bin];
-            if (pow1 > maxpower && pow1 > maskbuf[bin])
-            {
-                float thresh = param2 * (powbuf[bin-2]+powbuf[bin+2]);
-                if (pow1 > thresh)
-                    maxpower = pow1, bestindex = bin;
-            }
-            totalpower += pow1;
-        }
-
-        if (totalpower <= 0 || maxpower < 1e-10*totalpower || bestindex < 0)
-            break;
-        fp1 = rawreal+bestindex;
-        fp2 = rawimag+bestindex;
-        *power = 0.5 * totalpower *oneovern * oneovern;
-        powmask = maxpower * exp(-param1 * log(10.) / 10.);
-        /* if (loud > 2)
-            post("maxpower %f, powmask %f, param1 %f",
-                maxpower, powmask, param1); */
-        sigmund_remask(maxbin, bestindex, powmask, maxpower, maskbuf);
-        
-        /* if (loud > 1)
-            post("best index %d, total power %f", bestindex, totalpower); */
-
-        windreal = fp1[1] - fp1[-1];
-        windimag = fp2[1] - fp2[-1];
-        windpower = windreal * windreal + windimag * windimag;
-        detune = ((fp1[1] * fp1[1] - fp1[-1]*fp1[-1]) 
-            + (fp2[1] * fp2[1] - fp2[-1]*fp2[-1])) / (2 * windpower);
-
-        if (detune > 0.5)
-            detune = 0.5;
-        else if (detune < -0.5)
-            detune = -0.5;
-        /* if (loud > 1)
-            post("windpower %f, index %d, detune %f",
-                windpower, bestindex, detune); */
-        pidetune = PI * detune;
-        sinpidetune = sin(pidetune);
-        cospidetune = cos(pidetune);
-        ampcorrect = 1.0 / window_mag(pidetune, cospidetune);
-
-        ampout = ampcorrect *sqrt(windpower);
-        ampoutreal = ampcorrect *
-            (windreal * cospidetune - windimag * sinpidetune);
-        ampoutimag = ampcorrect *
-            (windreal * sinpidetune + windimag * cospidetune);
-
-            /* the frequency is the sum of the bin frequency and detuning */
-
-        peakv[peakcount].p_freq = (freqout = (bestindex + 2*detune)) * fperbin;
-        peakv[peakcount].p_amp = oneovern * ampout;
-        peakv[peakcount].p_ampreal = oneovern * ampoutreal;
-        peakv[peakcount].p_ampimag = oneovern * ampoutimag;
-    }
-    if (tweak)
-    {
-        sigmund_tweak(npts, rawreal, rawimag, peakcount, peakv, fperbin, loud);
-        sigmund_tweak(npts, rawreal, rawimag, peakcount, peakv, fperbin, loud);
-    }
-    for (i = 0; i < peakcount; i++)
-    {
-        peakv[i].p_pit = sigmund_ftom(peakv[i].p_freq);
-        peakv[i].p_db = sigmund_powtodb(peakv[i].p_amp);
-    }
-    *nfound = peakcount;
-}
-
-/*************** Routines for finding fundamental pitch *************/
-
-#define PITCHNPEAK 12
-#define PITCHUNCERTAINTY 0.3
-#define HALFTONEINC 0.059
-#define SUBHARMONICS 16
-#define DBPERHALFTONE 0.0
-
-static void sigmund_getpitch(int npeak, t_peak *peakv, float *freqp,
-    float npts, float srate, int loud)
-{
-    float fperbin = 0.5 * srate / npts;
-    int npit = 48 * sigmund_ilog2(npts), i, j, k, nsalient;
-    float bestbin, bestweight, sumamp, sumweight, sumfreq, freq;
-    float *weights =  (float *)alloca(sizeof(float) * npit);
-    t_peak *bigpeaks[PITCHNPEAK];
-    if (npeak < 1)
-    {
-        freq = 0;
-        goto done;
-    }
-    for (i = 0; i < npit; i++)
-        weights[i] = 0;
-    for (i = 0; i < npeak; i++)
-    {
-        peakv[i].p_tmp = 0;
-        peakv[i].p_salience = peakv[i].p_db - DBPERHALFTONE * peakv[i].p_pit;
-    }
-    for (nsalient = 0; nsalient < PITCHNPEAK; nsalient++)
-    {
-        t_peak *bestpeak = 0;
-        float bestsalience = -1e20;
-        for (j = 0; j < npeak; j++)
-            if (peakv[j].p_tmp == 0 && peakv[j].p_salience > bestsalience)
-        {
-            bestsalience = peakv[j].p_salience;
-            bestpeak = &peakv[j];
-        }
-        if (!bestpeak)
-            break;
-        bigpeaks[nsalient] = bestpeak;
-        bestpeak->p_tmp = 1;
-        /* post("peak f=%f a=%f", bestpeak->p_freq, bestpeak->p_amp); */
-    }
-    sumweight = 0;
-    for (i = 0; i < nsalient; i++)
-    {
-        t_peak *thispeak = bigpeaks[i];
-        float weightindex = (48./LOG2) *
-            log(thispeak->p_freq/(2.*fperbin));
-        float loudness = sqrt(thispeak->p_amp);
-        /* post("index %f, uncertainty %f", weightindex, pitchuncertainty); */
-        for (j = 0; j < SUBHARMONICS; j++)
-        {
-            float subindex = weightindex -
-                (48./LOG2) * log(j + 1.);
-            int loindex = subindex - 0.5;
-            int hiindex = loindex+2;
-            if (hiindex < 0)
-                break;
-            if (hiindex >= npit)
-                continue;
-            if (loindex < 0)
-                loindex = 0;
-            for (k = loindex; k <= hiindex; k++)
-                weights[k] += loudness * 6. / (6. + j);
-        }
-        sumweight += loudness;
-    }
-    bestbin = -1;
-    bestweight = -1e20;
-    for (i = 0; i < npit; i++)
-        if (weights[i] > bestweight)
-            bestweight = weights[i], bestbin = i;
-    if (bestweight < sumweight * 0.4)
-        bestbin = -1;
-    
-    if (bestbin < 0)
-    {
-        freq = 0;
-        goto done;
-    }
-    if (bestbin > 0 && bestbin < npit-1)
-    {
-        int ibest = bestbin;
-        bestbin += (weights[ibest+1] - weights[ibest-1]) /
-            (weights[ibest+1] +  weights[ibest] + weights[ibest-1]);
-    }
-    freq = 2*fperbin * exp((LOG2/48.)*bestbin);
-    for (sumamp = sumweight = sumfreq = 0, i = 0; i < nsalient; i++)
-    {
-        t_peak *thispeak = bigpeaks[i];
-        float thisloudness = thispeak->p_amp;
-        float thisfreq = thispeak->p_freq;
-        float harmonic = thisfreq/freq;
-        float intpart = (int)(0.5 + harmonic);
-        float inharm = harmonic - intpart;
-#if 0
-        if (loud)
-            post("freq %f intpart %f inharm %f", freq, intpart, inharm);
-#endif
-        if (intpart >= 1 && intpart <= 16 &&
-            inharm < 0.015 * intpart && inharm > - (0.015 * intpart))
-        {
-            float weight = thisloudness * intpart;
-            sumweight += weight;
-            sumfreq += weight*thisfreq/intpart;
-#if 0
-            if (loud)
-                post("weight %f freq %f", weight, thisfreq);
-#endif
-        }
-    }
-    if (sumweight > 0)
-        freq = sumfreq / sumweight;
-done:
-    if (!(freq >= 0 || freq <= 0))
-    {
-        /* post("freq nan cancelled"); */
-        freq = 0;
-    }
-    *freqp = freq;
-}
-
-/*************** gather peak lists into sinusoidal tracks *************/
-
-static void sigmund_peaktrack(int ninpeak, t_peak *inpeakv, 
-    int noutpeak, t_peak *outpeakv, int loud)
-{
-    int incnt, outcnt;
-    for (outcnt = 0; outcnt < noutpeak; outcnt++)
-        outpeakv[outcnt].p_tmp = -1;
-        
-        /* first pass. Match each "in" peak with the closest previous
-        "out" peak, but no two to the same one. */
-    for (incnt = 0; incnt < ninpeak; incnt++)
-    {
-        float besterror = 1e20;
-        int bestcnt = -1;
-        inpeakv[incnt].p_tmp = -1;
-        for (outcnt = 0; outcnt < noutpeak; outcnt++)
-        {
-            float thiserror =
-                inpeakv[incnt].p_freq - outpeakv[outcnt].p_freq;
-            if (thiserror < 0)
-                thiserror = -thiserror;
-            if (thiserror < besterror)
-            {
-                besterror = thiserror;
-                bestcnt = outcnt;
-            }
-        }
-        if (outpeakv[bestcnt].p_tmp < 0)
-        {
-            outpeakv[bestcnt] = inpeakv[incnt];
-            inpeakv[incnt].p_tmp = 0;
-            outpeakv[bestcnt].p_tmp = 0;
-        }
-    }
-        /* second pass.  Unmatched "in" peaks assigned to free "out"
-        peaks */
-    for (incnt = 0; incnt < ninpeak; incnt++)
-        if (inpeakv[incnt].p_tmp < 0)
-    {
-        for (outcnt = 0; outcnt < noutpeak; outcnt++)
-            if (outpeakv[outcnt].p_tmp < 0)
-        {
-            outpeakv[outcnt] = inpeakv[incnt];
-            inpeakv[incnt].p_tmp = 0;
-            outpeakv[outcnt].p_tmp = 1;
-            break;
-        }
-    }
-    for (outcnt = 0; outcnt < noutpeak; outcnt++)
-        if (outpeakv[outcnt].p_tmp == -1)
-            outpeakv[outcnt].p_amp = 0;
-}
-
-/**************** parse continuous pitch into note starts ***************/
-
-#define NHISTPOINT 100
-
-typedef struct _histpoint
-{
-    float h_freq;
-    float h_power;
-} t_histpoint;
-
-typedef struct _notefinder
-{
-    float n_age;
-    float n_hifreq;
-    float n_lofreq;
-    int n_peaked;
-    t_histpoint n_hist[NHISTPOINT];
-    int n_histphase;
-} t_notefinder;
-
-
-static void notefinder_init(t_notefinder *x)
-{
-    int i;
-    x->n_peaked = x->n_age = 0;
-    x->n_hifreq = x->n_lofreq = 0;
-    x->n_histphase = 0;
-    for (i = 0; i < NHISTPOINT; i++)
-        x->n_hist[i].h_freq =x->n_hist[i].h_power = 0;
-}
-
-static void notefinder_doit(t_notefinder *x, float freq, float power,
-    float *note, float vibrato, int stableperiod, float powerthresh,
-        float growththresh, int loud)
-{
-        /* calculate frequency ratio between allowable vibrato extremes
-        (equal to twice the vibrato deviation from center) */
-    float vibmultiple = exp((2*LOG2/12) * vibrato);
-    int oldhistphase, i, k;
-    if (stableperiod > NHISTPOINT - 1)
-        stableperiod = NHISTPOINT - 1;
-    else if (stableperiod < 1)
-        stableperiod = 1;
-    if (++x->n_histphase == NHISTPOINT)
-        x->n_histphase = 0;
-    x->n_hist[x->n_histphase].h_freq = freq;
-    x->n_hist[x->n_histphase].h_power = power;
-    x->n_age++;
-    *note = 0;
-#if 0
-    if (loud)
-    {
-        post("stable %d, age %d, vibmultiple %f, powerthresh %f, hifreq %f",
-            stableperiod, (int)x->n_age ,vibmultiple, powerthresh, x->n_hifreq);
-        post("histfreq %f %f %f %f",
-            x->n_hist[x->n_histphase].h_freq,
-            x->n_hist[(x->n_histphase+NHISTPOINT-1)%NHISTPOINT].h_freq,
-            x->n_hist[(x->n_histphase+NHISTPOINT-2)%NHISTPOINT].h_freq,
-            x->n_hist[(x->n_histphase+NHISTPOINT-3)%NHISTPOINT].h_freq);
-        post("power %f %f %f %f",
-            x->n_hist[x->n_histphase].h_power,
-            x->n_hist[(x->n_histphase+NHISTPOINT-1)%NHISTPOINT].h_power,
-            x->n_hist[(x->n_histphase+NHISTPOINT-2)%NHISTPOINT].h_power,
-            x->n_hist[(x->n_histphase+NHISTPOINT-3)%NHISTPOINT].h_power);
-        for (i = 0, k = x->n_histphase; i < stableperiod; i++)
-        {
-            post("pit %5.1f  pow %f", sigmund_ftom(x->n_hist[k].h_freq),
-                x->n_hist[k].h_power);
-            if (--k < 0)
-                k = NHISTPOINT - 1;
-        }
-    }
-#endif
-       /* look for shorter notes than "stableperiod" in length.
-       The amplitude must rise and then fall while the pitch holds
-       steady. */
-    if (x->n_hifreq <= 0 && x->n_age > stableperiod)
-    {
-        float maxpow = 0, freqatmaxpow = 0,
-            localhifreq = -1e20, locallofreq = 1e20;
-        int startphase = x->n_histphase - stableperiod + 1;
-        if (startphase < 0)
-            startphase += NHISTPOINT;
-        for (i = 0, k = startphase; i < stableperiod; i++)
-        {
-            if (x->n_hist[k].h_freq <= 0)
-                break;
-            if (x->n_hist[k].h_power > maxpow)
-                maxpow = x->n_hist[k].h_power,
-                    freqatmaxpow = x->n_hist[k].h_freq;
-            if (x->n_hist[k].h_freq > localhifreq)
-                localhifreq = x->n_hist[k].h_freq;
-            if (x->n_hist[k].h_freq < locallofreq)
-                locallofreq = x->n_hist[k].h_freq;
-            if (localhifreq > locallofreq * vibmultiple)
-                break;
-            if (maxpow > power * growththresh &&
-                maxpow > x->n_hist[startphase].h_power * growththresh &&
-                    localhifreq < vibmultiple * locallofreq
-                        && freqatmaxpow > 0 && maxpow > powerthresh)
-            {
-                x->n_hifreq = x->n_lofreq = *note = freqatmaxpow;
-                x->n_age = 0;
-                x->n_peaked = 0;
-                /* post("got short note"); */
-                return;
-            }
-            if (++k >= NHISTPOINT)
-                k = 0;
-        }
-        
-    }
-    if (x->n_hifreq > 0)
-    {
-            /* test if we're within "vibrato" range, and if so update range */
-        if (freq * vibmultiple >= x->n_hifreq &&
-            x->n_lofreq * vibmultiple >= freq)
-        {
-            if (freq > x->n_hifreq)
-                x->n_hifreq = freq;
-            if (freq < x->n_lofreq)
-                x->n_lofreq = freq;
-        }
-        else if (x->n_hifreq > 0 && x->n_age > stableperiod)
-        {
-                /* if we've been out of range at least 1/2 the
-                last "stableperiod+1" analyses, clear the note */
-            int nbad = 0;
-            for (i = 0, k = x->n_histphase; i < stableperiod + 1; i++)
-            {
-                if (--k < 0)
-                    k = NHISTPOINT - 1;
-                if (x->n_hist[k].h_freq * vibmultiple <= x->n_hifreq ||
-                    x->n_lofreq * vibmultiple <= x->n_hist[k].h_freq)
-                        nbad++;
-            }
-            if (2 * nbad >= stableperiod + 1)
-            {
-                x->n_hifreq = x->n_lofreq = 0;
-                x->n_age = 0;
-            }
-        }
-    }
-
-    oldhistphase = x->n_histphase - stableperiod;
-    if (oldhistphase < 0)
-        oldhistphase += NHISTPOINT;
-        
-        /* look for envelope attacks */
-
-    if (x->n_hifreq > 0 && x->n_peaked)
-    {
-        if (freq > 0 && power > powerthresh &&
-            power > x->n_hist[oldhistphase].h_power *
-                exp((LOG10*0.1)*growththresh))
-        {
-                /* clear it and fall through for new stable-note test */
-            x->n_peaked = 0;
-            x->n_hifreq = x->n_lofreq = 0;
-            x->n_age = 0;
-        }
-    }
-    else if (!x->n_peaked)
-    {
-        if (x->n_hist[oldhistphase].h_power > powerthresh &&
-            x->n_hist[oldhistphase].h_power > power)
-                x->n_peaked = 1;
-    }
-
-        /* test for a new note using a stability criterion. */
-
-    if (freq >= 0 &&
-        (x->n_hifreq <= 0 || freq > x->n_hifreq || freq < x->n_lofreq))
-    {
-        float testfhi = freq, testflo = freq,
-            maxpow = x->n_hist[x->n_histphase].h_freq;
-        for (i = 0, k = x->n_histphase; i < stableperiod-1; i++)
-        {
-            if (--k < 0)
-                k = NHISTPOINT - 1;
-            if (x->n_hist[k].h_freq > testfhi)
-                testfhi = x->n_hist[k].h_freq;
-            if (x->n_hist[k].h_freq < testflo)
-                testflo = x->n_hist[k].h_freq;
-            if (x->n_hist[k].h_power > maxpow)
-                maxpow = x->n_hist[k].h_power;
-        }
-#if 0
-        if (loud)
-            post("freq %.2g testfhi %.2g  testflo %.2g maxpow %.2g",
-                freq, testfhi, testflo, maxpow);
-#endif
-        if (testflo > 0 && testfhi <= vibmultiple * testflo
-            && maxpow > powerthresh)
-        {
-                /* report new note */
-            float sumf = 0, sumw = 0, thisw;
-            for (i = 0, k = x->n_histphase; i < stableperiod; i++)
-            {
-                thisw = x->n_hist[k].h_power;
-                sumw += thisw;
-                sumf += thisw*x->n_hist[k].h_freq;
-                if (--k < 0)
-                    k = NHISTPOINT - 1;
-            }
-            x->n_hifreq = x->n_lofreq = *note = (sumw > 0 ? sumf/sumw : 0);
-#if 0
-                /* debugging printout */
-            for (i = 0; i < stableperiod; i++)
-            {
-                int k3 = x->n_histphase - i;
-                if (k3 < 0)
-                    k3 += NHISTPOINT;
-                startpost("%5.1f ", sigmund_ftom(x->n_hist[k3].h_freq));
-            }
-            post("");
-#endif
-            x->n_age = 0;
-            x->n_peaked = 0;
-            return;
-        }
-    }
-    *note = 0;
-    return;
-}
-
-/**************** object structure for Pd and Max. *********************/ 
-
-/* From here onward, the code is specific to eithr Pd, Max, or both.  If
-neither "PD 'nor "MSP" is defined, none of this is compiled, so that the
-whole file can be included in other, non-PD and non-Max projects.  */
-#ifdef PD
-#include "m_pd.h"
-#endif
-#ifdef MSP
-#include "ext.h"
-#include "z_dsp.h"
-#include "ext_support.h"
-#include "ext_proto.h"
-#include "ext_obex.h"
-typedef float t_floatarg;
-#define t_resizebytes(a, b, c) t_resizebytes((char *)(a), (b), (c))
-#endif
-
-#if (defined(PD) || defined (MSP))
-
-#define NHIST 100
-
-#define MODE_STREAM 1
-#define MODE_BLOCK 2        /* unimplemented */
-#define MODE_TABLE 3
-
-#define NPOINTS_DEF 1024
-#define NPOINTS_MIN 128
-
-#define HOP_DEF 512
-#define NPEAK_DEF 20
-
-#define VIBRATO_DEF 1
-#define STABLETIME_DEF 50
-#define MINPOWER_DEF 50
-#define GROWTH_DEF 7
-
-#define OUT_PITCH 0
-#define OUT_ENV 1
-#define OUT_NOTE 2
-#define OUT_PEAKS 3
-#define OUT_TRACKS 4
-#define OUT_SMSPITCH 5
-#define OUT_SMSNONPITCH 6
-
-typedef struct _varout
-{
-#ifdef PD
-    t_outlet *v_outlet;
-#endif /* PD */
-#ifdef MSP
-    void *v_outlet;
-#endif /* MSP */
-    int v_what;
-} t_varout;
-
-typedef struct _sigmund
-{
-#ifdef PD
-    t_object x_obj;
-    t_clock *x_clock;
-    float x_f;          /* for main signal inlet */
-#endif /* PD */
-#ifdef MSP
-    t_pxobject x_obj;
-    void *obex;
-    void *x_clock;
-    t_sample *x_inbuf2; /* extra input buffer to eat clock/DSP jitter */
-#endif /* MSP */
-    t_varout *x_varoutv;
-    int x_nvarout;
-    float x_sr;         /* sample rate */
-    int x_mode;         /* MODE_STREAM, etc. */
-    int x_npts;         /* number of points in analysis window */
-    int x_npeak;        /* number of peaks to find */
-    int x_loud;         /* debug level */
-    t_sample *x_inbuf;  /* input buffer */
-    int x_infill;       /* number of points filled */
-    int x_countdown;    /* countdown to start filling buffer */
-    int x_hop;          /* samples between analyses */ 
-    float x_maxfreq;    /* highest-frequency peak to report */ 
-    float x_vibrato;    /* vibrato depth in half tones */ 
-    float x_stabletime; /* period of stability needed for note */ 
-    float x_growth;     /* growth to set off a new note */ 
-    float x_minpower;   /* minimum power, in DB, for a note */ 
-    float x_param1;     /* three parameters for temporary use */
-    float x_param2;
-    float x_param3;
-    t_notefinder x_notefinder;  /* note parsing state */
-    t_peak *x_trackv;           /* peak tracking state */
-    int x_ntrack;               /* number of peaks tracked */
-    unsigned int x_dopitch:1;   /* which things to calculate */
-    unsigned int x_donote:1;
-    unsigned int x_dotracks:1;
-} t_sigmund;
-
-static void sigmund_preinit(t_sigmund *x)
-{
-    x->x_npts = NPOINTS_DEF;
-    x->x_param1 = 0;
-    x->x_param2 = 0.6;
-    x->x_param3 = 0;
-    x->x_hop = HOP_DEF;
-    x->x_mode = MODE_STREAM;
-    x->x_npeak = NPEAK_DEF;
-    x->x_vibrato = VIBRATO_DEF;
-    x->x_stabletime = STABLETIME_DEF;
-    x->x_growth = GROWTH_DEF;
-    x->x_minpower = MINPOWER_DEF;
-    x->x_maxfreq = 1000000;
-    x->x_loud = 0;
-    x->x_sr = 1;
-    x->x_nvarout = 0;
-    x->x_varoutv = (t_varout *)getbytes(0);
-    x->x_trackv = 0;
-    x->x_ntrack = 0;
-    x->x_dopitch = x->x_donote = x->x_dotracks = 0;
-    x->x_inbuf = 0;
-#ifdef MSP
-    x->x_inbuf2 = 0;
-#endif
-}
-
-static void sigmund_npts(t_sigmund *x, t_floatarg f)
-{
-    int nwas = x->x_npts, npts = f;
-        /* check parameter ranges */
-    if (npts < NPOINTS_MIN)
-        post("sigmund~: minimum points %d", NPOINTS_MIN),
-            npts = NPOINTS_MIN;
-    if (npts != (1 << sigmund_ilog2(npts)))
-        post("sigmund~: adjusting analysis size to %d points",
-            (npts = (1 << sigmund_ilog2(npts))));
-    if (npts != nwas)
-        x->x_countdown = x->x_infill  = 0;
-    if (x->x_mode == MODE_STREAM)
-    {
-        if (x->x_inbuf)
-        {
-            x->x_inbuf = (t_sample *)t_resizebytes(x->x_inbuf,
-                sizeof(*x->x_inbuf) * nwas, sizeof(*x->x_inbuf) * npts);
-#ifdef MSP
-            x->x_inbuf2 = (t_sample *)t_resizebytes(x->x_inbuf2,
-                sizeof(*x->x_inbuf2) * nwas, sizeof(*x->x_inbuf2) * npts);
-#endif
-        }
-        else
-        {
-            x->x_inbuf = (t_sample *)getbytes(sizeof(*x->x_inbuf) * npts);
-            memset((char *)(x->x_inbuf), 0, sizeof(*x->x_inbuf) * npts);
-#ifdef MSP
-            x->x_inbuf2 = (t_sample *)getbytes(sizeof(*x->x_inbuf2) * npts);
-            memset((char *)(x->x_inbuf2), 0, sizeof(*x->x_inbuf2) * npts);
-#endif
-        }
-    }
-    else x->x_inbuf = 0;
-    x->x_npts = npts;
-}
-
-static void sigmund_hop(t_sigmund *x, t_floatarg f)
-{
-    x->x_hop = f;
-        /* check parameter ranges */
-    if (x->x_hop != (1 << sigmund_ilog2(x->x_hop)))
-        post("sigmund~: adjusting analysis size to %d points",
-            (x->x_hop = (1 << sigmund_ilog2(x->x_hop))));
-}
-
-static void sigmund_npeak(t_sigmund *x, t_floatarg f)
-{
-    if (f < 1)
-        f = 1;
-    x->x_npeak = f;
-}
-
-static void sigmund_maxfreq(t_sigmund *x, t_floatarg f)
-{
-    x->x_maxfreq = f;
-}
-
-static void sigmund_vibrato(t_sigmund *x, t_floatarg f)
-{
-    if (f < 0)
-        f = 0;
-    x->x_vibrato = f;
-}
-
-static void sigmund_stabletime(t_sigmund *x, t_floatarg f)
-{
-    if (f < 0)
-        f = 0;
-    x->x_stabletime = f;
-}
-
-static void sigmund_growth(t_sigmund *x, t_floatarg f)
-{
-    if (f < 0)
-        f = 0;
-    x->x_growth = f;
-}
-
-static void sigmund_minpower(t_sigmund *x, t_floatarg f)
-{
-    if (f < 0)
-        f = 0;
-    x->x_minpower = f;
-}
-
-static void sigmund_doit(t_sigmund *x, int npts, float *arraypoints,
-    int loud, float srate)
-{
-    t_peak *peakv = (t_peak *)alloca(sizeof(t_peak) * x->x_npeak);
-    int nfound, i, cnt;
-    float freq = 0, power, note = 0;
-    sigmund_getrawpeaks(npts, arraypoints, x->x_npeak, peakv,
-        &nfound, &power, srate, loud, x->x_param1, x->x_param2, x->x_param3,
-        x->x_maxfreq);
-    if (x->x_dopitch)
-        sigmund_getpitch(nfound, peakv, &freq, npts, srate, loud);
-    if (x->x_donote)
-        notefinder_doit(&x->x_notefinder, freq, power, &note, x->x_vibrato, 
-            1 + x->x_stabletime * 0.001f * x->x_sr / (float)x->x_hop,
-                exp(LOG10*0.1*(x->x_minpower - 100)), x->x_growth, loud);
-    if (x->x_dotracks)
-        sigmund_peaktrack(nfound, peakv, x->x_ntrack, x->x_trackv, loud);
-    
-    for (cnt = x->x_nvarout; cnt--;)
-    {
-        t_varout *v = &x->x_varoutv[cnt];
-        switch (v->v_what)
-        {
-        case OUT_PITCH:
-            outlet_float(v->v_outlet, sigmund_ftom(freq));
-            break;
-        case OUT_ENV:
-            outlet_float(v->v_outlet, sigmund_powtodb(power));
-            break;
-        case OUT_NOTE:
-            if (note > 0)
-                outlet_float(v->v_outlet, sigmund_ftom(note));
-            break;
-        case OUT_PEAKS:
-            for (i = 0; i < nfound; i++)
-            {
-                t_atom at[5];
-                SETFLOAT(at, (float)i);
-                SETFLOAT(at+1, peakv[i].p_freq);
-                SETFLOAT(at+2, 2*peakv[i].p_amp);
-                SETFLOAT(at+3, 2*peakv[i].p_ampreal);
-                SETFLOAT(at+4, 2*peakv[i].p_ampimag);
-                outlet_list(v->v_outlet, 0, 5, at);   
-            }
-            break;
-        case OUT_TRACKS:
-            for (i = 0; i < x->x_ntrack; i++)
-            {
-                t_atom at[4];
-                SETFLOAT(at, (float)i);
-                SETFLOAT(at+1, x->x_trackv[i].p_freq);
-                SETFLOAT(at+2, 2*x->x_trackv[i].p_amp);
-                SETFLOAT(at+3, x->x_trackv[i].p_tmp);
-                outlet_list(v->v_outlet, 0, 4, at);   
-            }
-            break;
-        }
-    }
-}
-
-static t_int *sigmund_perform(t_int *w);
-static void sigmund_dsp(t_sigmund *x, t_signal **sp)
-{
-    if (x->x_mode == MODE_STREAM)
-    {
-        if (x->x_hop % sp[0]->s_n)
-            post("sigmund: adjusting hop size to %d",
-                (x->x_hop = sp[0]->s_n * (x->x_hop / sp[0]->s_n)));
-        x->x_sr = sp[0]->s_sr;
-        dsp_add(sigmund_perform, 3, x, sp[0]->s_vec, sp[0]->s_n);
-    }
-}
-
-static void sigmund_print(t_sigmund *x)
-{
-    post("sigmund~ settings:");
-    post("npts %d", (int)x->x_npts);
-    post("hop %d", (int)x->x_hop);
-    post("npeak %d", (int)x->x_npeak);
-    post("maxfreq %g", x->x_maxfreq);
-    post("vibrato %g", x->x_vibrato);
-    post("stabletime %g", x->x_stabletime);
-    post("growth %g", x->x_growth);
-    post("minpower %g", x->x_minpower);
-}
-
-static void sigmund_free(t_sigmund *x)
-{
-    if (x->x_inbuf)
-    {
-        freebytes(x->x_inbuf, x->x_npts * sizeof(*x->x_inbuf));
-#ifdef MSP
-        freebytes(x->x_inbuf2, x->x_npts * sizeof(*x->x_inbuf2));
-#endif
-    }
-    if (x->x_trackv)
-        freebytes(x->x_trackv, x->x_ntrack * sizeof(*x->x_trackv));
-    clock_free(x->x_clock);
-}
-
-#endif /* PD or MSP */
-/*************************** Glue for Pd ************************/
-#ifdef PD
-
-static t_class *sigmund_class;
-
-static void sigmund_tick(t_sigmund *x);
-static void sigmund_clear(t_sigmund *x);
-static void sigmund_npts(t_sigmund *x, t_floatarg f);
-static void sigmund_hop(t_sigmund *x, t_floatarg f);
-static void sigmund_npeak(t_sigmund *x, t_floatarg f);
-static void sigmund_maxfreq(t_sigmund *x, t_floatarg f);
-static void sigmund_vibrato(t_sigmund *x, t_floatarg f);
-static void sigmund_stabletime(t_sigmund *x, t_floatarg f);
-static void sigmund_growth(t_sigmund *x, t_floatarg f);
-static void sigmund_minpower(t_sigmund *x, t_floatarg f);
-
-static void sigmund_tick(t_sigmund *x)
-{
-    if (x->x_infill == x->x_npts)
-    {
-        sigmund_doit(x, x->x_npts, x->x_inbuf, x->x_loud, x->x_sr);
-        if (x->x_hop >= x->x_npts)
-        {
-            x->x_infill = 0;
-            x->x_countdown = x->x_hop - x->x_npts;
-        }
-        else
-        {
-            memmove(x->x_inbuf, x->x_inbuf + x->x_hop,
-                (x->x_infill = x->x_npts - x->x_hop) * sizeof(*x->x_inbuf));
-            x->x_countdown = 0;
-        }
-        if (x->x_loud)
-            x->x_loud--;
-    }
-}
-
-static t_int *sigmund_perform(t_int *w)
-{
-    t_sigmund *x = (t_sigmund *)(w[1]);
-    float *in = (float *)(w[2]);
-    int n = (int)(w[3]);
-
-    if (x->x_hop % n)
-        return (w+4);
-    if (x->x_countdown > 0)
-        x->x_countdown -= n;
-    else if (x->x_infill != x->x_npts)
-    {
-        int j;
-        float *fp = x->x_inbuf + x->x_infill;
-        for (j = 0; j < n; j++)
-            *fp++ = *in++;
-        x->x_infill += n;
-        if (x->x_infill == x->x_npts)
-            clock_delay(x->x_clock, 0);
-    }
-    return (w+4);
-}
-
-static void *sigmund_new(t_symbol *s, int argc, t_atom *argv)
-{
-    t_sigmund *x = (t_sigmund *)pd_new(sigmund_class);
-    sigmund_preinit(x);
-
-    while (argc > 0)
-    {
-        t_symbol *firstarg = atom_getsymbolarg(0, argc, argv);
-        if (!strcmp(firstarg->s_name, "-t"))
-        {
-            x->x_mode = MODE_TABLE;
-            argc--, argv++;
-        }
-        else if (!strcmp(firstarg->s_name, "-s"))
-        {
-            x->x_mode = MODE_STREAM;
-            argc--, argv++;
-        }
-#if 0
-        else if (!strcmp(firstarg->s_name, "-b"))
-        {
-            x->x_mode = MODE_BLOCK;
-            argc--, argv++;
-        }
-#endif
-        else if (!strcmp(firstarg->s_name, "-npts") && argc > 1)
-        {
-            x->x_npts = atom_getfloatarg(1, argc, argv);
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-hop") && argc > 1)
-        {
-            sigmund_hop(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-npeak") && argc > 1)
-        {
-            sigmund_npeak(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-maxfreq") && argc > 1)
-        {
-            sigmund_maxfreq(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-vibrato") && argc > 1)
-        {
-            sigmund_vibrato(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-stabletime") && argc > 1)
-        {
-            sigmund_stabletime(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-growth") && argc > 1)
-        {
-            sigmund_growth(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "-minpower") && argc > 1)
-        {
-            sigmund_minpower(x, atom_getfloatarg(1, argc, argv));
-            argc -= 2; argv += 2;
-        }
-        else if (!strcmp(firstarg->s_name, "pitch"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_outlet =
-                outlet_new(&x->x_obj, &s_float);
-            x->x_varoutv[x->x_nvarout].v_what = OUT_PITCH;
-            x->x_nvarout = n2;
-            x->x_dopitch = 1;
-            argc--, argv++;
-        }
-        else if (!strcmp(firstarg->s_name, "env"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_outlet =
-                outlet_new(&x->x_obj, &s_float);
-            x->x_varoutv[x->x_nvarout].v_what = OUT_ENV;
-            x->x_nvarout = n2;
-            argc--, argv++;
-        }
-        else if (!strcmp(firstarg->s_name, "note")
-            || !strcmp(firstarg->s_name, "notes"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_outlet =
-                outlet_new(&x->x_obj, &s_float);
-            x->x_varoutv[x->x_nvarout].v_what = OUT_NOTE;
-            x->x_nvarout = n2;
-            x->x_dopitch = x->x_donote = 1;
-            argc--, argv++;
-        }
-        else if (!strcmp(firstarg->s_name, "peaks"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_outlet =
-                outlet_new(&x->x_obj, &s_list);
-            x->x_varoutv[x->x_nvarout].v_what = OUT_PEAKS;
-            x->x_nvarout = n2;
-            argc--, argv++;
-        }
-        else if (!strcmp(firstarg->s_name, "tracks"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_outlet =
-                outlet_new(&x->x_obj, &s_list);
-            x->x_varoutv[x->x_nvarout].v_what = OUT_TRACKS;
-            x->x_nvarout = n2;
-            x->x_dotracks = 1;
-            argc--, argv++;
-        }
-        else
-        {
-            pd_error(x, "sigmund: %s: unknown flag or argument missing",
-                firstarg->s_name);
-            argc--, argv++;
-        }
-    }
-    if (!x->x_nvarout)
-    {
-        x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-            0, 2*sizeof(t_varout));
-        x->x_varoutv[0].v_outlet = outlet_new(&x->x_obj, &s_float);
-        x->x_varoutv[0].v_what = OUT_PITCH;
-        x->x_varoutv[1].v_outlet = outlet_new(&x->x_obj, &s_float);
-        x->x_varoutv[1].v_what = OUT_ENV;
-        x->x_nvarout = 2;
-        x->x_dopitch = 1;
-    }
-    if (x->x_dotracks)
-    {
-        x->x_ntrack = x->x_npeak;
-        x->x_trackv = (t_peak *)getbytes(x->x_ntrack * sizeof(*x->x_trackv));
-    }
-    x->x_clock = clock_new(&x->x_obj.ob_pd, (t_method)sigmund_tick);
-    
-    x->x_infill = 0;
-    x->x_countdown = 0;
-    sigmund_npts(x, x->x_npts);
-    notefinder_init(&x->x_notefinder);
-    sigmund_clear(x);
-    return (x);
-}
-
-static void sigmund_list(t_sigmund *x, t_symbol *s, int argc, t_atom *argv)
-{
-    t_symbol *syminput = atom_getsymbolarg(0, argc, argv);
-    int npts = atom_getintarg(1, argc, argv);
-    int onset = atom_getintarg(2, argc, argv);
-    float srate = atom_getfloatarg(3, argc, argv);
-    int loud = atom_getfloatarg(4, argc, argv);
-    int arraysize, totstorage, nfound, i;
-    t_garray *a;
-    float *arraypoints, pit;
-    t_word *wordarray = 0;
-    if (argc < 5)
-    {
-        post(
-         "sigmund: array-name, npts, array-onset, samplerate, loud");
-        return;
-    }
-    if (npts < 64 || npts != (1 << ilog2(npts))) 
-    {
-        error("sigmund: bad npoints");
-        return;
-    }
-    if (onset < 0)
-    {
-        error("sigmund: negative onset");
-        return;
-    }
-    arraypoints = alloca(sizeof(float)*npts);
-    if (!(a = (t_garray *)pd_findbyclass(syminput, garray_class)) ||
-        !garray_getfloatwords(a, &arraysize, &wordarray) ||
-            arraysize < onset + npts)
-    {
-        error("%s: array missing or too small", syminput->s_name);
-        return;
-    }
-    if (arraysize < npts)
-    {
-        error("sigmund~: too few points in array");
-        return;
-    }
-    for (i = 0; i < npts; i++)
-        arraypoints[i] = wordarray[i+onset].w_float;
-    sigmund_doit(x, npts, arraypoints, loud, srate);
-}
-
-static void sigmund_clear(t_sigmund *x)
-{
-    if (x->x_trackv)
-        memset(x->x_trackv, 0, x->x_ntrack * sizeof(*x->x_trackv));
-    x->x_infill = x->x_countdown = 0;
-}
-
-    /* these are for testing; their meanings vary... */
-static void sigmund_param1(t_sigmund *x, t_floatarg f)
-{
-    x->x_param1 = f;
-}
-
-static void sigmund_param2(t_sigmund *x, t_floatarg f)
-{
-    x->x_param2 = f;
-}
-
-static void sigmund_param3(t_sigmund *x, t_floatarg f)
-{
-    x->x_param3 = f;
-}
-
-static void sigmund_printnext(t_sigmund *x, t_float f)
-{
-    x->x_loud = f;
-}
-
-void sigmund_tilde_setup(void)
-{
-    sigmund_class = class_new(gensym("sigmund~"), (t_newmethod)sigmund_new,
-        (t_method)sigmund_free, sizeof(t_sigmund), 0, A_GIMME, 0);
-    class_addlist(sigmund_class, sigmund_list);
-    class_addmethod(sigmund_class, (t_method)sigmund_dsp, gensym("dsp"), 0);
-    CLASS_MAINSIGNALIN(sigmund_class, t_sigmund, x_f);
-    class_addmethod(sigmund_class, (t_method)sigmund_param1,
-        gensym("param1"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_param2,
-        gensym("param2"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_param3,
-        gensym("param3"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_npts,
-        gensym("npts"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_hop,
-        gensym("hop"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_maxfreq,
-        gensym("maxfreq"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_npeak,
-        gensym("npeak"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_vibrato,
-        gensym("vibrato"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_stabletime,
-        gensym("stabletime"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_growth,
-        gensym("growth"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_minpower,
-        gensym("minpower"), A_FLOAT, 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_print,
-        gensym("print"), 0);
-    class_addmethod(sigmund_class, (t_method)sigmund_printnext,
-        gensym("printnext"), A_FLOAT, 0);
-    post("sigmund~ version 0.05");
-}
-
-#endif /* PD */
-
-/************************ Max/MSP glue **********************************/
-
-/* -------------------------- MSP glue ------------------------- */
-#ifdef MSP
-static void *sigmund_class;
-
-/* Max/MSP has laxer sync between DSP and "tick"s - so in the perf routine we
-keep a circular buffer that is rectified into inbuf only when the tick comes. */
-
-static void sigmund_tick(t_sigmund *x)
-{
-    int i, j, npts = x->x_npts;
-    if (!x->x_inbuf)
-        return;
-    for (i = x->x_infill, j = 0; i < npts; i++, j++)
-        x->x_inbuf[j] = x->x_inbuf2[i];
-    for (i = 0; j < npts; i++, j++)
-        x->x_inbuf[j] = x->x_inbuf2[i];
-    sigmund_doit(x, x->x_npts, x->x_inbuf, x->x_loud, x->x_sr);
-    x->x_loud = 0;
-}
-
-static t_int *sigmund_perform(t_int *w)
-{
-    t_sigmund *x = (t_sigmund *)(w[1]);
-    float *in = (float *)(w[2]);
-    int n = (int)(w[3]), j;
-    int infill = x->x_infill;
-    float *fp = x->x_inbuf2 + infill;
-    if (infill < 0 || infill >= x->x_npts)
-        infill = 0;
-        /* for some reason this sometimes happens: */
-    if (!x->x_inbuf2)
-        return (w+4);
-    for (j = 0; j < n; j++)
-    {
-         *fp++ = *in++;
-         if (++infill == x->x_npts)
-            infill = 0, fp = x->x_inbuf2;
-    }
-    x->x_infill = infill;
-    if (x->x_countdown <= 0)
-    {
-        x->x_countdown = x->x_hop;
-        clock_delay(x->x_clock, 0);
-    }
-    x->x_countdown -= n;
-    return (w+4);
-}
-
-static void *sigmund_new(t_symbol *s, long ac, t_atom *av)
-{
-    t_sigmund *x;
-    t_varout *g;
-    int i, j;
-    if (!(x = (t_sigmund *)object_alloc(sigmund_class)))
-        return (0);
-    sigmund_preinit(x);
-    attr_args_process(x, ac, av);   
-    dsp_setup((t_pxobject *)x, 1);
-    object_obex_store(x, gensym("dumpout"), outlet_new(x, NULL));
-    
-    for (i = 0; i < ac; i++)
-        if (av[i].a_type == A_SYM)
-    {
-        char *s = av[i].a_w.w_sym->s_name;
-        if (!strcmp(s, "pitch"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_what = OUT_PITCH;
-            x->x_nvarout = n2;
-            x->x_dopitch = 1;
-        }
-        else if (!strcmp(s, "env"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_what = OUT_ENV;
-            x->x_nvarout = n2;
-        }
-        else if (!strcmp(s, "note") || !strcmp(s, "notes"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_what = OUT_NOTE;
-            x->x_nvarout = n2;
-            x->x_dopitch = x->x_donote = 1;
-        }
-        else if (!strcmp(s, "peaks"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_what = OUT_PEAKS;
-            x->x_nvarout = n2;
-        }
-        else if (!strcmp(s, "tracks"))
-        {
-            int n2 = x->x_nvarout+1;
-            x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-                x->x_nvarout*sizeof(t_varout), n2*sizeof(t_varout));
-            x->x_varoutv[x->x_nvarout].v_what = OUT_TRACKS;
-            x->x_nvarout = n2;
-            x->x_dotracks = 1;
-        }
-        else if (s[0] != '@')
-            post("sigmund: ignoring unknown argument '%s'" ,s);
-    }
-    if (!x->x_nvarout)
-    {
-        x->x_varoutv = (t_varout *)t_resizebytes(x->x_varoutv,
-            0, 2*sizeof(t_varout));
-        x->x_varoutv[0].v_what = OUT_PITCH;
-        x->x_varoutv[1].v_what = OUT_ENV;
-        x->x_nvarout = 2;
-        x->x_dopitch = 1;
-    }
-    for (j = 0, g = x->x_varoutv + x->x_nvarout-1; j < x->x_nvarout; j++, g--)
-        g->v_outlet = ((g->v_what == OUT_PITCH  || g->v_what == OUT_ENV ||
-            g->v_what == OUT_NOTE) ?
-                floatout((t_object *)x) : listout((t_object *)x));
-    if (x->x_dotracks)
-    {
-        x->x_ntrack = x->x_npeak;
-        x->x_trackv = (t_peak *)getbytes(x->x_ntrack * sizeof(*x->x_trackv));
-    }
-    x->x_clock = clock_new(x, (method)sigmund_tick);
-    x->x_infill = 0;
-    x->x_countdown = 0;
-    sigmund_npts(x, x->x_npts);
-    notefinder_init(&x->x_notefinder);
-    return (x);
-}
-
-/* Attribute setters. */
-void sigmund_npts_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_npts(x, atom_getfloat(av));
-}
-
-void sigmund_hop_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_hop(x, atom_getfloat(av));
-}
-
-void sigmund_npeak_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_npeak(x, atom_getfloat(av));
-}
-
-void sigmund_maxfreq_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_maxfreq(x, atom_getfloat(av));
-}
-
-void sigmund_vibrato_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_vibrato(x, atom_getfloat(av));
-}
-
-void sigmund_stabletime_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_stabletime(x, atom_getfloat(av));
-}
-
-void sigmund_growth_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_growth(x, atom_getfloat(av));
-}
-
-void sigmund_minpower_set(t_sigmund *x, void *attr, long ac, t_atom *av)
-{
-    if (ac && av)
-        sigmund_minpower(x, atom_getfloat(av));
-}
-
-/* end attr setters */
-
-void sigmund_assist(t_sigmund *x, void *b, long m, long a, char *s)
-{
-}
-
-int main()
-{       
-    t_class *c;
-    long attrflags = 0;
-    t_symbol *sym_long = gensym("long"), *sym_float32 = gensym("float32");
-    
-    c = class_new("sigmund~", (method)sigmund_new,
-        (method)sigmund_free, sizeof(t_sigmund), (method)0L, A_GIMME, 0);
-    
-    class_obexoffset_set(c, calcoffset(t_sigmund, obex));
-    
-    class_addattr(c, attr_offset_new("npts", sym_long, attrflags,
-        (method)0L, (method)sigmund_npts_set,
-            calcoffset(t_sigmund, x_npts)));
-    class_addattr(c ,attr_offset_new("hop", sym_long, attrflags,
-        (method)0L, (method)sigmund_hop_set,
-            calcoffset(t_sigmund, x_hop)));
-    class_addattr(c ,attr_offset_new("maxfreq", sym_float32, attrflags,
-        (method)0L, (method)sigmund_maxfreq_set,
-            calcoffset(t_sigmund, x_maxfreq)));
-    class_addattr(c ,attr_offset_new("npeak", sym_long, attrflags,
-        (method)0L, (method)sigmund_npeak_set,
-            calcoffset(t_sigmund, x_npeak)));
-    class_addattr(c ,attr_offset_new("vibrato", sym_float32, attrflags,
-        (method)0L, (method)sigmund_vibrato_set,
-            calcoffset(t_sigmund, x_vibrato)));
-    class_addattr(c ,attr_offset_new("stabletime", sym_float32, attrflags,
-        (method)0L, (method)sigmund_stabletime_set,
-            calcoffset(t_sigmund, x_stabletime)));
-    class_addattr(c ,attr_offset_new("growth", sym_float32, attrflags,
-        (method)0L, (method)sigmund_growth_set,
-            calcoffset(t_sigmund, x_growth)));
-    class_addattr(c ,attr_offset_new("minpower", sym_float32, attrflags,
-        (method)0L, (method)sigmund_minpower_set,
-            calcoffset(t_sigmund, x_minpower)));
-
-    class_addmethod(c, (method)sigmund_dsp, "dsp", A_CANT, 0);
-    class_addmethod(c, (method)sigmund_print, "print", 0);
-    class_addmethod(c, (method)sigmund_print, "printnext", A_DEFFLOAT, 0);
-    class_addmethod(c, (method)sigmund_assist, "assist", A_CANT, 0);
-    
-    class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0);
-    class_addmethod(c, (method)object_obex_quickref, "quickref", A_CANT, 0);
-    
-    class_dspinit(c);
-
-    class_register(CLASS_BOX, c);
-    sigmund_class = c;
-    
-    post("sigmund~ v0.05");
-    return (0);
-}
-
-
-#endif /* MSP */
-
-
diff --git a/extra/stdout/stdout.pd_linux b/extra/stdout/stdout.pd_linux
new file mode 100755
index 0000000000000000000000000000000000000000..2d88ec3f99662cbb905d4a1d01c13d0bac25df75
GIT binary patch
literal 5424
zcmeHLeQaA-6~9j0ELpO~4eoHOz`XJ{Qo31bYoV4E5iKbN6rrw3KOm%z6Fae)KZ5<-
zwNTV#FA;JbPk{`n5}*w#&=5mRWFR&smd%j^0-+E-)V~nwI`*7qC9SeCbtUHayYJo1
z%`{EoFaGF>&O7Ja^SkGqckaE<@8!(?&QCiW4xy-8R0~>tHA46yy_+nLUwB20Xc1e*
z7U@@b%22(<8)&$M<!^+3m&JYrYy%^t^jAT+;djGNo`+4Q-)Zv-q+$&^S@|A%RS&^@
z7peJ&=&#5x3qpR*hmg_@Sq(n$`NN{~Nd320uANJaKJe6;M;^VmWV{)DjJLfROuEAo
z62B2T^T>OJybb&TFyo>P;&w1vAam40z8|p;_JhQdo4|Eo=5GMM7qNEYIhXZhh1Vfw
z+v-#d#`Vm9?K{uE@~zYD`~SLh;VZ|QpUYp}c=^x&;w{`nT@@B<=e;QMLfN4VNZL<S
z*sOPKo!whuGhXL9`|A}p=bu|=|8kvuqQYihk`*@NH&@u(piflT^nVKM#X=<@o6yxu
zkZoREKrV5${3l4imzHH;fUL9`<4g8}H(`bEguRE04Qk@<2n2@W$wVNn2UB_=AOg`u
zR2P9k2)G7L2B`*P(XWO@;BzMehr&bAv>r~i$Aal}I4#n8D4Ed%>9C#|7DM4g`czyD
z&=*LAAF;JyC=^Vb(j(EtkQfe0hc!(M4#qO+2!f;%1H-38P*28DNQyv+SU7<ahGFW1
zfq}@wA{Ol*@THT!k7F414m`}!z+f;MqbqK^!l9rZ1fm~B$h#7Oa3UlQbbj{1_P{RR
zPT%e|-M^-_u4%h{eycmYR>^b2(^idB!F|hCI&S)Nil;HgK9kaSMR5c+h!S*;xua1u
z*(u(zZI`sGMcKCXEyP!eI(y@`dWGQGyM$*;4GxG&iNs5kShr<L9%|rj!yG3iaJ7_p
zNHkEQNEamzmzxs%$3uz0&6LRKrNn{PC~;U@C=vHQN}RI8*;l)aC8sGsJ)?z*twQ9c
zmdoYx_=3K{^kLNOMSAljavkgWU7<Y9Csg^odTx}@BdCagMd=@yRzA;eMCdNfOPi-W
z!okvvv^}(WDLo@?o{Wf>_LI`48fl?DDQ%5*EA0_!(-ql6dsy1{(Qc#NCv8F_pP_wF
z+Fa(yLE3H7=G4eB+O4o5*@Gip=1-xG7S3)F!dP;R{JM>vOmEJ(0o3@6zA<O)!${Vt
znNMLPXLP{IPkW%}r`))1|JzHeRmK&^-sQA6FCP!aj3X;y<;M*otT}s^Q~xX)ZJ6ya
zW?enUdkb6x+3L|ky-e@UO*I3LCD@!ZR;bPB^?5m#b!+8$W7gf%TgWwQg-KGEc@>z^
z!XMF9W2q%?^j$8OS?JGJS==99!!`F^T(jL;ZMIW$&UI*96#>bGp={tXaLx`n=Z1xL
zW({_d<6RgxW?Om+gUB~3^BtG@Jh?T@8Hw@q6!OpB%eeU$K1$JLJ|yuz8$b0H%v=?t
zerRom>{$Lq;twA^(lxr&jE$C?(EJeQCOQAg2Ql)rwg)4{4owre7qorQQGKn6qm$bd
z{yuLjJEk>Yc;`$WplpZMj6}F|r#bQ;q}8?N;+R$sfXLlx6rK4;%d4xa|6aIzKKt_M
z#SxJH+K)#@@XIx}k3U=s#^0-VVAA;OjbqQ@Bp9zdvWxi%nW7rw#>MKq6%U>DAf3B$
z?DxR!)uDZ(1TBYg&g#}&SzU8x_i4sl?e?pH*P3yZl=W-oJuD3XN71<MXdFAsMAxhI
zRx8RBqjXzQ-idIH%W3YgBfNrr>L^<HF5)}Z<Cjrft@$=^%s5TCn2Tv1N3rxn-00w>
zvFJc$RuIJYoTw|-c#Wc?SR=9}t6=*E%wO11;*j~H_MA$*xqTU1l^Hq39JleGlz7}G
z3$4VLj5!ZdU<%qIryR1U+zu&kezE%9)0l>Rwez62=2m;&!rN9$#}^vMw{gRr)|&Iv
zLp&O&XwIpjNg{h1EjdP{wQ0h;H*gDO`bKBD|9XxGdJB_Qn=Tt`-6%bQZ96#mjvZKM
z*Gc=OMVC>ms@y^2zrkviQmDq{OPM^qlato@N7*?4o3YzlP>=1B!g@a4ApwghFK09$
zg7H>a-;$rEY9BY_inBbQtAQi4qMj=i&-Q09)pQ~D7w{anf0^$|Kft%aTXd@fw>t3u
z+5wz!`JSRA>*T|W@1vA+V7`U%{U5J(^1YwGZyq?`SS=@i1qqkvz>g%q!&YGP)Nh95
zCj#FA_|Ch6cTWD~^?~^m<aZ2ya>We<qy862ehcvpjNg;BU_9uOV;DzmNrV&2kY9v-
z-L^6GKM}vV75xCk{~Y`>cmaG7d<|TMn`r`X1MdPq2tEYnyY+$g_D^_Q4)<pgddBPb
z`F%U@_h+QFce`Z^;Y&yG`Jo5<g)foR!@i+J#@C;T#zOZ;Lqb}SAU<1sp;PjEM@l_q
zc}|2=>1Z->lM#R~6^;>SDZ?>c_~eI{PY<7jE<d+?sigdL@r5IS!Bj9F7QO*JnMxy(
zCB8g>KnN0yM+cA~iHW%QWHf6gzIiYy8IOk(y6V#VORhD4cDTkXHfxZIuxygH;fnT3
z9QP3UN!ZFyN&YbSO{_EHagUMtj=Ubn{leTbFEHGH2f@q%A@SUUtzhm$;<#7I+@p$=
zx(5T?Z^Uu0kv|4q<>feeKbZTII`=5~AoR+-Fhw^QpGtBL_c)m~Lr9|JUg!S|6pm+t
z+=nsxd4CEw2%WWJE6Ov;bIE&CL>wsyR=5dZ$n(-;U5F#czzWxgpyUfG2z)LuDFs$I
ze*2U8TCYe=If(({c7eNrA@lj6h(7X&E!n?5V8|*4hSv16HjZm2|DT3`@UUNs)SPc(
zfN_bd#rdv%58Sy5oC`P?a4H5|Yx?(~v&W1l|4#=T`^WVqaSrSF5m@Er_x2^=RL|g&
zIAVWNf#b7q1vu_!MZ}Pw1*>>`*0drR#}z64c?>W=>*N1w{J>TAS>axUpYdA3B;r0|
Vsq#vnV#ZQ*6u93i1Ckihe*tf#?vnrj

literal 0
HcmV?d00001

diff --git a/portaudio/include/pa_asio.h b/portaudio/include/pa_asio.h
index 64d1bd4e7..21f50ddac 100644
--- a/portaudio/include/pa_asio.h
+++ b/portaudio/include/pa_asio.h
@@ -1,7 +1,7 @@
 #ifndef PA_ASIO_H
 #define PA_ASIO_H
 /*
- * $Id: pa_asio.h 1400 2009-01-21 10:20:42Z rossb $
+ * $Id: pa_asio.h 1083 2006-08-23 07:30:49Z rossb $
  * PortAudio Portable Real-Time Audio Library
  * ASIO specific extensions
  *
@@ -40,7 +40,6 @@
 
 
 /** @file
- @ingroup public_header
  @brief ASIO-specific PortAudio API extension header file.
 */
 
@@ -100,19 +99,6 @@ PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
         const char** channelName );
 
 
-/** Set the sample rate of an open paASIO stream.
- 
- @param stream The stream to operate on.
- @param sampleRate The new sample rate. 
-
- Note that this function may fail if the stream is alredy running and the 
- ASIO driver does not support switching the sample rate of a running stream.
-
- Returns paIncompatibleStreamHostApi if stream is not a paASIO stream.
-*/
-PaError PaAsio_SetStreamSampleRate( PaStream* stream, double sampleRate );
-
-
 #define paAsioUseChannelSelectors      (0x01)
 
 typedef struct PaAsioStreamInfo{
diff --git a/portaudio/include/pa_jack.h b/portaudio/include/pa_jack.h
index ba2aeb9c0..c4eca1d6f 100644
--- a/portaudio/include/pa_jack.h
+++ b/portaudio/include/pa_jack.h
@@ -40,8 +40,7 @@
  */
 
 /** @file
- *  @ingroup public_header
- *  @brief JACK-specific PortAudio API extension header file.
+ * JACK-specific PortAudio API extension header file.
  */
 #include "portaudio.h"
 
diff --git a/portaudio/include/pa_linux_alsa.h b/portaudio/include/pa_linux_alsa.h
index de89ae9bf..7db633aea 100644
--- a/portaudio/include/pa_linux_alsa.h
+++ b/portaudio/include/pa_linux_alsa.h
@@ -2,7 +2,7 @@
 #define PA_LINUX_ALSA_H
 
 /*
- * $Id: pa_linux_alsa.h 1414 2009-05-24 17:02:10Z aknudsen $
+ * $Id: pa_linux_alsa.h 1236 2007-06-24 20:39:26Z aknudsen $
  * PortAudio Portable Real-Time Audio Library
  * ALSA-specific extensions
  *
@@ -40,8 +40,7 @@
  */
 
 /** @file
- *  @ingroup public_header
- *  @brief ALSA-specific PortAudio API extension header file.
+ * ALSA-specific PortAudio API extension header file.
  */
 #include "portaudio.h"
 
@@ -87,11 +86,6 @@ PaError PaAlsa_GetStreamOutputCard( PaStream *s, int *card );
  */
 PaError PaAlsa_SetNumPeriods( int numPeriods );
 
-/** Set the maximum number of times to retry opening busy device (sleeping for a
- * short interval inbetween).
- */
-PaError PaAlsa_SetRetriesBusy( int retries );
-
 #ifdef __cplusplus
 }
 #endif
diff --git a/portaudio/include/pa_mac_core.h b/portaudio/include/pa_mac_core.h
index b0921b3c7..783e3bc97 100644
--- a/portaudio/include/pa_mac_core.h
+++ b/portaudio/include/pa_mac_core.h
@@ -38,11 +38,6 @@
  * license above.
  */
 
-/** @file
- *  @ingroup public_header
- *  @brief CoreAudio-specific PortAudio API extension header file.
- */
-
 #include <AudioUnit/AudioUnit.h>
 //#include <AudioToolbox/AudioToolbox.h>
 
diff --git a/portaudio/include/pa_win_ds.h b/portaudio/include/pa_win_ds.h
deleted file mode 100644
index 47e1d722c..000000000
--- a/portaudio/include/pa_win_ds.h
+++ /dev/null
@@ -1,101 +0,0 @@
-#ifndef PA_WIN_DS_H
-#define PA_WIN_DS_H
-/*
- * $Id:  $
- * PortAudio Portable Real-Time Audio Library
- * DirectSound specific extensions
- *
- * Copyright (c) 1999-2007 Ross Bencina and Phil Burk
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/** @file
- @ingroup public_header
- @brief DirectSound-specific PortAudio API extension header file.
-*/
-
-
-#include "portaudio.h"
-#include "pa_win_waveformat.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-
-#define paWinDirectSoundUseLowLevelLatencyParameters            (0x01)
-#define paWinDirectSoundUseChannelMask                          (0x04)
-
-
-typedef struct PaWinDirectSoundStreamInfo{
-    unsigned long size;             /**< sizeof(PaWinDirectSoundStreamInfo) */
-    PaHostApiTypeId hostApiType;    /**< paDirectSound */
-    unsigned long version;          /**< 1 */
-
-    unsigned long flags;
-
-    /* low-level latency setting support
-        TODO ** NOT IMPLEMENTED **
-        These settings control the number and size of host buffers in order
-        to set latency. They will be used instead of the generic parameters
-        to Pa_OpenStream() if flags contains the paWinDirectSoundUseLowLevelLatencyParameters
-        flag.
-
-        If PaWinDirectSoundStreamInfo structures with paWinDirectSoundUseLowLevelLatencyParameters
-        are supplied for both input and output in a full duplex stream, then the
-        input and output framesPerBuffer must be the same, or the larger of the
-        two must be a multiple of the smaller, otherwise a
-        paIncompatibleHostApiSpecificStreamInfo error will be returned from
-        Pa_OpenStream().
-
-    unsigned long framesPerBuffer;
-    */
-
-    /*
-        support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
-        paWinDirectSoundUseChannelMask this allows you to specify which speakers 
-        to address in a multichannel stream. Constants for channelMask
-        are specified in pa_win_waveformat.h
-
-    */
-    PaWinWaveFormatChannelMask channelMask;
-
-}PaWinDirectSoundStreamInfo;
-
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* PA_WIN_DS_H */                                  
diff --git a/portaudio/include/pa_win_wasapi.h b/portaudio/include/pa_win_wasapi.h
deleted file mode 100644
index 64eb49b02..000000000
--- a/portaudio/include/pa_win_wasapi.h
+++ /dev/null
@@ -1,391 +0,0 @@
-#ifndef PA_WIN_WASAPI_H
-#define PA_WIN_WASAPI_H
-/*
- * $Id:  $
- * PortAudio Portable Real-Time Audio Library
- * DirectSound specific extensions
- *
- * Copyright (c) 1999-2007 Ross Bencina and Phil Burk
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/** @file
- @ingroup public_header
- @brief WASAPI-specific PortAudio API extension header file.
-*/
-
-#include "portaudio.h"
-#include "pa_win_waveformat.h"
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-
-/* Setup flags */
-typedef enum PaWasapiFlags
-{
-    /* puts WASAPI into exclusive mode */
-    paWinWasapiExclusive                = (1 << 0),
-
-    /* allows to skip internal PA processing completely */
-    paWinWasapiRedirectHostProcessor    = (1 << 1),
-
-    /* assigns custom channel mask */
-    paWinWasapiUseChannelMask           = (1 << 2),
-
-    /* selects non-Event driven method of data read/write
-       Note: WASAPI Event driven core is capable of 2ms latency!!!, but Polling
-             method can only provide 15-20ms latency. */
-    paWinWasapiPolling                  = (1 << 3),
-
-    /* forces custom thread priority setting. must be used if PaWasapiStreamInfo::threadPriority 
-       is set to custom value. */
-    paWinWasapiThreadPriority           = (1 << 4)
-}
-PaWasapiFlags;
-#define paWinWasapiExclusive             (paWinWasapiExclusive)
-#define paWinWasapiRedirectHostProcessor (paWinWasapiRedirectHostProcessor)
-#define paWinWasapiUseChannelMask        (paWinWasapiUseChannelMask)
-#define paWinWasapiPolling               (paWinWasapiPolling)
-#define paWinWasapiThreadPriority        (paWinWasapiThreadPriority)
-
-
-/* Host processor. Allows to skip internal PA processing completely. 
-   You must set paWinWasapiRedirectHostProcessor flag to PaWasapiStreamInfo::flags member
-   in order to have host processor redirected to your callback.
-   Use with caution! inputFrames and outputFrames depend solely on final device setup.
-   To query maximal values of inputFrames/outputFrames use PaWasapi_GetFramesPerHostBuffer.
-*/
-typedef void (*PaWasapiHostProcessorCallback) (void *inputBuffer,  long inputFrames,
-                                               void *outputBuffer, long outputFrames,
-                                               void *userData);
-
-/* Device role */
-typedef enum PaWasapiDeviceRole
-{
-    eRoleRemoteNetworkDevice = 0,
-    eRoleSpeakers,
-    eRoleLineLevel,
-    eRoleHeadphones,
-    eRoleMicrophone,
-    eRoleHeadset,
-    eRoleHandset,
-    eRoleUnknownDigitalPassthrough,
-    eRoleSPDIF,
-    eRoleHDMI,
-    eRoleUnknownFormFactor
-}
-PaWasapiDeviceRole;
-
-
-/* Jack connection type */
-typedef enum PaWasapiJackConnectionType
-{
-    eJackConnTypeUnknown,
-    eJackConnType3Point5mm,
-    eJackConnTypeQuarter,
-    eJackConnTypeAtapiInternal,
-    eJackConnTypeRCA,
-    eJackConnTypeOptical,
-    eJackConnTypeOtherDigital,
-    eJackConnTypeOtherAnalog,
-    eJackConnTypeMultichannelAnalogDIN,
-    eJackConnTypeXlrProfessional,
-    eJackConnTypeRJ11Modem,
-    eJackConnTypeCombination
-} 
-PaWasapiJackConnectionType;
-
-
-/* Jack geometric location */
-typedef enum PaWasapiJackGeoLocation
-{
-	eJackGeoLocUnk = 0,
-    eJackGeoLocRear = 0x1, /* matches EPcxGeoLocation::eGeoLocRear */
-    eJackGeoLocFront,
-    eJackGeoLocLeft,
-    eJackGeoLocRight,
-    eJackGeoLocTop,
-    eJackGeoLocBottom,
-    eJackGeoLocRearPanel,
-    eJackGeoLocRiser,
-    eJackGeoLocInsideMobileLid,
-    eJackGeoLocDrivebay,
-    eJackGeoLocHDMI,
-    eJackGeoLocOutsideMobileLid,
-    eJackGeoLocATAPI,
-    eJackGeoLocReserved5,
-    eJackGeoLocReserved6,
-} 
-PaWasapiJackGeoLocation;
-
-
-/* Jack general location */
-typedef enum PaWasapiJackGenLocation
-{
-    eJackGenLocPrimaryBox = 0,
-    eJackGenLocInternal,
-    eJackGenLocSeparate,
-    eJackGenLocOther
-} 
-PaWasapiJackGenLocation;
-
-
-/* Jack's type of port */
-typedef enum PaWasapiJackPortConnection
-{
-    eJackPortConnJack = 0,
-    eJackPortConnIntegratedDevice,
-    eJackPortConnBothIntegratedAndJack,
-    eJackPortConnUnknown
-} 
-PaWasapiJackPortConnection;
-
-
-/* Thread priority */
-typedef enum PaWasapiThreadPriority
-{
-    eThreadPriorityNone = 0,
-    eThreadPriorityAudio,            //!< Default for Shared mode.
-    eThreadPriorityCapture,
-    eThreadPriorityDistribution,
-    eThreadPriorityGames,
-    eThreadPriorityPlayback,
-    eThreadPriorityProAudio,        //!< Default for Exclusive mode.
-    eThreadPriorityWindowManager
-}
-PaWasapiThreadPriority;
-
-
-/* Stream descriptor. */
-typedef struct PaWasapiJackDescription 
-{
-    unsigned long              channelMapping;
-    unsigned long              color; /* derived from macro: #define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) */
-    PaWasapiJackConnectionType connectionType;
-    PaWasapiJackGeoLocation    geoLocation;
-    PaWasapiJackGenLocation    genLocation;
-    PaWasapiJackPortConnection portConnection;
-    unsigned int               isConnected;
-}
-PaWasapiJackDescription;
-
-
-/* Stream descriptor. */
-typedef struct PaWasapiStreamInfo 
-{
-    unsigned long size;             /**< sizeof(PaWasapiStreamInfo) */
-    PaHostApiTypeId hostApiType;    /**< paWASAPI */
-    unsigned long version;          /**< 1 */
-
-    unsigned long flags;            /**< collection of PaWasapiFlags */
-
-    /* Support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
-       paWinWasapiUseChannelMask this allows you to specify which speakers 
-       to address in a multichannel stream. Constants for channelMask
-       are specified in pa_win_waveformat.h. Will be used only if 
-       paWinWasapiUseChannelMask flag is specified.
-    */
-    PaWinWaveFormatChannelMask channelMask;
-
-    /* Delivers raw data to callback obtained from GetBuffer() methods skipping 
-       internal PortAudio processing inventory completely. userData parameter will 
-       be the same that was passed to Pa_OpenStream method. Will be used only if 
-       paWinWasapiRedirectHostProcessor flag is specified.
-    */
-    PaWasapiHostProcessorCallback hostProcessorOutput;
-    PaWasapiHostProcessorCallback hostProcessorInput;
-
-    /* Specifies thread priority explicitly. Will be used only if paWinWasapiThreadPriority flag
-       is specified.
-
-       Please note, if Input/Output streams are opened simultaniously (Full-Duplex mode)
-       you shall specify same value for threadPriority or othervise one of the values will be used
-       to setup thread priority.
-    */
-    PaWasapiThreadPriority threadPriority;
-} 
-PaWasapiStreamInfo;
-
-
-/** Returns default sound format for device. Format is represented by PaWinWaveFormat or 
-    WAVEFORMATEXTENSIBLE structure.
-
- @param pFormat Pointer to PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure.
- @param nFormatSize Size of PaWinWaveFormat or WAVEFORMATEXTENSIBLE structure in bytes.
- @param nDevice Device index.
-
- @return Non-negative value indicating the number of bytes copied into format decriptor
-         or, a PaErrorCode (which are always negative) if PortAudio is not initialized
-         or an error is encountered.
-*/
-int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int nFormatSize, PaDeviceIndex nDevice );
-
-
-/** Returns device role (PaWasapiDeviceRole enum).
-
- @param nDevice device index.
-
- @return Non-negative value indicating device role or, a PaErrorCode (which are always negative)
-         if PortAudio is not initialized or an error is encountered.
-*/
-int/*PaWasapiDeviceRole*/ PaWasapi_GetDeviceRole( PaDeviceIndex nDevice );
-
-
-/** Boost thread priority of calling thread (MMCSS). Use it for Blocking Interface only for thread
-    which makes calls to Pa_WriteStream/Pa_ReadStream.
-
- @param hTask Handle to pointer to priority task. Must be used with PaWasapi_RevertThreadPriority
-              method to revert thread priority to initial state.
-
- @param nPriorityClass Id of thread priority of PaWasapiThreadPriority type. Specifying 
-                       eThreadPriorityNone does nothing.
-
- @return Error code indicating success or failure.
- @see    PaWasapi_RevertThreadPriority
-*/
-PaError PaWasapi_ThreadPriorityBoost( void **hTask, PaWasapiThreadPriority nPriorityClass );
-
-
-/** Boost thread priority of calling thread (MMCSS). Use it for Blocking Interface only for thread
-    which makes calls to Pa_WriteStream/Pa_ReadStream.
-
- @param  hTask Task handle obtained by PaWasapi_BoostThreadPriority method.
- @return Error code indicating success or failure.
- @see    PaWasapi_BoostThreadPriority
-*/
-PaError PaWasapi_ThreadPriorityRevert( void *hTask );
-
-
-/** Get number of frames per host buffer. This is maximal value of frames of WASAPI buffer which 
-    can be locked for operations. Use this method as helper to findout maximal values of 
-    inputFrames/outputFrames of PaWasapiHostProcessorCallback.
-
- @param  pStream Pointer to PaStream to query.
- @param  nInput  Pointer to variable to receive number of input frames. Can be NULL.
- @param  nOutput Pointer to variable to receive number of output frames. Can be NULL.
- @return Error code indicating success or failure.
- @see    PaWasapiHostProcessorCallback
-*/
-PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *nInput, unsigned int *nOutput );
-
-
-/** Get number of jacks associated with a WASAPI device.  Use this method to determine if
-    there are any jacks associated with the provided WASAPI device.  Not all audio devices
-	will support this capability.  This is valid for both input and output devices.
- @param  nDevice  device index.
- @param  jcount   Number of jacks is returned in this variable
- @return Error code indicating success or failure
- @see PaWasapi_GetJackDescription
- */
-PaError PaWasapi_GetJackCount(PaDeviceIndex nDevice, int *jcount);
-
-
-/** Get the jack description associated with a WASAPI device and jack number
-    Before this function is called, use PaWasapi_GetJackCount to determine the
-	number of jacks associated with device.  If jcount is greater than zero, then
-	each jack from 0 to jcount can be queried with this function to get the jack
-	description.
- @param  nDevice  device index.
- @param  jindex   Which jack to return information
- @param  KSJACK_DESCRIPTION This structure filled in on success.
- @return Error code indicating success or failure
- @see PaWasapi_GetJackCount
- */
-PaError PaWasapi_GetJackDescription(PaDeviceIndex nDevice, int jindex, PaWasapiJackDescription *pJackDescription);
-
-
-/*
-    IMPORTANT:
-
-    WASAPI is implemented for Callback and Blocking interfaces. It supports Shared and Exclusive
-    share modes. 
-    
-    Exclusive Mode:
-
-        Exclusive mode allows to deliver audio data directly to hardware bypassing
-        software mixing.
-        Exclusive mode is specified by 'paWinWasapiExclusive' flag.
-
-    Callback Interface:
-
-        Provides best audio quality with low latency. Callback interface is implemented in 
-        two versions:
-
-        1) Event-Driven:
-        This is the most powerful WASAPI implementation which provides glitch-free
-        audio at around 3ms latency in Exclusive mode. Lowest possible latency for this mode is 
-        3 ms for HD Audio class audio chips. For the Shared mode latency can not be 
-		lower than 20 ms.
-
-        2) Poll-Driven:
-        Polling is another 2-nd method to operate with WASAPI. It is less efficient than Event-Driven
-        and provides latency at around 10-13ms. Polling must be used to overcome a system bug
-        under Windows Vista x64 when application is WOW64(32-bit) and Event-Driven method simply 
-        times out (event handle is never signalled on buffer completion). Please note, such WOW64 bug 
-        does not exist in Vista x86 or Windows 7.
-        Polling can be setup by speciying 'paWinWasapiPolling' flag. Our WASAPI implementation detects
-        WOW64 bug and sets 'paWinWasapiPolling' automatically.
-
-    Thread priority:
-
-        Normally thread priority is set automatically and does not require modification. Although
-        if user wants some tweaking thread priority can be modified by setting 'paWinWasapiThreadPriority'
-        flag and specifying 'PaWasapiStreamInfo::threadPriority' with value from PaWasapiThreadPriority 
-        enum.
-
-    Blocking Interface:
-
-        Blocking interface is implemented but due to above described Poll-Driven method can not
-        deliver lowest possible latency. Specifying too low latency in Shared mode will result in 
-        distorted audio although Exclusive mode adds stability.
-
-    Pa_IsFormatSupported:
-
-        To check format with correct Share Mode (Exclusive/Shared) you must supply
-        PaWasapiStreamInfo with flags paWinWasapiExclusive set through member of 
-        PaStreamParameters::hostApiSpecificStreamInfo structure.
-
-    Pa_OpenStream:
-
-        To set desired Share Mode (Exclusive/Shared) you must supply
-        PaWasapiStreamInfo with flags paWinWasapiExclusive set through member of 
-        PaStreamParameters::hostApiSpecificStreamInfo structure.
-*/
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* PA_WIN_WASAPI_H */                                  
diff --git a/portaudio/include/pa_win_waveformat.h b/portaudio/include/pa_win_waveformat.h
deleted file mode 100644
index dce18c0d9..000000000
--- a/portaudio/include/pa_win_waveformat.h
+++ /dev/null
@@ -1,199 +0,0 @@
-#ifndef PA_WIN_WAVEFORMAT_H
-#define PA_WIN_WAVEFORMAT_H
-
-/*
- * PortAudio Portable Real-Time Audio Library
- * Windows WAVEFORMAT* data structure utilities
- * portaudio.h should be included before this file.
- *
- * Copyright (c) 2007 Ross Bencina
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/** @file
- @ingroup public_header
- @brief Windows specific PortAudio API extension and utilities header file.
-*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
-	The following #defines for speaker channel masks are the same
-	as those in ksmedia.h, except with PAWIN_ prepended, KSAUDIO_ removed
-	in some cases, and casts to PaWinWaveFormatChannelMask added.
-*/
-
-typedef unsigned long PaWinWaveFormatChannelMask;
-
-/* Speaker Positions: */
-#define PAWIN_SPEAKER_FRONT_LEFT				((PaWinWaveFormatChannelMask)0x1)
-#define PAWIN_SPEAKER_FRONT_RIGHT				((PaWinWaveFormatChannelMask)0x2)
-#define PAWIN_SPEAKER_FRONT_CENTER				((PaWinWaveFormatChannelMask)0x4)
-#define PAWIN_SPEAKER_LOW_FREQUENCY				((PaWinWaveFormatChannelMask)0x8)
-#define PAWIN_SPEAKER_BACK_LEFT					((PaWinWaveFormatChannelMask)0x10)
-#define PAWIN_SPEAKER_BACK_RIGHT				((PaWinWaveFormatChannelMask)0x20)
-#define PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER		((PaWinWaveFormatChannelMask)0x40)
-#define PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER		((PaWinWaveFormatChannelMask)0x80)
-#define PAWIN_SPEAKER_BACK_CENTER				((PaWinWaveFormatChannelMask)0x100)
-#define PAWIN_SPEAKER_SIDE_LEFT					((PaWinWaveFormatChannelMask)0x200)
-#define PAWIN_SPEAKER_SIDE_RIGHT				((PaWinWaveFormatChannelMask)0x400)
-#define PAWIN_SPEAKER_TOP_CENTER				((PaWinWaveFormatChannelMask)0x800)
-#define PAWIN_SPEAKER_TOP_FRONT_LEFT			((PaWinWaveFormatChannelMask)0x1000)
-#define PAWIN_SPEAKER_TOP_FRONT_CENTER			((PaWinWaveFormatChannelMask)0x2000)
-#define PAWIN_SPEAKER_TOP_FRONT_RIGHT			((PaWinWaveFormatChannelMask)0x4000)
-#define PAWIN_SPEAKER_TOP_BACK_LEFT				((PaWinWaveFormatChannelMask)0x8000)
-#define PAWIN_SPEAKER_TOP_BACK_CENTER			((PaWinWaveFormatChannelMask)0x10000)
-#define PAWIN_SPEAKER_TOP_BACK_RIGHT			((PaWinWaveFormatChannelMask)0x20000)
-
-/* Bit mask locations reserved for future use */
-#define PAWIN_SPEAKER_RESERVED					((PaWinWaveFormatChannelMask)0x7FFC0000)
-
-/* Used to specify that any possible permutation of speaker configurations */
-#define PAWIN_SPEAKER_ALL						((PaWinWaveFormatChannelMask)0x80000000)
-
-/* DirectSound Speaker Config */
-#define PAWIN_SPEAKER_DIRECTOUT					0
-#define PAWIN_SPEAKER_MONO						(PAWIN_SPEAKER_FRONT_CENTER)
-#define PAWIN_SPEAKER_STEREO					(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT)
-#define PAWIN_SPEAKER_QUAD						(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
-												PAWIN_SPEAKER_BACK_LEFT  | PAWIN_SPEAKER_BACK_RIGHT)
-#define PAWIN_SPEAKER_SURROUND					(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
-												PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_BACK_CENTER)
-#define PAWIN_SPEAKER_5POINT1					(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
-												PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
-												PAWIN_SPEAKER_BACK_LEFT  | PAWIN_SPEAKER_BACK_RIGHT)
-#define PAWIN_SPEAKER_7POINT1					(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
-												PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
-												PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \
-												PAWIN_SPEAKER_FRONT_LEFT_OF_CENTER | PAWIN_SPEAKER_FRONT_RIGHT_OF_CENTER)
-#define PAWIN_SPEAKER_5POINT1_SURROUND			(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
-												PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
-												PAWIN_SPEAKER_SIDE_LEFT  | PAWIN_SPEAKER_SIDE_RIGHT)
-#define PAWIN_SPEAKER_7POINT1_SURROUND			(PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_RIGHT | \
-												PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_LOW_FREQUENCY | \
-												PAWIN_SPEAKER_BACK_LEFT | PAWIN_SPEAKER_BACK_RIGHT | \
-												PAWIN_SPEAKER_SIDE_LEFT | PAWIN_SPEAKER_SIDE_RIGHT)
-/*
- According to the Microsoft documentation:
- The following are obsolete 5.1 and 7.1 settings (they lack side speakers).  Note this means
- that the default 5.1 and 7.1 settings (KSAUDIO_SPEAKER_5POINT1 and KSAUDIO_SPEAKER_7POINT1 are
- similarly obsolete but are unchanged for compatibility reasons).
-*/
-#define PAWIN_SPEAKER_5POINT1_BACK				PAWIN_SPEAKER_5POINT1
-#define PAWIN_SPEAKER_7POINT1_WIDE				PAWIN_SPEAKER_7POINT1
-
-/* DVD Speaker Positions */
-#define PAWIN_SPEAKER_GROUND_FRONT_LEFT			PAWIN_SPEAKER_FRONT_LEFT
-#define PAWIN_SPEAKER_GROUND_FRONT_CENTER		PAWIN_SPEAKER_FRONT_CENTER
-#define PAWIN_SPEAKER_GROUND_FRONT_RIGHT		PAWIN_SPEAKER_FRONT_RIGHT
-#define PAWIN_SPEAKER_GROUND_REAR_LEFT			PAWIN_SPEAKER_BACK_LEFT
-#define PAWIN_SPEAKER_GROUND_REAR_RIGHT			PAWIN_SPEAKER_BACK_RIGHT
-#define PAWIN_SPEAKER_TOP_MIDDLE				PAWIN_SPEAKER_TOP_CENTER
-#define PAWIN_SPEAKER_SUPER_WOOFER				PAWIN_SPEAKER_LOW_FREQUENCY
-
-
-/*
-	PaWinWaveFormat is defined here to provide compatibility with
-	compilation environments which don't have headers defining 
-	WAVEFORMATEXTENSIBLE (e.g. older versions of MSVC, Borland C++ etc.
-
-	The fields for WAVEFORMATEX and WAVEFORMATEXTENSIBLE are declared as an
-    unsigned char array here to avoid clients who include this file having 
-    a dependency on windows.h and mmsystem.h, and also to to avoid having
-    to write separate packing pragmas for each compiler.
-*/
-#define PAWIN_SIZEOF_WAVEFORMATEX   18
-#define PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE (PAWIN_SIZEOF_WAVEFORMATEX + 22)
-
-typedef struct{
-    unsigned char fields[ PAWIN_SIZEOF_WAVEFORMATEXTENSIBLE ];
-    unsigned long extraLongForAlignment; /* ensure that compiler aligns struct to DWORD */ 
-} PaWinWaveFormat;
-
-/*
-    WAVEFORMATEXTENSIBLE fields:
-    
-    union  {
-	    WORD  wValidBitsPerSample;    
-	    WORD  wSamplesPerBlock;    
-	    WORD  wReserved;  
-    } Samples;
-    DWORD  dwChannelMask;  
-    GUID  SubFormat;
-*/
-
-#define PAWIN_INDEXOF_WVALIDBITSPERSAMPLE	(PAWIN_SIZEOF_WAVEFORMATEX+0)
-#define PAWIN_INDEXOF_DWCHANNELMASK			(PAWIN_SIZEOF_WAVEFORMATEX+2)
-#define PAWIN_INDEXOF_SUBFORMAT				(PAWIN_SIZEOF_WAVEFORMATEX+6)
-
-
-/*
-    Valid values to pass for the waveFormatTag PaWin_InitializeWaveFormatEx and
-    PaWin_InitializeWaveFormatExtensible functions below. These must match
-    the standard Windows WAVE_FORMAT_* values.
-*/
-#define PAWIN_WAVE_FORMAT_PCM               (1)
-#define PAWIN_WAVE_FORMAT_IEEE_FLOAT        (3)
-#define PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF   (0x0092)
-#define PAWIN_WAVE_FORMAT_WMA_SPDIF         (0x0164)
-
-
-/*
-    returns PAWIN_WAVE_FORMAT_PCM or PAWIN_WAVE_FORMAT_IEEE_FLOAT
-    depending on the sampleFormat parameter.
-*/
-int PaWin_SampleFormatToLinearWaveFormatTag( PaSampleFormat sampleFormat );
-
-/*
-	Use the following two functions to initialize the waveformat structure.
-*/
-
-void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat, 
-		int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate );
-
-
-void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat, 
-		int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate,
-	    PaWinWaveFormatChannelMask channelMask );
-
-
-/* Map a channel count to a speaker channel mask */
-PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels );
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* PA_WIN_WAVEFORMAT_H */
\ No newline at end of file
diff --git a/portaudio/include/pa_win_wmme.h b/portaudio/include/pa_win_wmme.h
index deffd1006..2e90233a3 100644
--- a/portaudio/include/pa_win_wmme.h
+++ b/portaudio/include/pa_win_wmme.h
@@ -1,7 +1,7 @@
 #ifndef PA_WIN_WMME_H
 #define PA_WIN_WMME_H
 /*
- * $Id: pa_win_wmme.h 1405 2009-03-08 08:10:55Z rossb $
+ * $Id: pa_win_wmme.h 1115 2006-09-06 15:39:48Z rossb $
  * PortAudio Portable Real-Time Audio Library
  * MME specific extensions
  *
@@ -39,13 +39,11 @@
  */
 
 /** @file
- @ingroup public_header
  @brief WMME-specific PortAudio API extension header file.
 */
 
 
 #include "portaudio.h"
-#include "pa_win_waveformat.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -53,13 +51,9 @@ extern "C"
 #endif /* __cplusplus */
 
 
-/* The following are flags which can be set in 
-  PaWinMmeStreamInfo's flags field.
-*/
-
 #define paWinMmeUseLowLevelLatencyParameters            (0x01)
 #define paWinMmeUseMultipleDevices                      (0x02)  /* use mme specific multiple device feature */
-#define paWinMmeUseChannelMask                          (0x04)
+
 
 /* By default, the mme implementation drops the processing thread's priority
     to THREAD_PRIORITY_NORMAL and sleeps the thread if the CPU load exceeds 100%
@@ -68,11 +62,6 @@ extern "C"
 */
 #define paWinMmeDontThrottleOverloadedProcessingThread  (0x08)
 
-/*  Flags for non-PCM spdif passthrough.
-*/
-#define paWinMmeWaveFormatDolbyAc3Spdif                 (0x10)
-#define paWinMmeWaveFormatWmaSpdif                      (0x20)
-
 
 typedef struct PaWinMmeDeviceAndChannelCount{
     PaDeviceIndex device;
@@ -117,15 +106,6 @@ typedef struct PaWinMmeStreamInfo{
     PaWinMmeDeviceAndChannelCount *devices;
     unsigned long deviceCount;
 
-    /*
-        support for WAVEFORMATEXTENSIBLE channel masks. If flags contains
-        paWinMmeUseChannelMask this allows you to specify which speakers 
-        to address in a multichannel stream. Constants for channelMask
-        are specified in pa_win_waveformat.h
-
-    */
-    PaWinWaveFormatChannelMask channelMask;
-
 }PaWinMmeStreamInfo;
 
 
diff --git a/portaudio/include/portaudio.h b/portaudio/include/portaudio.h
index 89964ab3e..67fa2ea40 100644
--- a/portaudio/include/portaudio.h
+++ b/portaudio/include/portaudio.h
@@ -1,7 +1,8 @@
+
 #ifndef PORTAUDIO_H
 #define PORTAUDIO_H
 /*
- * $Id: portaudio.h 1337 2008-02-15 07:32:09Z rossb $
+ * $Id: portaudio.h 1195 2007-04-22 17:34:45Z aknudsen $
  * PortAudio Portable Real-Time Audio Library
  * PortAudio API Header File
  * Latest version available at: http://www.portaudio.com/
@@ -40,8 +41,7 @@
  */
 
 /** @file
- @ingroup public_header
- @brief The portable PortAudio API.
+ @brief The PortAudio API.
 */
 
 
diff --git a/portaudio/src/common/pa_allocation.h b/portaudio/src/common/pa_allocation.h
index 811dd72e0..b265b016f 100644
--- a/portaudio/src/common/pa_allocation.h
+++ b/portaudio/src/common/pa_allocation.h
@@ -1,12 +1,12 @@
 #ifndef PA_ALLOCATION_H
 #define PA_ALLOCATION_H
 /*
- * $Id: pa_allocation.h 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_allocation.h 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library allocation context header
  * memory allocation context for tracking allocation groups
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -43,12 +43,12 @@
  @ingroup common_src
 
  @brief Allocation Group prototypes. An Allocation Group makes it easy to
- allocate multiple blocks of memory and free them all at once.
+ allocate multiple blocks of memory and free them all simultanously.
  
  An allocation group is useful for keeping track of multiple blocks
  of memory which are allocated at the same time (such as during initialization)
  and need to be deallocated at the same time. The allocation group maintains
- a list of allocated blocks, and can free all allocations at once. This
+ a list of allocated blocks, and can deallocate them all simultaneously which
  can be usefull for cleaning up after a partially initialized object fails.
 
  The allocation group implementation is built on top of the lower
diff --git a/portaudio/src/common/pa_converters.c b/portaudio/src/common/pa_converters.c
index 009149c68..3b98c858a 100644
--- a/portaudio/src/common/pa_converters.c
+++ b/portaudio/src/common/pa_converters.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_converters.c 1495 2010-04-17 07:43:00Z dmitrykos $
+ * $Id: pa_converters.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library sample conversion mechanism
  *
  * Based on the Open Source API proposed by Ross Bencina
@@ -39,7 +39,7 @@
 /** @file
  @ingroup common_src
 
- @brief Conversion function implementations.
+ @brief Conversion functions implementations.
  
  If the C9x function lrintf() is available, define PA_USE_C99_LRINTF to use it
 
@@ -1073,13 +1073,13 @@ static void Int24_To_Float32(
     {
 
 #if defined(PA_LITTLE_ENDIAN)
-        temp = (((PaInt32)src[0]) << 8);  
-        temp = temp | (((PaInt32)src[1]) << 16);
-        temp = temp | (((PaInt32)src[2]) << 24);
+        temp = (((long)src[0]) << 8);  
+        temp = temp | (((long)src[1]) << 16);
+        temp = temp | (((long)src[2]) << 24);
 #elif defined(PA_BIG_ENDIAN)
-        temp = (((PaInt32)src[0]) << 24);
-        temp = temp | (((PaInt32)src[1]) << 16);
-        temp = temp | (((PaInt32)src[2]) << 8);
+        temp = (((long)src[0]) << 24);
+        temp = temp | (((long)src[1]) << 16);
+        temp = temp | (((long)src[2]) << 8);
 #endif
 
         *dest = (float) ((double)temp * const_1_div_2147483648_);
@@ -1106,13 +1106,13 @@ static void Int24_To_Int32(
     {
 
 #if defined(PA_LITTLE_ENDIAN)
-        temp = (((PaInt32)src[0]) << 8);  
-        temp = temp | (((PaInt32)src[1]) << 16);
-        temp = temp | (((PaInt32)src[2]) << 24);
+        temp = (((long)src[0]) << 8);  
+        temp = temp | (((long)src[1]) << 16);
+        temp = temp | (((long)src[2]) << 24);
 #elif defined(PA_BIG_ENDIAN)
-        temp = (((PaInt32)src[0]) << 24);
-        temp = temp | (((PaInt32)src[1]) << 16);
-        temp = temp | (((PaInt32)src[2]) << 8);
+        temp = (((long)src[0]) << 24);
+        temp = temp | (((long)src[1]) << 16);
+        temp = temp | (((long)src[2]) << 8);
 #endif
 
         *dest = temp;
@@ -1163,39 +1163,15 @@ static void Int24_To_Int16_Dither(
     void *sourceBuffer, signed int sourceStride,
     unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )
 {
-	#define _PA_CNV_RESCALE(__max_from,__max_to,g) ((1.0f/(float)(__max_from/2+1))*((float)((__max_to/2+1)+g)))
-#ifndef PA_BIG_ENDIAN
-	#define _PA_INT24_TO_INT32(v)   ((int)(((int)v[2] << 24)|((int)v[1] << 16)|((int)v[0] << 8)) >> 8)
-#else
-	#define _PA_INT24_TO_INT32(v)   ((int)(((int)v[0] << 24)|((int)v[1] << 16)|((int)v[2] << 8)) >> 8)
-#endif
-	#define _PA_INT24_TO_FLOAT(v,g) ((float)(_PA_INT24_TO_INT32(v)) * _PA_CNV_RESCALE(0xffffff,0xffff,g))
-
-    unsigned char *src = (unsigned char *)sourceBuffer;
-    PaInt16 *dest = (PaInt16 *)destinationBuffer;
-	float dither, dithered;
-
-    while( count-- )
-    {
-        dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
-
-		/* downscale 24-bit int to 16-bit int placed into 32-bit float container, 
-		   16-bit scaler is decreased by 2 to leave space for dither in order not to overflow
-		*/
-		dithered = _PA_INT24_TO_FLOAT(src, -2.0f) + dither;
-
-#ifdef PA_USE_C99_LRINTF
-        *dest = lrintf(dithered-0.5f);
-#else
-        *dest = (PaInt16) dithered;
-#endif
-
-        src += sourceStride * 3;
-        dest += destinationStride;
-    }
+    (void) destinationBuffer; /* unused parameters */
+    (void) destinationStride; /* unused parameters */
+    (void) sourceBuffer; /* unused parameters */
+    (void) sourceStride; /* unused parameters */
+    (void) count; /* unused parameters */
+    (void) ditherGenerator; /* unused parameters */
+    /* IMPLEMENT ME */
 }
 
-
 /* -------------------------------------------------------------------------- */
 
 static void Int24_To_Int8(
diff --git a/portaudio/src/common/pa_debugprint.c b/portaudio/src/common/pa_debugprint.c
index 7ee8f7f23..33fcf32e7 100644
--- a/portaudio/src/common/pa_debugprint.c
+++ b/portaudio/src/common/pa_debugprint.c
@@ -53,21 +53,17 @@
     @todo Consider reentrancy and possibly corrupted strdump buffer.
 */
 
+
 #include <stdio.h>
 #include <stdarg.h>
 
 #include "pa_debugprint.h"
 
-// for OutputDebugStringA
-#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
-	#define WIN32_LEAN_AND_MEAN // exclude rare headers
-	#include "windows.h"
-#endif
 
-// User callback
-static PaUtilLogCallback userCB = NULL;
 
-// Sets user callback
+static PaUtilLogCallback userCB=0;
+
+
 void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)
 {
     userCB = cb;
@@ -76,51 +72,36 @@ void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)
 /*
  If your platform doesn’t have vsnprintf, you are stuck with a
  VERY dangerous alternative, vsprintf (with no n)
-*/
-#if _MSC_VER
-	/* Some Windows Mobile SDKs don't define vsnprintf but all define _vsnprintf (hopefully).
-	   According to MSDN "vsnprintf is identical to _vsnprintf". So we use _vsnprintf with MSC.
-	*/
-	#define VSNPRINTF  _vsnprintf 
+ */
+
+#if (_MSC_VER) && (_MSC_VER < 1400)
+#define VSNPRINTF  _vsnprintf
 #else
-	#define VSNPRINTF  vsnprintf
+#define VSNPRINTF  vsnprintf
 #endif
 
-#define PA_LOG_BUF_SIZE 2048
+#define SIZEDUMP 1024
+
+static char strdump[SIZEDUMP];
 
 void PaUtil_DebugPrint( const char *format, ... )
 {
-	// Optional logging into Output console of Visual Studio
-#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
-	{
-		char buf[PA_LOG_BUF_SIZE];
-		va_list ap;
-		va_start(ap, format);
-		VSNPRINTF(buf, sizeof(buf), format, ap);
-		buf[sizeof(buf)-1] = 0;
-		OutputDebugStringA(buf);
-		va_end(ap);
-	}
-#endif
 
-	// Output to User-Callback
-    if (userCB != NULL)
+    if (userCB)
     {
-        char strdump[PA_LOG_BUF_SIZE];
         va_list ap;
-        va_start(ap, format);
-        VSNPRINTF(strdump, sizeof(strdump), format, ap);
-        strdump[sizeof(strdump)-1] = 0;
+        va_start( ap, format );
+        VSNPRINTF( strdump, SIZEDUMP, format, ap );
         userCB(strdump);
-        va_end(ap);
+        va_end( ap ); 
     }
     else
-	// Standard output to stderr
     {
         va_list ap;
-        va_start(ap, format);
-        vfprintf(stderr, format, ap);
-        va_end(ap);
-        fflush(stderr);
+        va_start( ap, format );
+        vfprintf( stderr, format, ap );
+        va_end( ap );
+        fflush( stderr );
     }
+
 }
diff --git a/portaudio/src/common/pa_dither.c b/portaudio/src/common/pa_dither.c
index 7a1b13125..6f6c9a1a6 100644
--- a/portaudio/src/common/pa_dither.c
+++ b/portaudio/src/common/pa_dither.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_dither.c 1418 2009-10-12 21:00:53Z philburk $
+ * $Id: pa_dither.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library triangular dither generator
  *
  * Based on the Open Source API proposed by Ross Bencina
@@ -42,14 +42,9 @@
  @brief Functions for generating dither noise
 */
 
-#include "pa_types.h"
-#include "pa_dither.h"
-
 
-/* Note that the linear congruential algorithm requires 32 bit integers
- * because it uses arithmetic overflow. So use PaUint32 instead of
- * unsigned long so it will work on 64 bit systems.
- */
+#include "pa_dither.h"
+#include "pa_types.h"
 
 #define PA_DITHER_BITS_   (15)
 
@@ -62,9 +57,9 @@ void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *st
 }
 
 
-PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state )
+signed long PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state )
 {
-    PaInt32 current, highPass;
+    signed long current, highPass;
 
     /* Generate two random numbers. */
     state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;
@@ -74,10 +69,9 @@ PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *s
      * Shift before adding to prevent overflow which would skew the distribution.
      * Also shift an extra bit for the high pass filter. 
      */
-#define DITHER_SHIFT_  ((sizeof(PaInt32)*8 - PA_DITHER_BITS_) + 1)
-	
-    current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) +
-              (((PaInt32)state->randSeed2)>>DITHER_SHIFT_);
+#define DITHER_SHIFT_  ((SIZEOF_LONG*8 - PA_DITHER_BITS_) + 1)
+    current = (((signed long)state->randSeed1)>>DITHER_SHIFT_) +
+              (((signed long)state->randSeed2)>>DITHER_SHIFT_);
 
     /* High pass filter to reduce audibility. */
     highPass = current - state->previous;
@@ -92,7 +86,7 @@ static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;
 
 float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *state )
 {
-    PaInt32 current, highPass;
+    signed long current, highPass;
 
     /* Generate two random numbers. */
     state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;
@@ -102,8 +96,9 @@ float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *sta
      * Shift before adding to prevent overflow which would skew the distribution.
      * Also shift an extra bit for the high pass filter. 
      */
-    current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) +
-              (((PaInt32)state->randSeed2)>>DITHER_SHIFT_);
+#define DITHER_SHIFT_  ((SIZEOF_LONG*8 - PA_DITHER_BITS_) + 1)
+    current = (((signed long)state->randSeed1)>>DITHER_SHIFT_) +
+              (((signed long)state->randSeed2)>>DITHER_SHIFT_);
 
     /* High pass filter to reduce audibility. */
     highPass = current - state->previous;
diff --git a/portaudio/src/common/pa_dither.h b/portaudio/src/common/pa_dither.h
index a5131b27f..e77ce470d 100644
--- a/portaudio/src/common/pa_dither.h
+++ b/portaudio/src/common/pa_dither.h
@@ -1,7 +1,7 @@
 #ifndef PA_DITHER_H
 #define PA_DITHER_H
 /*
- * $Id: pa_dither.h 1418 2009-10-12 21:00:53Z philburk $
+ * $Id: pa_dither.h 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library triangular dither generator
  *
  * Based on the Open Source API proposed by Ross Bencina
@@ -44,24 +44,18 @@
  @brief Functions for generating dither noise
 */
 
-#include "pa_types.h"
-
 
 #ifdef __cplusplus
 extern "C"
 {
 #endif /* __cplusplus */
 
-/* Note that the linear congruential algorithm requires 32 bit integers
- * because it uses arithmetic overflow. So use PaUint32 instead of
- * unsigned long so it will work on 64 bit systems.
- */
 
 /** @brief State needed to generate a dither signal */
 typedef struct PaUtilTriangularDitherGenerator{
-    PaUint32 previous;
-    PaUint32 randSeed1;
-    PaUint32 randSeed2;
+    unsigned long previous;
+    unsigned long randSeed1;
+    unsigned long randSeed2;
 } PaUtilTriangularDitherGenerator;
 
 
@@ -79,9 +73,9 @@ void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *di
     signed short out = (signed short)(((in>>1) + dither) >> 15);
 </pre>
  @return
- A signed 32-bit integer with a range of +32767 to -32768
+ A signed long with a range of +32767 to -32768
 */
-PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *ditherState );
+signed long PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *ditherState );
 
 
 /**
diff --git a/portaudio/src/common/pa_endianness.h b/portaudio/src/common/pa_endianness.h
index 84e904ca7..bdcc74f79 100644
--- a/portaudio/src/common/pa_endianness.h
+++ b/portaudio/src/common/pa_endianness.h
@@ -1,7 +1,7 @@
 #ifndef PA_ENDIANNESS_H
 #define PA_ENDIANNESS_H
 /*
- * $Id: pa_endianness.h 1324 2008-01-27 02:03:30Z bjornroche $
+ * $Id: pa_endianness.h 1216 2007-06-10 09:26:00Z aknudsen $
  * Portable Audio I/O Library current platform endianness macros
  *
  * Based on the Open Source API proposed by Ross Bencina
@@ -120,22 +120,18 @@ extern "C"
  and raises an assertion if they don't match. <assert.h> must be included in
  the context in which this macro is used.
 */
-#if defined(NDEBUG)
-    #define PA_VALIDATE_ENDIANNESS
-#else
-    #if defined(PA_LITTLE_ENDIAN)
-        #define PA_VALIDATE_ENDIANNESS \
-        { \
-            const long nativeOne = 1; \
-            assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 1 ); \
-        }
-    #elif defined(PA_BIG_ENDIAN)
-        #define PA_VALIDATE_ENDIANNESS \
-        { \
-            const long nativeOne = 1; \
-            assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 0 ); \
-        }
-    #endif
+#if defined(PA_LITTLE_ENDIAN)
+    #define PA_VALIDATE_ENDIANNESS \
+    { \
+        const long nativeOne = 1; \
+        assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 1 ); \
+    }
+#elif defined(PA_BIG_ENDIAN)
+    #define PA_VALIDATE_ENDIANNESS \
+    { \
+        const long nativeOne = 1; \
+        assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 0 ); \
+    }
 #endif
 
 
diff --git a/portaudio/src/common/pa_front.c b/portaudio/src/common/pa_front.c
index 28f0c60e8..5af90d45c 100644
--- a/portaudio/src/common/pa_front.c
+++ b/portaudio/src/common/pa_front.c
@@ -1,10 +1,10 @@
 /*
- * $Id: pa_front.c 1396 2008-11-03 19:31:30Z philburk $
+ * $Id: pa_front.c 1229 2007-06-15 16:11:11Z rossb $
  * Portable Audio I/O Library Multi-Host API front end
  * Validate function parameters and manage multiple host APIs.
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -40,20 +40,17 @@
 /** @file
  @ingroup common_src
 
- @brief Implements PortAudio API functions defined in portaudio.h, checks 
- some errors, delegates platform-specific behavior to host API implementations.
+ @brief Implements public PortAudio API, checks some errors, forwards to
+ host API implementations.
  
- Implements the functions defined in the PortAudio API (portaudio.h), 
- validates some parameters and checks for state inconsistencies before 
- forwarding API requests to specific Host API implementations (via the 
- interface declared in pa_hostapi.h), and Streams (via the interface 
- declared in pa_stream.h).
+ Implements the functions defined in the PortAudio API, checks for
+ some parameter and state inconsistencies and forwards API requests to
+ specific Host API implementations (via the interface declared in
+ pa_hostapi.h), and Streams (via the interface declared in pa_stream.h).
 
- This file manages initialization and termination of Host API
- implementations via initializer functions stored in the paHostApiInitializers
- global array (usually defined in an os-specific pa_[os]_hostapis.c file).
-
- This file maintains a list of all open streams and closes them at Pa_Terminate().
+ This file handles initialization and termination of Host API
+ implementations via initializers stored in the paHostApiInitializers
+ global variable.
 
  Some utility functions declared in pa_util.h are implemented in this file.
 
@@ -90,7 +87,7 @@
 
 
 #define PA_VERSION_  1899
-#define PA_VERSION_TEXT_ "PortAudio V19-devel (built " __DATE__  " " __TIME__ ")"
+#define PA_VERSION_TEXT_ "PortAudio V19-devel (built " __DATE__  ")"
 
 
 
@@ -408,8 +405,6 @@ const char *Pa_GetErrorText( PaError errorCode )
     case paCanNotWriteToACallbackStream:        result = "Can't write to a callback stream"; break;
     case paCanNotReadFromAnOutputOnlyStream:    result = "Can't read from an output only stream"; break;
     case paCanNotWriteToAnInputOnlyStream:      result = "Can't write to an input only stream"; break;
-    case paIncompatibleStreamHostApi: result = "Incompatible stream host API"; break;
-    case paBadBufferPtr:             result = "Bad buffer pointer"; break;
     default:                         
 		if( errorCode > 0 )
 			result = "Invalid error code (value greater than zero)"; 
@@ -1506,7 +1501,7 @@ const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream )
         result = 0;
 
         PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));
-        PA_LOGAPI(("\tconst PaStreamInfo*: 0 [PaError error:%d ( %s )]\n", error, Pa_GetErrorText( error ) ));
+        PA_LOGAPI(("\tconst PaStreamInfo*: 0 [PaError error:%d ( %s )]\n", result, error, Pa_GetErrorText( error ) ));
 
     }
     else
diff --git a/portaudio/src/common/pa_hostapi.h b/portaudio/src/common/pa_hostapi.h
index 5462d4439..5a86d4e94 100644
--- a/portaudio/src/common/pa_hostapi.h
+++ b/portaudio/src/common/pa_hostapi.h
@@ -1,12 +1,12 @@
 #ifndef PA_HOSTAPI_H
 #define PA_HOSTAPI_H
 /*
- * $Id: pa_hostapi.h 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_hostapi.h 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library
  * host api representation
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -42,8 +42,8 @@
 /** @file
  @ingroup common_src
 
- @brief Interfaces and representation structures used by pa_front.c 
- to manage and communicate with host API implementations.
+ @brief Interface used by pa_front to virtualize functions which operate on
+ host APIs.
 */
 
 
@@ -224,19 +224,13 @@ typedef struct PaUtilHostApiRepresentation {
 /** Prototype for the initialization function which must be implemented by every
  host API.
  
- This function should only return an error other than paNoError if it encounters 
- an unexpected and fatal error (memory allocation error for example). In general, 
- there may be conditions under which it returns a NULL interface pointer and also 
- returns paNoError. For example, if the ASIO implementation detects that ASIO is 
- not installed, it should return a NULL interface, and paNoError.
-
  @see paHostApiInitializers
 */
 typedef PaError PaUtilHostApiInitializer( PaUtilHostApiRepresentation**, PaHostApiIndex );
 
 
 /** paHostApiInitializers is a NULL-terminated array of host API initialization
- functions. These functions are called by pa_front.c to initialize the host APIs
+ functions. These functions are called by pa_front to initialize the host APIs
  when the client calls Pa_Initialize().
 
  There is a platform specific file which defines paHostApiInitializers for that
diff --git a/portaudio/src/common/pa_memorybarrier.h b/portaudio/src/common/pa_memorybarrier.h
deleted file mode 100644
index f68962220..000000000
--- a/portaudio/src/common/pa_memorybarrier.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * $Id: pa_memorybarrier.h 1240 2007-07-17 13:05:07Z bjornroche $
- * Portable Audio I/O Library
- * Memory barrier utilities
- *
- * Author: Bjorn Roche, XO Audio, LLC
- *
- * This program uses the PortAudio Portable Audio Library.
- * For more information see: http://www.portaudio.com
- * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/**
- @file pa_memorybarrier.h
- @ingroup common_src
-*/
-
-/****************
- * Some memory barrier primitives based on the system.
- * right now only OS X, FreeBSD, and Linux are supported. In addition to providing
- * memory barriers, these functions should ensure that data cached in registers
- * is written out to cache where it can be snooped by other CPUs. (ie, the volatile
- * keyword should not be required)
- *
- * the primitives that must be defined are:
- *
- * PaUtil_FullMemoryBarrier()
- * PaUtil_ReadMemoryBarrier()
- * PaUtil_WriteMemoryBarrier()
- *
- ****************/
-
-#if defined(__APPLE__)
-#   include <libkern/OSAtomic.h>
-    /* Here are the memory barrier functions. Mac OS X only provides
-       full memory barriers, so the three types of barriers are the same,
-       however, these barriers are superior to compiler-based ones. */
-#   define PaUtil_FullMemoryBarrier()  OSMemoryBarrier()
-#   define PaUtil_ReadMemoryBarrier()  OSMemoryBarrier()
-#   define PaUtil_WriteMemoryBarrier() OSMemoryBarrier()
-#elif defined(__GNUC__)
-    /* GCC >= 4.1 has built-in intrinsics. We'll use those */
-#   if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
-#      define PaUtil_FullMemoryBarrier()  __sync_synchronize()
-#      define PaUtil_ReadMemoryBarrier()  __sync_synchronize()
-#      define PaUtil_WriteMemoryBarrier() __sync_synchronize()
-    /* as a fallback, GCC understands volatile asm and "memory" to mean it
-     * should not reorder memory read/writes */
-    /* Note that it is not clear that any compiler actually defines __PPC__,
-     * it can probably removed safely. */
-#   elif defined( __ppc__ ) || defined( __powerpc__) || defined( __PPC__ )
-#      define PaUtil_FullMemoryBarrier()  asm volatile("sync":::"memory")
-#      define PaUtil_ReadMemoryBarrier()  asm volatile("sync":::"memory")
-#      define PaUtil_WriteMemoryBarrier() asm volatile("sync":::"memory")
-#   elif defined( __i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \
-         defined( __i686__ ) || defined( __x86_64__ )
-#      define PaUtil_FullMemoryBarrier()  asm volatile("mfence":::"memory")
-#      define PaUtil_ReadMemoryBarrier()  asm volatile("lfence":::"memory")
-#      define PaUtil_WriteMemoryBarrier() asm volatile("sfence":::"memory")
-#   else
-#      ifdef ALLOW_SMP_DANGERS
-#         warning Memory barriers not defined on this system or system unknown
-#         warning For SMP safety, you should fix this.
-#         define PaUtil_FullMemoryBarrier()
-#         define PaUtil_ReadMemoryBarrier()
-#         define PaUtil_WriteMemoryBarrier()
-#      else
-#         error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
-#      endif
-#   endif
-#elif (_MSC_VER >= 1400) && !defined(_WIN32_WCE)
-#   include <intrin.h>
-#   pragma intrinsic(_ReadWriteBarrier)
-#   pragma intrinsic(_ReadBarrier)
-#   pragma intrinsic(_WriteBarrier)
-#   define PaUtil_FullMemoryBarrier()  _ReadWriteBarrier()
-#   define PaUtil_ReadMemoryBarrier()  _ReadBarrier()
-#   define PaUtil_WriteMemoryBarrier() _WriteBarrier()
-#elif defined(_WIN32_WCE)
-#   define PaUtil_FullMemoryBarrier()
-#   define PaUtil_ReadMemoryBarrier()
-#   define PaUtil_WriteMemoryBarrier()
-#elif defined(_MSC_VER) || defined(__BORLANDC__)
-#   define PaUtil_FullMemoryBarrier()  _asm { lock add    [esp], 0 }
-#   define PaUtil_ReadMemoryBarrier()  _asm { lock add    [esp], 0 }
-#   define PaUtil_WriteMemoryBarrier() _asm { lock add    [esp], 0 }
-#else
-#   ifdef ALLOW_SMP_DANGERS
-#      warning Memory barriers not defined on this system or system unknown
-#      warning For SMP safety, you should fix this.
-#      define PaUtil_FullMemoryBarrier()
-#      define PaUtil_ReadMemoryBarrier()
-#      define PaUtil_WriteMemoryBarrier()
-#   else
-#      error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
-#   endif
-#endif
diff --git a/portaudio/src/common/pa_process.c b/portaudio/src/common/pa_process.c
index e176670aa..fac474d55 100644
--- a/portaudio/src/common/pa_process.c
+++ b/portaudio/src/common/pa_process.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_process.c 1523 2010-07-10 17:41:25Z dmitrykos $
+ * $Id: pa_process.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library
  * streamCallback <-> host buffer processing adapter
  *
@@ -56,6 +56,8 @@
 
     @todo Consider cache tilings for intereave<->deinterleave.
 
+    @todo implement timeInfo->currentTime int PaUtil_BeginBufferProcessing()
+
     @todo specify and implement some kind of logical policy for handling the
         underflow and overflow stream flags when the underflow/overflow overlaps
         multiple user buffers/callbacks.
@@ -263,10 +265,7 @@ PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bp,
         bp->inputZeroer = PaUtil_SelectZeroer( hostInputSampleFormat );
             
         bp->userInputIsInterleaved = (userInputSampleFormat & paNonInterleaved)?0:1;
-		
-        bp->hostInputIsInterleaved = (hostInputSampleFormat & paNonInterleaved)?0:1;
 
-        bp->userInputSampleFormatIsEqualToHost = ((userInputSampleFormat & ~paNonInterleaved) == (hostInputSampleFormat & ~paNonInterleaved));
 
         tempInputBufferSize =
             bp->framesPerTempBuffer * bp->bytesPerUserInputSample * inputChannelCount;
@@ -334,10 +333,6 @@ PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bp,
 
         bp->userOutputIsInterleaved = (userOutputSampleFormat & paNonInterleaved)?0:1;
 
-        bp->hostOutputIsInterleaved = (hostOutputSampleFormat & paNonInterleaved)?0:1;
-
-        bp->userOutputSampleFormatIsEqualToHost = ((userOutputSampleFormat & ~paNonInterleaved) == (hostOutputSampleFormat & ~paNonInterleaved));
-
         tempOutputBufferSize =
                 bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * outputChannelCount;
 
@@ -502,7 +497,6 @@ void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bp,
 
     assert( firstChannel < bp->inputChannelCount );
     assert( firstChannel + channelCount <= bp->inputChannelCount );
-    assert( bp->hostInputIsInterleaved );
 
     for( i=0; i< channelCount; ++i )
     {
@@ -517,7 +511,6 @@ void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bp,
         unsigned int channel, void *data )
 {
     assert( channel < bp->inputChannelCount );
-    assert( !bp->hostInputIsInterleaved );
     
     bp->hostInputChannels[0][channel].data = data;
     bp->hostInputChannels[0][channel].stride = 1;
@@ -553,7 +546,6 @@ void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bp,
 
     assert( firstChannel < bp->inputChannelCount );
     assert( firstChannel + channelCount <= bp->inputChannelCount );
-    assert( bp->hostInputIsInterleaved );
     
     for( i=0; i< channelCount; ++i )
     {
@@ -568,7 +560,6 @@ void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bp,
         unsigned int channel, void *data )
 {
     assert( channel < bp->inputChannelCount );
-    assert( !bp->hostInputIsInterleaved );
     
     bp->hostInputChannels[1][channel].data = data;
     bp->hostInputChannels[1][channel].stride = 1;
@@ -616,7 +607,6 @@ void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bp,
 
     assert( firstChannel < bp->outputChannelCount );
     assert( firstChannel + channelCount <= bp->outputChannelCount );
-    assert( bp->hostOutputIsInterleaved );
     
     for( i=0; i< channelCount; ++i )
     {
@@ -630,7 +620,6 @@ void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,
         unsigned int channel, void *data )
 {
     assert( channel < bp->outputChannelCount );
-    assert( !bp->hostOutputIsInterleaved );
 
     PaUtil_SetOutputChannel( bp, channel, data, 1 );
 }
@@ -666,7 +655,6 @@ void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bp,
 
     assert( firstChannel < bp->outputChannelCount );
     assert( firstChannel + channelCount <= bp->outputChannelCount );
-    assert( bp->hostOutputIsInterleaved );
     
     for( i=0; i< channelCount; ++i )
     {
@@ -680,7 +668,6 @@ void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,
         unsigned int channel, void *data )
 {
     assert( channel < bp->outputChannelCount );
-    assert( !bp->hostOutputIsInterleaved );
     
     PaUtil_Set2ndOutputChannel( bp, channel, data, 1 );
 }
@@ -696,9 +683,7 @@ void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bp,
         
     bp->timeInfo->inputBufferAdcTime -= bp->framesInTempInputBuffer * bp->samplePeriod;
     
-    /* We just pass through timeInfo->currentTime provided by the caller. This is
-        not strictly conformant to the word of the spec, since the buffer processor 
-        might call the callback multiple times, and we never refresh currentTime. */
+    bp->timeInfo->currentTime = 0; /** FIXME: @todo time info currentTime not implemented */
 
     /* the first streamCallback will be called to generate samples which will be
         outputted after the frames currently in the output buffer have been
@@ -737,8 +722,6 @@ static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
     unsigned long frameCount;
     unsigned long framesToGo = framesToProcess;
     unsigned long framesProcessed = 0;
-    int skipOutputConvert = 0;
-    int skipInputConvert = 0;
 
 
     if( *streamCallbackResult == paContinue )
@@ -755,25 +738,18 @@ static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
             }
             else /* there are input channels */
             {
-                
+                /*
+                    could use more elaborate logic here and sometimes process
+                    buffers in-place.
+                */
+            
                 destBytePtr = (unsigned char *)bp->tempInputBuffer;
 
                 if( bp->userInputIsInterleaved )
                 {
                     destSampleStrideSamples = bp->inputChannelCount;
                     destChannelStrideBytes = bp->bytesPerUserInputSample;
-
-                    /* process host buffer directly, or use temp buffer if formats differ or host buffer non-interleaved */
-                    if( bp->userInputSampleFormatIsEqualToHost && bp->hostInputIsInterleaved )
-                    {
-                        userInput = hostInputChannels[0].data;
-                        destBytePtr = (unsigned char *)hostInputChannels[0].data;
-                        skipInputConvert = 1;
-                    }
-                    else
-                    {
-                        userInput = bp->tempInputBuffer;
-                    }
+                    userInput = bp->tempInputBuffer;
                 }
                 else /* user input is not interleaved */
                 {
@@ -781,21 +757,10 @@ static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
                     destChannelStrideBytes = frameCount * bp->bytesPerUserInputSample;
 
                     /* setup non-interleaved ptrs */
-                    if( bp->userInputSampleFormatIsEqualToHost && !bp->hostInputIsInterleaved )
-                    {
-                        for( i=0; i<bp->inputChannelCount; ++i )
-                        {
-                            bp->tempInputBufferPtrs[i] = hostInputChannels[i].data;
-                        }
-                        skipInputConvert = 1;
-                    }
-                    else
+                    for( i=0; i<bp->inputChannelCount; ++i )
                     {
-                        for( i=0; i<bp->inputChannelCount; ++i )
-                        {
-                            bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +
-                                i * bp->bytesPerUserInputSample * frameCount;
-                        }
+                        bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +
+                            i * bp->bytesPerUserInputSample * frameCount;
                     }
                 
                     userInput = bp->tempInputBufferPtrs;
@@ -813,31 +778,19 @@ static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
                     }
                 }
                 else
-	            {
-                    if( skipInputConvert )
-                    {
-                        for( i=0; i<bp->inputChannelCount; ++i )
-                        {
-                            /* advance src ptr for next iteration */
-                            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
-                                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
-                        }
-                    }
-                    else
+                {
+                    for( i=0; i<bp->inputChannelCount; ++i )
                     {
-                        for( i=0; i<bp->inputChannelCount; ++i )
-                        {
-                            bp->inputConverter( destBytePtr, destSampleStrideSamples,
-                                                    hostInputChannels[i].data,
-                                                    hostInputChannels[i].stride,
-                                                    frameCount, &bp->ditherGenerator );
-
-                            destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */
-
-                            /* advance src ptr for next iteration */
-                            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
-                                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
-                        }
+                        bp->inputConverter( destBytePtr, destSampleStrideSamples,
+                                                hostInputChannels[i].data,
+                                                hostInputChannels[i].stride,
+                                                frameCount, &bp->ditherGenerator );
+
+                        destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */
+
+                        /* advance src ptr for next iteration */
+                        hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +
+                                frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;
                     }
                 }
             }
@@ -852,34 +805,14 @@ static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
             {
                 if( bp->userOutputIsInterleaved )
                 {
-                    /* process host buffer directly, or use temp buffer if formats differ or host buffer non-interleaved */
-                    if( bp->userOutputSampleFormatIsEqualToHost && bp->hostOutputIsInterleaved )
-                    {
-                        userOutput = hostOutputChannels[0].data;
-                        skipOutputConvert = 1;
-                    }
-                    else
-                    {
-                        userOutput = bp->tempOutputBuffer;
-                    }
+                    userOutput = bp->tempOutputBuffer;
                 }
                 else /* user output is not interleaved */
                 {
-                    if( bp->userOutputSampleFormatIsEqualToHost && !bp->hostOutputIsInterleaved )
-                    {
-                        for( i=0; i<bp->outputChannelCount; ++i )
-                        {
-                            bp->tempOutputBufferPtrs[i] = hostOutputChannels[i].data;
-                        }
-                        skipOutputConvert = 1;
-                    }
-                    else
+                    for( i = 0; i < bp->outputChannelCount; ++i )
                     {
-                        for( i=0; i<bp->outputChannelCount; ++i )
-                        {
-                            bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +
-                                i * bp->bytesPerUserOutputSample * frameCount;
-                        }
+                        bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +
+                            i * bp->bytesPerUserOutputSample * frameCount;
                     }
 
                     userOutput = bp->tempOutputBufferPtrs;
@@ -903,45 +836,37 @@ static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,
                 
                 if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )
                 {
-                    if( skipOutputConvert )
-					{
-						for( i=0; i<bp->outputChannelCount; ++i )
-                    	{
-                        	/* advance dest ptr for next iteration */
-                        	hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
-                            	    frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
-                    	}
-					}
-					else
-					{
-
-                    	srcBytePtr = (unsigned char *)bp->tempOutputBuffer;
-
-                    	if( bp->userOutputIsInterleaved )
-                    	{
-                        	srcSampleStrideSamples = bp->outputChannelCount;
-                        	srcChannelStrideBytes = bp->bytesPerUserOutputSample;
-                    	}
-                    	else /* user output is not interleaved */
-                    	{
-                        	srcSampleStrideSamples = 1;
-                        	srcChannelStrideBytes = frameCount * bp->bytesPerUserOutputSample;
-                    	}
-
-                    	for( i=0; i<bp->outputChannelCount; ++i )
-                    	{
-                        	bp->outputConverter(    hostOutputChannels[i].data,
-                                                	hostOutputChannels[i].stride,
-                                                	srcBytePtr, srcSampleStrideSamples,
-                                                	frameCount, &bp->ditherGenerator );
-
-                        	srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */
-
-                        	/* advance dest ptr for next iteration */
-                        	hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
-                                		frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
-                    	}
-					}
+                    /*
+                        could use more elaborate logic here and sometimes process
+                        buffers in-place.
+                    */
+            
+                    srcBytePtr = (unsigned char *)bp->tempOutputBuffer;
+
+                    if( bp->userOutputIsInterleaved )
+                    {
+                        srcSampleStrideSamples = bp->outputChannelCount;
+                        srcChannelStrideBytes = bp->bytesPerUserOutputSample;
+                    }
+                    else /* user output is not interleaved */
+                    {
+                        srcSampleStrideSamples = 1;
+                        srcChannelStrideBytes = frameCount * bp->bytesPerUserOutputSample;
+                    }
+
+                    for( i=0; i<bp->outputChannelCount; ++i )
+                    {
+                        bp->outputConverter(    hostOutputChannels[i].data,
+                                                hostOutputChannels[i].stride,
+                                                srcBytePtr, srcSampleStrideSamples,
+                                                frameCount, &bp->ditherGenerator );
+
+                        srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */
+
+                        /* advance dest ptr for next iteration */
+                        hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +
+                                frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;
+                    }
                 }
              
                 framesProcessed += frameCount;
@@ -1072,7 +997,7 @@ static unsigned long AdaptingInputOnlyProcess( PaUtilBufferProcessor *bp,
                         bp->framesPerUserBuffer, bp->timeInfo,
                         bp->callbackStatusFlags, bp->userData );
 
-                bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod;
+                bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod;
             }
             
             bp->framesInTempInputBuffer = 0;
diff --git a/portaudio/src/common/pa_process.h b/portaudio/src/common/pa_process.h
index 12274eecf..89584bc07 100644
--- a/portaudio/src/common/pa_process.h
+++ b/portaudio/src/common/pa_process.h
@@ -1,7 +1,7 @@
 #ifndef PA_PROCESS_H
 #define PA_PROCESS_H
 /*
- * $Id: pa_process.h 1523 2010-07-10 17:41:25Z dmitrykos $
+ * $Id: pa_process.h 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library callback buffer processing adapters
  *
  * Based on the Open Source API proposed by Ross Bencina
@@ -256,8 +256,6 @@ typedef struct {
 
     PaUtilHostBufferSizeMode hostBufferSizeMode;
     int useNonAdaptingProcess;
-    int userOutputSampleFormatIsEqualToHost;
-    int userInputSampleFormatIsEqualToHost;
     unsigned long framesPerTempBuffer;
 
     unsigned int inputChannelCount;
@@ -289,14 +287,12 @@ typedef struct {
 
     PaStreamCallbackFlags callbackStatusFlags;
 
-    int hostInputIsInterleaved;
     unsigned long hostInputFrameCount[2];
     PaUtilChannelDescriptor *hostInputChannels[2]; /**< pointers to arrays of channel descriptors.
                                                         pointers are NULL for half-duplex output processing.
                                                         hostInputChannels[i].data is NULL when the caller
                                                         calls PaUtil_SetNoInput()
                                                         */
-    int hostOutputIsInterleaved;
     unsigned long hostOutputFrameCount[2];
     PaUtilChannelDescriptor *hostOutputChannels[2]; /**< pointers to arrays of channel descriptors.
                                                          pointers are NULL for half-duplex input processing.
diff --git a/portaudio/src/common/pa_ringbuffer.c b/portaudio/src/common/pa_ringbuffer.c
index 310d719f2..f4e1201a6 100644
--- a/portaudio/src/common/pa_ringbuffer.c
+++ b/portaudio/src/common/pa_ringbuffer.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_ringbuffer.c 1421 2009-11-18 16:09:05Z bjornroche $
+ * $Id: pa_ringbuffer.c 1240 2007-07-17 13:05:07Z bjornroche $
  * Portable Audio I/O Library
  * Ring Buffer utility.
  *
@@ -7,8 +7,6 @@
  * modified for SMP safety on Mac OS X by Bjorn Roche
  * modified for SMP safety on Linux by Leland Lucius
  * also, allowed for const where possible
- * modified for multiple-byte-sized data elements by Sven Fischer 
- *
  * Note that this is safe only for a single-thread reader and a
  * single-thread writer.
  *
@@ -57,34 +55,94 @@
 #include <math.h>
 #include "pa_ringbuffer.h"
 #include <string.h>
-#include "pa_memorybarrier.h"
+
+/****************
+ * First, we'll define some memory barrier primitives based on the system.
+ * right now only OS X, FreeBSD, and Linux are supported. In addition to providing
+ * memory barriers, these functions should ensure that data cached in registers
+ * is written out to cache where it can be snooped by other CPUs. (ie, the volatile
+ * keyword should not be required)
+ *
+ * the primitives that must be defined are:
+ *
+ * PaUtil_FullMemoryBarrier()
+ * PaUtil_ReadMemoryBarrier()
+ * PaUtil_WriteMemoryBarrier()
+ *
+ ****************/
+
+#if defined(__APPLE__)
+#   include <libkern/OSAtomic.h>
+    /* Here are the memory barrier functions. Mac OS X only provides
+       full memory barriers, so the three types of barriers are the same,
+       however, these barriers are superior to compiler-based ones. */
+#   define PaUtil_FullMemoryBarrier()  OSMemoryBarrier()
+#   define PaUtil_ReadMemoryBarrier()  OSMemoryBarrier()
+#   define PaUtil_WriteMemoryBarrier() OSMemoryBarrier()
+#elif defined(__GNUC__)
+    /* GCC >= 4.1 has built-in intrinsics. We'll use those */
+#   if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)
+#      define PaUtil_FullMemoryBarrier()  __sync_synchronize()
+#      define PaUtil_ReadMemoryBarrier()  __sync_synchronize()
+#      define PaUtil_WriteMemoryBarrier() __sync_synchronize()
+    /* as a fallback, GCC understands volatile asm and "memory" to mean it
+     * should not reorder memory read/writes */
+#   elif defined( __PPC__ )
+#      define PaUtil_FullMemoryBarrier()  asm volatile("sync":::"memory")
+#      define PaUtil_ReadMemoryBarrier()  asm volatile("sync":::"memory")
+#      define PaUtil_WriteMemoryBarrier() asm volatile("sync":::"memory")
+#   elif defined( __i386__ ) || defined( __i486__ ) || defined( __i586__ ) || defined( __i686__ ) || defined( __x86_64__ )
+#      define PaUtil_FullMemoryBarrier()  asm volatile("mfence":::"memory")
+#      define PaUtil_ReadMemoryBarrier()  asm volatile("lfence":::"memory")
+#      define PaUtil_WriteMemoryBarrier() asm volatile("sfence":::"memory")
+#   else
+#      ifdef ALLOW_SMP_DANGERS
+#         warning Memory barriers not defined on this system or system unknown
+#         warning For SMP safety, you should fix this.
+#         define PaUtil_FullMemoryBarrier()
+#         define PaUtil_ReadMemoryBarrier()
+#         define PaUtil_WriteMemoryBarrier()
+#      else
+#         error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
+#      endif
+#   endif
+#else
+#   ifdef ALLOW_SMP_DANGERS
+#      warning Memory barriers not defined on this system or system unknown
+#      warning For SMP safety, you should fix this.
+#      define PaUtil_FullMemoryBarrier()
+#      define PaUtil_ReadMemoryBarrier()
+#      define PaUtil_WriteMemoryBarrier()
+#   else
+#      error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.
+#   endif
+#endif
 
 /***************************************************************************
  * Initialize FIFO.
- * elementCount must be power of 2, returns -1 if not.
+ * numBytes must be power of 2, returns -1 if not.
  */
-ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr )
+long PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, long numBytes, void *dataPtr )
 {
-    if( ((elementCount-1) & elementCount) != 0) return -1; /* Not Power of two. */
-    rbuf->bufferSize = elementCount;
+    if( ((numBytes-1) & numBytes) != 0) return -1; /* Not Power of two. */
+    rbuf->bufferSize = numBytes;
     rbuf->buffer = (char *)dataPtr;
     PaUtil_FlushRingBuffer( rbuf );
-    rbuf->bigMask = (elementCount*2)-1;
-    rbuf->smallMask = (elementCount)-1;
-    rbuf->elementSizeBytes = elementSizeBytes;
+    rbuf->bigMask = (numBytes*2)-1;
+    rbuf->smallMask = (numBytes)-1;
     return 0;
 }
 
 /***************************************************************************
-** Return number of elements available for reading. */
-ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf )
+** Return number of bytes available for reading. */
+long PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf )
 {
     PaUtil_ReadMemoryBarrier();
     return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask );
 }
 /***************************************************************************
-** Return number of elements available for writing. */
-ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf )
+** Return number of bytes available for writing. */
+long PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf )
 {
     /* Since we are calling PaUtil_GetRingBufferReadAvailable, we don't need an aditional MB */
     return ( rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));
@@ -101,126 +159,126 @@ void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf )
 ** Get address of region(s) to which we can write data.
 ** If the region is contiguous, size2 will be zero.
 ** If non-contiguous, size2 will be the size of second region.
-** Returns room available to be written or elementCount, whichever is smaller.
+** Returns room available to be written or numBytes, whichever is smaller.
 */
-ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
-                                       void **dataPtr1, ring_buffer_size_t *sizePtr1,
-                                       void **dataPtr2, ring_buffer_size_t *sizePtr2 )
+long PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, long numBytes,
+                                       void **dataPtr1, long *sizePtr1,
+                                       void **dataPtr2, long *sizePtr2 )
 {
-    ring_buffer_size_t   index;
-    ring_buffer_size_t   available = PaUtil_GetRingBufferWriteAvailable( rbuf );
-    if( elementCount > available ) elementCount = available;
+    long   index;
+    long   available = PaUtil_GetRingBufferWriteAvailable( rbuf );
+    if( numBytes > available ) numBytes = available;
     /* Check to see if write is not contiguous. */
     index = rbuf->writeIndex & rbuf->smallMask;
-    if( (index + elementCount) > rbuf->bufferSize )
+    if( (index + numBytes) > rbuf->bufferSize )
     {
         /* Write data in two blocks that wrap the buffer. */
-        ring_buffer_size_t   firstHalf = rbuf->bufferSize - index;
-        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
+        long   firstHalf = rbuf->bufferSize - index;
+        *dataPtr1 = &rbuf->buffer[index];
         *sizePtr1 = firstHalf;
         *dataPtr2 = &rbuf->buffer[0];
-        *sizePtr2 = elementCount - firstHalf;
+        *sizePtr2 = numBytes - firstHalf;
     }
     else
     {
-        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
-        *sizePtr1 = elementCount;
+        *dataPtr1 = &rbuf->buffer[index];
+        *sizePtr1 = numBytes;
         *dataPtr2 = NULL;
         *sizePtr2 = 0;
     }
-    return elementCount;
+    return numBytes;
 }
 
 
 /***************************************************************************
 */
-ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )
+long PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, long numBytes )
 {
     /* we need to ensure that previous writes are seen before we update the write index */
     PaUtil_WriteMemoryBarrier();
-    return rbuf->writeIndex = (rbuf->writeIndex + elementCount) & rbuf->bigMask;
+    return rbuf->writeIndex = (rbuf->writeIndex + numBytes) & rbuf->bigMask;
 }
 
 /***************************************************************************
 ** Get address of region(s) from which we can read data.
 ** If the region is contiguous, size2 will be zero.
 ** If non-contiguous, size2 will be the size of second region.
-** Returns room available to be written or elementCount, whichever is smaller.
+** Returns room available to be written or numBytes, whichever is smaller.
 */
-ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
-                                void **dataPtr1, ring_buffer_size_t *sizePtr1,
-                                void **dataPtr2, ring_buffer_size_t *sizePtr2 )
+long PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, long numBytes,
+                                void **dataPtr1, long *sizePtr1,
+                                void **dataPtr2, long *sizePtr2 )
 {
-    ring_buffer_size_t   index;
-    ring_buffer_size_t   available = PaUtil_GetRingBufferReadAvailable( rbuf );
-    if( elementCount > available ) elementCount = available;
+    long   index;
+    long   available = PaUtil_GetRingBufferReadAvailable( rbuf );
+    if( numBytes > available ) numBytes = available;
     /* Check to see if read is not contiguous. */
     index = rbuf->readIndex & rbuf->smallMask;
-    if( (index + elementCount) > rbuf->bufferSize )
+    if( (index + numBytes) > rbuf->bufferSize )
     {
         /* Write data in two blocks that wrap the buffer. */
-        ring_buffer_size_t firstHalf = rbuf->bufferSize - index;
-        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
+        long firstHalf = rbuf->bufferSize - index;
+        *dataPtr1 = &rbuf->buffer[index];
         *sizePtr1 = firstHalf;
         *dataPtr2 = &rbuf->buffer[0];
-        *sizePtr2 = elementCount - firstHalf;
+        *sizePtr2 = numBytes - firstHalf;
     }
     else
     {
-        *dataPtr1 = &rbuf->buffer[index*rbuf->elementSizeBytes];
-        *sizePtr1 = elementCount;
+        *dataPtr1 = &rbuf->buffer[index];
+        *sizePtr1 = numBytes;
         *dataPtr2 = NULL;
         *sizePtr2 = 0;
     }
-    return elementCount;
+    return numBytes;
 }
 /***************************************************************************
 */
-ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount )
+long PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, long numBytes )
 {
     /* we need to ensure that previous writes are always seen before updating the index. */
     PaUtil_WriteMemoryBarrier();
-    return rbuf->readIndex = (rbuf->readIndex + elementCount) & rbuf->bigMask;
+    return rbuf->readIndex = (rbuf->readIndex + numBytes) & rbuf->bigMask;
 }
 
 /***************************************************************************
-** Return elements written. */
-ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount )
+** Return bytes written. */
+long PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, long numBytes )
 {
-    ring_buffer_size_t size1, size2, numWritten;
+    long size1, size2, numWritten;
     void *data1, *data2;
-    numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );
+    numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 );
     if( size2 > 0 )
     {
 
-        memcpy( data1, data, size1*rbuf->elementSizeBytes );
-        data = ((char *)data) + size1*rbuf->elementSizeBytes;
-        memcpy( data2, data, size2*rbuf->elementSizeBytes );
+        memcpy( data1, data, size1 );
+        data = ((char *)data) + size1;
+        memcpy( data2, data, size2 );
     }
     else
     {
-        memcpy( data1, data, size1*rbuf->elementSizeBytes );
+        memcpy( data1, data, size1 );
     }
     PaUtil_AdvanceRingBufferWriteIndex( rbuf, numWritten );
     return numWritten;
 }
 
 /***************************************************************************
-** Return elements read. */
-ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount )
+** Return bytes read. */
+long PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, long numBytes )
 {
-    ring_buffer_size_t size1, size2, numRead;
+    long size1, size2, numRead;
     void *data1, *data2;
-    numRead = PaUtil_GetRingBufferReadRegions( rbuf, elementCount, &data1, &size1, &data2, &size2 );
+    numRead = PaUtil_GetRingBufferReadRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 );
     if( size2 > 0 )
     {
-        memcpy( data, data1, size1*rbuf->elementSizeBytes );
-        data = ((char *)data) + size1*rbuf->elementSizeBytes;
-        memcpy( data, data2, size2*rbuf->elementSizeBytes );
+        memcpy( data, data1, size1 );
+        data = ((char *)data) + size1;
+        memcpy( data, data2, size2 );
     }
     else
     {
-        memcpy( data, data1, size1*rbuf->elementSizeBytes );
+        memcpy( data, data1, size1 );
     }
     PaUtil_AdvanceRingBufferReadIndex( rbuf, numRead );
     return numRead;
diff --git a/portaudio/src/common/pa_ringbuffer.h b/portaudio/src/common/pa_ringbuffer.h
index 7efd1914d..b38088981 100644
--- a/portaudio/src/common/pa_ringbuffer.h
+++ b/portaudio/src/common/pa_ringbuffer.h
@@ -1,15 +1,13 @@
 #ifndef PA_RINGBUFFER_H
 #define PA_RINGBUFFER_H
 /*
- * $Id: pa_ringbuffer.h 1421 2009-11-18 16:09:05Z bjornroche $
+ * $Id: pa_ringbuffer.h 1151 2006-11-29 02:11:16Z leland_lucius $
  * Portable Audio I/O Library
  * Ring Buffer utility.
  *
  * Author: Phil Burk, http://www.softsynth.com
  * modified for SMP safety on OS X by Bjorn Roche.
  * also allowed for const where possible.
- * modified for multiple-byte-sized data elements by Sven Fischer 
- *
  * Note that this is safe only for a single-thread reader
  * and a single-thread writer.
  *
@@ -50,38 +48,8 @@
 
 /** @file
  @ingroup common_src
- @brief Single-reader single-writer lock-free ring buffer
-
- PaUtilRingBuffer is a ring buffer used to transport samples between
- different execution contexts (threads, OS callbacks, interrupt handlers)
- without requiring the use of any locks. This only works when there is
- a single reader and a single writer (ie. one thread or callback writes
- to the ring buffer, another thread or callback reads from it).
-
- The PaUtilRingBuffer structure manages a ring buffer containing N 
- elements, where N must be a power of two. An element may be any size 
- (specified in bytes).
-
- The memory area used to store the buffer elements must be allocated by 
- the client prior to calling PaUtil_InitializeRingBuffer() and must outlive
- the use of the ring buffer.
 */
 
-#if defined(__APPLE__)
-#include <sys/types.h>
-typedef int32_t ring_buffer_size_t;
-#elif defined( __GNUC__ )
-typedef long ring_buffer_size_t;
-#elif (_MSC_VER >= 1400)
-typedef long ring_buffer_size_t;
-#elif defined(_MSC_VER) || defined(__BORLANDC__)
-typedef long ring_buffer_size_t;
-#else
-typedef long ring_buffer_size_t;
-#endif
-
-
-
 #ifdef __cplusplus
 extern "C"
 {
@@ -89,29 +57,26 @@ extern "C"
 
 typedef struct PaUtilRingBuffer
 {
-    ring_buffer_size_t  bufferSize; /**< Number of elements in FIFO. Power of 2. Set by PaUtil_InitRingBuffer. */
-    ring_buffer_size_t  writeIndex; /**< Index of next writable element. Set by PaUtil_AdvanceRingBufferWriteIndex. */
-    ring_buffer_size_t  readIndex;  /**< Index of next readable element. Set by PaUtil_AdvanceRingBufferReadIndex. */
-    ring_buffer_size_t  bigMask;    /**< Used for wrapping indices with extra bit to distinguish full/empty. */
-    ring_buffer_size_t  smallMask;  /**< Used for fitting indices to buffer. */
-    ring_buffer_size_t  elementSizeBytes; /**< Number of bytes per element. */
-    char  *buffer;    /**< Pointer to the buffer containing the actual data. */
+    long   bufferSize; /* Number of bytes in FIFO. Power of 2. Set by PaUtil_InitRingBuffer. */
+    long   writeIndex; /* Index of next writable byte. Set by PaUtil_AdvanceRingBufferWriteIndex. */
+    long   readIndex;  /* Index of next readable byte. Set by PaUtil_AdvanceRingBufferReadIndex. */
+    long   bigMask;    /* Used for wrapping indices with extra bit to distinguish full/empty. */
+    long   smallMask;  /* Used for fitting indices to buffer. */
+    char  *buffer;
 }PaUtilRingBuffer;
 
 /** Initialize Ring Buffer.
 
  @param rbuf The ring buffer.
 
- @param elementSizeBytes The size of a single data element in bytes.
-
- @param elementCount The number of elements in the buffer (must be power of 2).
+ @param numBytes The number of bytes in the buffer and must be power of 2.
 
  @param dataPtr A pointer to a previously allocated area where the data
- will be maintained.  It must be elementCount*elementSizeBytes long.
+ will be maintained.  It must be numBytes long.
 
- @return -1 if elementCount is not a power of 2, otherwise 0.
+ @return -1 if numBytes is not a power of 2, otherwise 0.
 */
-ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementSizeBytes, ring_buffer_size_t elementCount, void *dataPtr );
+long PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, long numBytes, void *dataPtr );
 
 /** Clear buffer. Should only be called when buffer is NOT being read.
 
@@ -119,21 +84,21 @@ ring_buffer_size_t PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, ring_buf
 */
 void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf );
 
-/** Retrieve the number of elements available in the ring buffer for writing.
+/** Retrieve the number of bytes available in the ring buffer for writing.
 
  @param rbuf The ring buffer.
 
- @return The number of elements available for writing.
+ @return The number of bytes available for writing.
 */
-ring_buffer_size_t PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf );
+long PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf );
 
-/** Retrieve the number of elements available in the ring buffer for reading.
+/** Retrieve the number of bytes available in the ring buffer for reading.
 
  @param rbuf The ring buffer.
 
- @return The number of elements available for reading.
+ @return The number of bytes available for reading.
 */
-ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf );
+long PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf );
 
 /** Write data to the ring buffer.
 
@@ -141,11 +106,11 @@ ring_buffer_size_t PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf );
 
  @param data The address of new data to write to the buffer.
 
- @param elementCount The number of elements to be written.
+ @param numBytes The number of bytes to be written.
 
- @return The number of elements written.
+ @return The number of bytes written.
 */
-ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, ring_buffer_size_t elementCount );
+long PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, long numBytes );
 
 /** Read data from the ring buffer.
 
@@ -153,17 +118,17 @@ ring_buffer_size_t PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *d
 
  @param data The address where the data should be stored.
 
- @param elementCount The number of elements to be read.
+ @param numBytes The number of bytes to be read.
 
- @return The number of elements read.
+ @return The number of bytes read.
 */
-ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ring_buffer_size_t elementCount );
+long PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, long numBytes );
 
 /** Get address of region(s) to which we can write data.
 
  @param rbuf The ring buffer.
 
- @param elementCount The number of elements desired.
+ @param numBytes The number of bytes desired.
 
  @param dataPtr1 The address where the first (or only) region pointer will be
  stored.
@@ -172,32 +137,32 @@ ring_buffer_size_t PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, ri
  stored.
 
  @param dataPtr2 The address where the second region pointer will be stored if
- the first region is too small to satisfy elementCount.
+ the first region is too small to satisfy numBytes.
 
  @param sizePtr2 The address where the second region length will be stored if
- the first region is too small to satisfy elementCount.
+ the first region is too small to satisfy numBytes.
 
- @return The room available to be written or elementCount, whichever is smaller.
+ @return The room available to be written or numBytes, whichever is smaller.
 */
-ring_buffer_size_t PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
-                                       void **dataPtr1, ring_buffer_size_t *sizePtr1,
-                                       void **dataPtr2, ring_buffer_size_t *sizePtr2 );
+long PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, long numBytes,
+                                       void **dataPtr1, long *sizePtr1,
+                                       void **dataPtr2, long *sizePtr2 );
 
 /** Advance the write index to the next location to be written.
 
  @param rbuf The ring buffer.
 
- @param elementCount The number of elements to advance.
+ @param numBytes The number of bytes to advance.
 
  @return The new position.
 */
-ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount );
+long PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, long numBytes );
 
 /** Get address of region(s) from which we can write data.
 
  @param rbuf The ring buffer.
 
- @param elementCount The number of elements desired.
+ @param numBytes The number of bytes desired.
 
  @param dataPtr1 The address where the first (or only) region pointer will be
  stored.
@@ -206,26 +171,26 @@ ring_buffer_size_t PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, r
  stored.
 
  @param dataPtr2 The address where the second region pointer will be stored if
- the first region is too small to satisfy elementCount.
+ the first region is too small to satisfy numBytes.
 
  @param sizePtr2 The address where the second region length will be stored if
- the first region is too small to satisfy elementCount.
+ the first region is too small to satisfy numBytes.
 
- @return The number of elements available for reading.
+ @return The number of bytes available for reading.
 */
-ring_buffer_size_t PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount,
-                                      void **dataPtr1, ring_buffer_size_t *sizePtr1,
-                                      void **dataPtr2, ring_buffer_size_t *sizePtr2 );
+long PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, long numBytes,
+                                      void **dataPtr1, long *sizePtr1,
+                                      void **dataPtr2, long *sizePtr2 );
 
 /** Advance the read index to the next location to be read.
 
  @param rbuf The ring buffer.
 
- @param elementCount The number of elements to advance.
+ @param numBytes The number of bytes to advance.
 
  @return The new position.
 */
-ring_buffer_size_t PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, ring_buffer_size_t elementCount );
+long PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, long numBytes );
 
 #ifdef __cplusplus
 }
diff --git a/portaudio/src/common/pa_skeleton.c b/portaudio/src/common/pa_skeleton.c
index d5cb52d82..e229b07ba 100644
--- a/portaudio/src/common/pa_skeleton.c
+++ b/portaudio/src/common/pa_skeleton.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_skeleton.c 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_skeleton.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library skeleton implementation
  * demonstrates how to use the common functions to implement support
  * for a host API
@@ -43,10 +43,8 @@
 
  @brief Skeleton implementation of support for a host API.
 
- This file is provided as a starting point for implementing support for
- a new host API. It provides examples of how the common code can be used.
-
- @note IMPLEMENT ME comments are used to indicate functionality
+ @note This file is provided as a starting point for implementing support for
+ a new host API. IMPLEMENT ME comments are used to indicate functionality
  which much be customised for each implementation.
 */
 
diff --git a/portaudio/src/common/pa_stream.c b/portaudio/src/common/pa_stream.c
index ea91821f8..172e7d26b 100644
--- a/portaudio/src/common/pa_stream.c
+++ b/portaudio/src/common/pa_stream.c
@@ -1,10 +1,10 @@
 /*
- * $Id: pa_stream.c 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_stream.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library
- * stream interface
+ * 
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 2008 Ross Bencina
+ * Copyright (c) 2002 Ross Bencina
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -40,8 +40,8 @@
 /** @file
  @ingroup common_src
 
- @brief Stream interfaces, representation structures and helper functions
- used to interface between pa_front.c host API implementations.
+ @brief Interface used by pa_front to virtualize functions which operate on
+ streams.
 */
 
 
diff --git a/portaudio/src/common/pa_stream.h b/portaudio/src/common/pa_stream.h
index 8d707b79c..f5363b3e1 100644
--- a/portaudio/src/common/pa_stream.h
+++ b/portaudio/src/common/pa_stream.h
@@ -1,12 +1,12 @@
 #ifndef PA_STREAM_H
 #define PA_STREAM_H
 /*
- * $Id: pa_stream.h 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_stream.h 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library
  * stream interface
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -42,8 +42,8 @@
 /** @file
  @ingroup common_src
 
- @brief Stream interfaces, representation structures and helper functions
- used to interface between pa_front.c host API implementations.
+ @brief Interface used by pa_front to virtualize functions which operate on
+ streams.
 */
 
 
diff --git a/portaudio/src/common/pa_trace.c b/portaudio/src/common/pa_trace.c
index 24305003f..583d3ae9f 100644
--- a/portaudio/src/common/pa_trace.c
+++ b/portaudio/src/common/pa_trace.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_trace.c 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_trace.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library Trace Facility
  * Store trace information in real-time for later printing.
  *
@@ -40,7 +40,7 @@
 /** @file
  @ingroup common_src
 
- @brief Real-time safe event trace logging facility for debugging.
+ @brief Event trace mechanism for debugging.
 */
 
 
diff --git a/portaudio/src/common/pa_trace.h b/portaudio/src/common/pa_trace.h
index b11509e0e..a4d2a3314 100644
--- a/portaudio/src/common/pa_trace.h
+++ b/portaudio/src/common/pa_trace.h
@@ -1,7 +1,7 @@
 #ifndef PA_TRACE_H
 #define PA_TRACE_H
 /*
- * $Id: pa_trace.h 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_trace.h 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library Trace Facility
  * Store trace information in real-time for later printing.
  *
@@ -42,36 +42,14 @@
 /** @file
  @ingroup common_src
 
- @brief Real-time safe event trace logging facility for debugging.
+ @brief Event trace mechanism for debugging.
 
- Allows data to be logged to a fixed size trace buffer in a real-time
- execution context (such as at interrupt time). Each log entry consists 
- of a message comprising a string pointer and an int.  The trace buffer 
- may be dumped to stdout later.
-
- This facility is only active if PA_TRACE_REALTIME_EVENTS is set to 1,
- otherwise the trace functions expand to no-ops.
-
- @fn PaUtil_ResetTraceMessages
- @brief Clear the trace buffer.
-
- @fn PaUtil_AddTraceMessage
- @brief Add a message to the trace buffer. A message consists of string and an int.
- @param msg The string pointer must remain valid until PaUtil_DumpTraceMessages 
-    is called. As a result, usually only string literals should be passed as 
-    the msg parameter.
-
- @fn PaUtil_DumpTraceMessages
- @brief Print all messages in the trace buffer to stdout and clear the trace buffer.
+ Allows data to be written to the buffer at interrupt time and dumped later.
 */
 
-#ifndef PA_TRACE_REALTIME_EVENTS
-#define PA_TRACE_REALTIME_EVENTS     (0)   /**< Set to 1 to enable logging using the trace functions defined below */
-#endif
 
-#ifndef PA_MAX_TRACE_RECORDS
-#define PA_MAX_TRACE_RECORDS      (2048)   /**< Maximum number of records stored in trace buffer */   
-#endif
+#define PA_TRACE_REALTIME_EVENTS     (0)   /* Keep log of various real-time events. */
+#define PA_MAX_TRACE_RECORDS      (2048)
 
 #ifdef __cplusplus
 extern "C"
diff --git a/portaudio/src/common/pa_util.h b/portaudio/src/common/pa_util.h
index 95ea6789a..55eaa1388 100644
--- a/portaudio/src/common/pa_util.h
+++ b/portaudio/src/common/pa_util.h
@@ -1,12 +1,12 @@
 #ifndef PA_UTIL_H
 #define PA_UTIL_H
 /*
- * $Id: pa_util.h 1339 2008-02-15 07:50:33Z rossb $
+ * $Id: pa_util.h 1229 2007-06-15 16:11:11Z rossb $
  * Portable Audio I/O Library implementation utilities header
  * common implementation utilities and interfaces
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -44,9 +44,6 @@
 
     @brief Prototypes for utility functions used by PortAudio implementations.
 
-    Some functions declared here are defined in pa_front.c while others
-    are implemented separately for each platform.
-
     @todo Document and adhere to the alignment guarantees provided by
     PaUtil_AllocateMemory().
 */
diff --git a/portaudio/src/hostapi/alsa/pa_linux_alsa.c b/portaudio/src/hostapi/alsa/pa_linux_alsa.c
index 86baf2286..06b17ac13 100644
--- a/portaudio/src/hostapi/alsa/pa_linux_alsa.c
+++ b/portaudio/src/hostapi/alsa/pa_linux_alsa.c
@@ -1,12 +1,11 @@
 /*
- * $Id: pa_linux_alsa.c 1533 2010-08-02 10:37:18Z dmitrykos $
+ * $Id: pa_linux_alsa.c 1236 2007-06-24 20:39:26Z aknudsen $
  * PortAudio Portable Real-Time Audio Library
  * Latest Version at: http://www.portaudio.com
  * ALSA implementation by Joshua Haberman and Arve Knudsen
  *
  * Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
- * Copyright (c) 2005-2009 Arve Knudsen <arve.knudsen@gmail.com>
- * Copyright (c) 2008 Kevin Kofler <kevin.kofler@chello.at>
+ * Copyright (c) 2005-2006 Arve Knudsen <aknuds-1@broadpark.no>
  *
  * Based on the Open Source API proposed by Ross Bencina
  * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
@@ -32,13 +31,13 @@
  */
 
 /*
- * The text above constitutes the entire PortAudio license; however,
+ * The text above constitutes the entire PortAudio license; however, 
  * the PortAudio community also makes the following non-binding requests:
  *
  * Any person wishing to distribute modifications to the Software is
  * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also
- * requested that these non-binding requests be included along with the
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
  * license above.
  */
 
@@ -63,7 +62,6 @@
 #include <sys/mman.h>
 #include <signal.h> /* For sig_atomic_t */
 
-#include "portaudio.h"
 #include "pa_util.h"
 #include "pa_unix_util.h"
 #include "pa_allocation.h"
@@ -100,7 +98,6 @@
 
 static int aErr_;               /* Used with ENSURE_ */
 static int numPeriods_ = 4;
-static int busyRetries_ = 100;
 
 int PaAlsa_SetNumPeriods( int numPeriods )
 {
@@ -120,9 +117,6 @@ typedef struct
     unsigned long framesPerBuffer;
     int numUserChannels, numHostChannels;
     int userInterleaved, hostInterleaved;
-    int canMmap;
-    void *nonMmapBuffer;
-    unsigned int nonMmapBufferSize;
     PaDeviceIndex device;     /* Keep the device index */
 
     snd_pcm_t *pcm;
@@ -149,7 +143,7 @@ typedef struct PaAlsaStream
 
     int primeBuffers;
     int callbackMode;              /* bool: are we running in callback mode? */
-    int pcmsSynced;                /* Have we successfully synced pcms */
+    int pcmsSynced;	            /* Have we successfully synced pcms */
     int rtSched;
 
     /* the callback thread uses these to poll the sound device(s), waiting
@@ -321,12 +315,12 @@ static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
 
 /** Determine max channels and default latencies.
  *
- * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for
+ * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for 
  * traits like max channels, suitable default latencies and default sample rate. Upon error, max channels is set to zero,
  * and a suitable result returned. The device is closed before returning.
  */
 static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, int openBlocking,
-        PaAlsaDeviceInfo* devInfo )
+        PaAlsaDeviceInfo* devInfo, int* canMmap )
 {
     PaError result = paNoError;
     snd_pcm_hw_params_t *hwParams;
@@ -359,6 +353,9 @@ static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, in
     snd_pcm_hw_params_alloca( &hwParams );
     snd_pcm_hw_params_any( pcm, hwParams );
 
+    *canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_INTERLEAVED ) >= 0 ||
+            snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_NONINTERLEAVED ) >= 0;
+
     if( defaultSr >= 0 )
     {
         /* Could be that the device opened in one mode supports samplerates that the other mode wont have,
@@ -380,7 +377,7 @@ static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, in
         }
         ENSURE_( GetExactSampleRate( hwParams, &defaultSr ), paUnanticipatedHostError );
     }
-
+    
     ENSURE_( snd_pcm_hw_params_get_channels_min( hwParams, &minChans ), paUnanticipatedHostError );
     ENSURE_( snd_pcm_hw_params_get_channels_max( hwParams, &maxChans ), paUnanticipatedHostError );
     assert( maxChans <= INT_MAX );
@@ -416,7 +413,7 @@ static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, in
     ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &lowLatency ), paUnanticipatedHostError );
 
     /* Have to reset hwParams, to set new buffer size */
-    ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError ); 
     ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &highLatency ), paUnanticipatedHostError );
 
     *minChannels = (int)minChans;
@@ -486,10 +483,10 @@ static const HwDevInfo *FindDeviceName( const char *name )
 
     for( i = 0; predefinedNames[i].alsaName; i++ )
     {
-        if( strcmp( name, predefinedNames[i].alsaName ) == 0 )
-        {
-            return &predefinedNames[i];
-        }
+	if( strcmp( name, predefinedNames[i].alsaName ) == 0 )
+	{
+	    return &predefinedNames[i];
+	}
     }
 
     return NULL;
@@ -541,7 +538,7 @@ static int IgnorePlugin( const char *pluginId )
  **/
 static int OpenPcm( snd_pcm_t **pcmp, const char *name, snd_pcm_stream_t stream, int mode, int waitOnBusy )
 {
-    int tries = 0, maxTries = waitOnBusy ? busyRetries_ : 0;
+    int tries = 0, maxTries = waitOnBusy ? 100 : 0;
     int ret = snd_pcm_open( pcmp, name, stream, mode );
     for( tries = 0; tries < maxTries && -EBUSY == ret; ++tries )
     {
@@ -568,6 +565,7 @@ static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* d
     PaError result = 0;
     PaDeviceInfo *baseDeviceInfo = &devInfo->baseDeviceInfo;
     snd_pcm_t *pcm;
+    int canMmap = -1;
     PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
 
     /* Zero fields */
@@ -581,7 +579,8 @@ static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* d
             OpenPcm( &pcm, deviceName->alsaName, SND_PCM_STREAM_CAPTURE, blocking, 0 )
             >= 0 )
     {
-        if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_In, blocking, devInfo ) != paNoError )
+        if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_In, blocking, devInfo,
+                    &canMmap ) != paNoError )
         {
             /* Error */
             PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceName->alsaName));
@@ -594,7 +593,8 @@ static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* d
             OpenPcm( &pcm, deviceName->alsaName, SND_PCM_STREAM_PLAYBACK, blocking, 0 )
             >= 0 )
     {
-        if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_Out, blocking, devInfo ) != paNoError )
+        if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_Out, blocking, devInfo,
+                    &canMmap ) != paNoError )
         {
             /* Error */
             PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceName->alsaName));
@@ -602,6 +602,12 @@ static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* d
         }
     }
 
+    if( 0 == canMmap )
+    {
+        PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceName->alsaName));
+        goto end;
+    }
+
     baseDeviceInfo->structVersion = 2;
     baseDeviceInfo->hostApi = alsaApi->hostApiIndex;
     baseDeviceInfo->name = deviceName->name;
@@ -614,12 +620,8 @@ static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* d
     if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 )
     {
         /* Make device default if there isn't already one or it is the ALSA "default" device */
-        if( (baseApi->info.defaultInputDevice == paNoDevice || !strcmp(deviceName->alsaName,
-                        "default" )) && baseDeviceInfo->maxInputChannels > 0 )
-        {
+        if( baseApi->info.defaultInputDevice == paNoDevice && baseDeviceInfo->maxInputChannels > 0 )
             baseApi->info.defaultInputDevice = *devIdx;
-            PA_DEBUG(("Default input device: %s\n", deviceName->name));
-        }
         if( (baseApi->info.defaultOutputDevice == paNoDevice || !strcmp(deviceName->alsaName,
                         "default" )) && baseDeviceInfo->maxOutputChannels > 0 )
         {
@@ -707,7 +709,7 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
             {
                 hasCapture = 1;
             }
-
+            
             snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_PLAYBACK );
             if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
             {
@@ -765,7 +767,7 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
             int err = 0;
 
             char *alsaDeviceName, *deviceName;
-            const HwDevInfo *predefined = NULL;
+	    const HwDevInfo *predefined = NULL;
             snd_config_t *n = snd_config_iterator_entry( i ), * tp = NULL;;
 
             if( (err = snd_config_search( n, "type", &tp )) < 0 )
@@ -775,7 +777,7 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
                     ENSURE_(err, paUnanticipatedHostError);
                 }
             }
-            else
+            else 
             {
                 ENSURE_( snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError );
             }
@@ -802,22 +804,24 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
                         paInsufficientMemory );
             }
 
-            predefined = FindDeviceName( alsaDeviceName );
+	    predefined = FindDeviceName( alsaDeviceName );
 
             hwDevInfos[numDeviceNames - 1].alsaName = alsaDeviceName;
             hwDevInfos[numDeviceNames - 1].name = deviceName;
             hwDevInfos[numDeviceNames - 1].isPlug = 1;
 
-            if( predefined )
-            {
-                hwDevInfos[numDeviceNames - 1].hasPlayback = predefined->hasPlayback;
-                hwDevInfos[numDeviceNames - 1].hasCapture = predefined->hasCapture;
-            }
-            else
-            {
-                hwDevInfos[numDeviceNames - 1].hasPlayback = 1;
-                hwDevInfos[numDeviceNames - 1].hasCapture = 1;
-            }
+	    if( predefined )
+	    {
+		hwDevInfos[numDeviceNames - 1].hasPlayback =
+		    predefined->hasPlayback;
+		hwDevInfos[numDeviceNames - 1].hasCapture =
+		    predefined->hasCapture;
+	    }
+	    else
+	    {
+		hwDevInfos[numDeviceNames - 1].hasPlayback = 1;
+		hwDevInfos[numDeviceNames - 1].hasCapture = 1;
+	    }
         }
     }
     else
@@ -985,7 +989,7 @@ static snd_pcm_format_t Pa2AlsaFormat( PaSampleFormat paFormat )
 }
 
 /** Open an ALSA pcm handle.
- *
+ * 
  * The device to be open can be specified in a custom PaAlsaStreamInfo struct, or it will be a device number. In case of a
  * device number, it maybe specified through an env variable (PA_ALSA_PLUGHW) that we should open the corresponding plugin
  * device.
@@ -1004,7 +1008,7 @@ static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStr
     {
         int usePlug = 0;
         deviceInfo = GetDeviceInfo( hostApi, params->device );
-
+        
         /* If device name starts with hw: and PA_ALSA_PLUGHW is 1, we open the plughw device instead */
         if( !strncmp( "hw:", deviceInfo->alsaName, 3 ) && getenv( "PA_ALSA_PLUGHW" ) )
             usePlug = atoi( getenv( "PA_ALSA_PLUGHW" ) );
@@ -1044,7 +1048,7 @@ static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const
     PaSampleFormat hostFormat;
     snd_pcm_hw_params_t *hwParams;
     snd_pcm_hw_params_alloca( &hwParams );
-
+    
     if( !parameters->hostApiSpecificStreamInfo )
     {
         const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, parameters->device );
@@ -1188,9 +1192,6 @@ static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, Pa
     self->hostInterleaved = self->userInterleaved = !(userSampleFormat & paNonInterleaved);
     self->numUserChannels = params->channelCount;
     self->streamDir = streamDir;
-    self->canMmap = 0;
-    self->nonMmapBuffer = NULL;
-    self->nonMmapBufferSize = 0;
 
     if( !callbackMode && !self->userInterleaved )
     {
@@ -1251,43 +1252,14 @@ static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *se
 
     if( self->userInterleaved )
     {
-        accessMode          = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+        accessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
         alternateAccessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
-
-        /* test if MMAP supported */
-        self->canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ||
-                        snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0;
-
-        PA_DEBUG(("%s: device MMAP SND_PCM_ACCESS_MMAP_INTERLEAVED: %s\n", __FUNCTION__, (snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ? "YES" : "NO")));
-        PA_DEBUG(("%s: device MMAP SND_PCM_ACCESS_MMAP_NONINTERLEAVED: %s\n", __FUNCTION__, (snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0 ? "YES" : "NO")));
-
-        if (!self->canMmap)
-        {
-            accessMode          = SND_PCM_ACCESS_RW_INTERLEAVED;
-            alternateAccessMode = SND_PCM_ACCESS_RW_NONINTERLEAVED;
-        }
     }
     else
     {
-        accessMode          = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+        accessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
         alternateAccessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
-
-        /* test if MMAP supported */
-        self->canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ||
-                        snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0;
-
-        PA_DEBUG(("%s: device MMAP SND_PCM_ACCESS_MMAP_NONINTERLEAVED: %s\n", __FUNCTION__, (snd_pcm_hw_params_test_access( pcm, hwParams, accessMode ) >= 0 ? "YES" : "NO")));
-        PA_DEBUG(("%s: device MMAP SND_PCM_ACCESS_MMAP_INTERLEAVED: %s\n", __FUNCTION__, (snd_pcm_hw_params_test_access( pcm, hwParams, alternateAccessMode ) >= 0 ? "YES" : "NO")));
-
-        if (!self->canMmap)
-        {
-            accessMode          = SND_PCM_ACCESS_RW_NONINTERLEAVED;
-            alternateAccessMode = SND_PCM_ACCESS_RW_INTERLEAVED;
-        }
     }
-
-    PA_DEBUG(("%s: device can MMAP: %s\n", __FUNCTION__, (self->canMmap ? "YES" : "NO")));
-
     /* If requested access mode fails, try alternate mode */
     if( snd_pcm_hw_params_set_access( pcm, hwParams, accessMode ) < 0 )
     {
@@ -1295,7 +1267,14 @@ static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *se
         if( (err = snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode )) < 0)
         {
             result = paUnanticipatedHostError;
-            PaUtil_SetLastHostErrorInfo( paALSA, err, snd_strerror( err ) );
+            if( -EINVAL == err )
+            {
+                PaUtil_SetLastHostErrorInfo( paALSA, err, "PA ALSA requires that a device supports mmap access" );
+            }
+            else
+            {
+                PaUtil_SetLastHostErrorInfo( paALSA, err, snd_strerror( err ) );
+            }
             goto error;
         }
         /* Flip mode */
@@ -1309,7 +1288,7 @@ static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *se
     /* reject if there's no sample rate within 1% of the one requested */
     if( (fabs( *sampleRate - sr ) / *sampleRate) > 0.01 )
     {
-        PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
+        PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));                 
         PA_ENSURE( paInvalidSampleRate );
     }
 
@@ -1374,10 +1353,10 @@ static PaError PaAlsaStreamComponent_FinishConfigure( PaAlsaStreamComponent *sel
         ENSURE_( snd_pcm_sw_params_set_silence_threshold( self->pcm, swParams, 0 ), paUnanticipatedHostError );
         ENSURE_( snd_pcm_sw_params_set_silence_size( self->pcm, swParams, boundary ), paUnanticipatedHostError );
     }
-
+        
     ENSURE_( snd_pcm_sw_params_set_avail_min( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
     ENSURE_( snd_pcm_sw_params_set_xfer_align( self->pcm, swParams, 1 ), paUnanticipatedHostError );
-    ENSURE_( snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_ENABLE ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_MMAP ), paUnanticipatedHostError );
 
     /* Set the parameters! */
     ENSURE_( snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError );
@@ -1474,40 +1453,6 @@ static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frame
     return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate );
 }
 
-/** Align value in backward direction.
- *
- * @param v: Value to align.
- * @param align: Alignment.
- */
-static unsigned long PaAlsa_AlignBackward(unsigned long v, unsigned long align)
-{
-	return ((v - (align ? v % align : 0)));
-}
-
-/** Align value in forward direction.
- *
- * @param v: Value to align.
- * @param align: Alignment.
- */
-static unsigned long PaAlsa_AlignForward(unsigned long v, unsigned long align)
-{
-	unsigned long remainder = (align ? (v % align) : 0);
-	return (remainder != 0 ? v + (align - remainder) : v);
-}
-
-/** Get size of host buffer maintained from the number of user frames, sample rate and suggested latency. Minimum double buffering
- *  is maintained to allow 100% CPU usage inside user callback.
- *
- * @param userFramesPerBuffer: User buffer size in number of frames.
- * @param suggestedLatency: User provided desired latency.
- * @param sampleRate: Sample rate.
- */
-static unsigned long PaAlsa_GetFramesPerHostBuffer(unsigned long userFramesPerBuffer, PaTime suggestedLatency, double sampleRate)
-{
-	unsigned long frames = userFramesPerBuffer + PA_MAX( userFramesPerBuffer, (unsigned long)(suggestedLatency * sampleRate) );
-	return frames;
-}
-
 /** Determine size per host buffer.
  *
  * During this method call, the component's framesPerBuffer attribute gets computed, and the corresponding period size
@@ -1518,20 +1463,18 @@ static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamCompo
         unsigned long framesPerUserBuffer, double sampleRate, snd_pcm_hw_params_t* hwParams, int* accurate )
 {
     PaError result = paNoError;
-    unsigned long bufferSize, framesPerHostBuffer;
+    unsigned long bufferSize = params->suggestedLatency * sampleRate, framesPerHostBuffer;
     int dir = 0;
+    
+    {
+        snd_pcm_uframes_t tmp;
+        snd_pcm_hw_params_get_buffer_size_min( hwParams, &tmp );
+        bufferSize = PA_MAX( bufferSize, tmp );
+        snd_pcm_hw_params_get_buffer_size_max( hwParams, &tmp );
+        bufferSize = PA_MIN( bufferSize, tmp );
+    }
 
-    /* Calculate host buffer size */
-    bufferSize = PaAlsa_GetFramesPerHostBuffer(framesPerUserBuffer, params->suggestedLatency, sampleRate);
-
-    /* Log */
-    PA_DEBUG(( "%s: user-buffer (frames)           = %lu\n", __FUNCTION__, framesPerUserBuffer ));
-    PA_DEBUG(( "%s: user-buffer (sec)              = %f\n",  __FUNCTION__, (double)(framesPerUserBuffer / sampleRate) ));
-    PA_DEBUG(( "%s: suggested latency (sec)        = %f\n",  __FUNCTION__, params->suggestedLatency ));
-    PA_DEBUG(( "%s: suggested host buffer (frames) = %lu\n", __FUNCTION__, bufferSize ));
-    PA_DEBUG(( "%s: suggested host buffer (sec)    = %f\n",  __FUNCTION__, (double)(bufferSize / sampleRate) ));
-
-#ifdef PA_ALSA_USE_OBSOLETE_HOST_BUFFER_CALC
+    assert( bufferSize > 0 );
 
     if( framesPerUserBuffer != paFramesPerBufferUnspecified )
     {
@@ -1573,62 +1516,15 @@ static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamCompo
         }
     }
 
-#endif
-
-	{
-        unsigned numPeriods = numPeriods_, maxPeriods = 0, minPeriods = numPeriods_;
-
+    /* Using the base number of periods, we try to approximate the suggested latency (+1 period),
+       finding a combination of period/buffer size which best fits these constraints */
+    {
+        unsigned numPeriods = numPeriods_, maxPeriods = 0;
         /* It may be that the device only supports 2 periods for instance */
         dir = 0;
-        ENSURE_( snd_pcm_hw_params_get_periods_min( hwParams, &minPeriods, &dir ), paUnanticipatedHostError )
         ENSURE_( snd_pcm_hw_params_get_periods_max( hwParams, &maxPeriods, &dir ), paUnanticipatedHostError );
         assert( maxPeriods > 1 );
-
-        /* Clamp to min/max */
-        numPeriods = PA_MIN(maxPeriods, PA_MAX(minPeriods, numPeriods));
-
-        PA_DEBUG(( "%s: periods min = %lu, max = %lu, req = %lu \n", __FUNCTION__, minPeriods, maxPeriods, numPeriods ));
-
-#ifndef PA_ALSA_USE_OBSOLETE_HOST_BUFFER_CALC
-
-        /* Calculate period size */
-        framesPerHostBuffer = (bufferSize / numPeriods);
-
-        /* Align & test size */
-        if( framesPerUserBuffer != paFramesPerBufferUnspecified )
-        {
-            /* Align to user buffer size */
-            framesPerHostBuffer = PaAlsa_AlignForward(framesPerHostBuffer, framesPerUserBuffer);
-
-            /* Test (borrowed from older implementation) */
-            if( framesPerHostBuffer < framesPerUserBuffer )
-            {
-                assert( framesPerUserBuffer % framesPerHostBuffer == 0 );
-                if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
-                {
-                    if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 )
-                        framesPerHostBuffer *= 2;
-                    else 
-                    if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 )
-                        framesPerHostBuffer /= 2;
-                }
-            }
-            else
-            {
-                assert( framesPerHostBuffer % framesPerUserBuffer == 0 );
-                if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
-                {
-                    if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 )
-                        framesPerHostBuffer += framesPerUserBuffer;
-                    else 
-                    if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 )
-                        framesPerHostBuffer -= framesPerUserBuffer;
-                }
-            }
-        }
-#endif
-
-#ifdef PA_ALSA_USE_OBSOLETE_HOST_BUFFER_CALC
+        numPeriods = PA_MIN( maxPeriods, numPeriods );
 
         if( framesPerUserBuffer != paFramesPerBufferUnspecified )
         {
@@ -1686,49 +1582,37 @@ static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamCompo
         {
             framesPerHostBuffer = bufferSize / numPeriods;
         }
+    }
 
-        /* non-mmap mode needs a reasonably-sized buffer or it'll stutter */
-        if( !self->canMmap && framesPerHostBuffer < 2048 )
-            framesPerHostBuffer = 2048;
-#endif
-        PA_DEBUG(( "%s: suggested host buffer period   = %lu \n", __FUNCTION__, framesPerHostBuffer ));
-	}
-
+    assert( framesPerHostBuffer > 0 );
     {
-        /* Get min/max period sizes and adjust our chosen */
-        snd_pcm_uframes_t min = 0, max = 0, minmax_diff;
+        snd_pcm_uframes_t min = 0, max = 0;
         ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParams, &min, NULL ), paUnanticipatedHostError );
         ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParams, &max, NULL ), paUnanticipatedHostError );
-        minmax_diff = max - min;
 
         if( framesPerHostBuffer < min )
         {
-            PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__, framesPerHostBuffer, min ));
-            framesPerHostBuffer = ((minmax_diff == 2) ? min + 1 : min);
+            PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__,
+                        framesPerHostBuffer, min ));
+            framesPerHostBuffer = min;
         }
-        else 
-        if( framesPerHostBuffer > max )
+        else if( framesPerHostBuffer > max )
         {
-            PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__, framesPerHostBuffer, max ));
-            framesPerHostBuffer = ((minmax_diff == 2) ? max - 1 : max);
+            PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__,
+                        framesPerHostBuffer, max ));
+            framesPerHostBuffer = max;
         }
 
-		PA_DEBUG(( "%s: device period minimum          = %lu\n", __FUNCTION__, min ));
-		PA_DEBUG(( "%s: device period maximum          = %lu\n", __FUNCTION__, max ));
-		PA_DEBUG(( "%s: host buffer period             = %lu\n", __FUNCTION__, framesPerHostBuffer ));
-		PA_DEBUG(( "%s: host buffer period latency     = %f\n", __FUNCTION__, (double)(framesPerHostBuffer / sampleRate) ));
-
-        /* Try setting period size */
+        assert( framesPerHostBuffer >= min && framesPerHostBuffer <= max );
         dir = 0;
-        ENSURE_( snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ), paUnanticipatedHostError );
+        ENSURE_( snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ),
+                paUnanticipatedHostError );
         if( dir != 0 )
         {
             PA_DEBUG(( "%s: The configured period size is non-integer.\n", __FUNCTION__, dir ));
             *accurate = 0;
         }
     }
-
-    /* Set result */
     self->framesPerBuffer = framesPerHostBuffer;
 
 error:
@@ -1757,7 +1641,7 @@ error:
  * buffer size, this method tries it best to determine a period size which is a multiple of the user buffer size.
  *
  * The framesPerBuffer attributes of the individual capture and playback components of the stream are set to corresponding
- * values determined here. Since these should be reported as
+ * values determined here. Since these should be reported as 
  *
  * This is one of those blocks of code that will just take a lot of
  * refinement to be any good.
@@ -1841,15 +1725,12 @@ static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double
 
             while( optimalPeriodSize >= periodSize )
             {
-                if( snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 )
-                        >= 0 && snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback,
-                            optimalPeriodSize, 0 ) >= 0 )
-                {
+                if( snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 ) < 0 )
+                    continue;
+                if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, optimalPeriodSize, 0 ) >= 0 )
                     break;
-                }
                 optimalPeriodSize /= 2;
             }
-
             if( optimalPeriodSize > periodSize )
                 periodSize = optimalPeriodSize;
 
@@ -1942,13 +1823,12 @@ static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double
     PA_UNLESS( framesPerHostBuffer != 0, paInternalError );
     self->maxFramesPerHostBuffer = framesPerHostBuffer;
 
-    if( !self->playback.canMmap || !accurate )
+    if( !accurate )
     {
         /* Don't know the exact size per host buffer */
         *hostBufferSizeMode = paUtilBoundedHostBufferSize;
         /* Raise upper bound */
-        if( !accurate )
-            ++self->maxFramesPerHostBuffer;
+        ++self->maxFramesPerHostBuffer;
     }
 
 error:
@@ -2096,8 +1976,8 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
 
     PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer,
                 &inputLatency, &outputLatency, &hostBufferSizeMode ) );
-    hostInputSampleFormat = stream->capture.hostSampleFormat | (!stream->capture.hostInterleaved ? paNonInterleaved : 0);
-    hostOutputSampleFormat = stream->playback.hostSampleFormat | (!stream->playback.hostInterleaved ? paNonInterleaved : 0);
+    hostInputSampleFormat = stream->capture.hostSampleFormat;
+    hostOutputSampleFormat = stream->playback.hostSampleFormat;
 
     PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
                     numInputChannels, inputSampleFormat, hostInputSampleFormat,
@@ -2107,13 +1987,11 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
 
     /* Ok, buffer processor is initialized, now we can deduce it's latency */
     if( numInputChannels > 0 )
-        stream->streamRepresentation.streamInfo.inputLatency = inputLatency + (PaTime)(
-                PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor ) / sampleRate);
+        stream->streamRepresentation.streamInfo.inputLatency = inputLatency + PaUtil_GetBufferProcessorInputLatency(
+                &stream->bufferProcessor );
     if( numOutputChannels > 0 )
-        stream->streamRepresentation.streamInfo.outputLatency = outputLatency + (PaTime)(
-                PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor ) / sampleRate);
-
-    PA_DEBUG(( "%s: Stream: framesPerBuffer = %lu, maxFramesPerHostBuffer = %lu, latency = i(%f)/o(%f), \n", __FUNCTION__, framesPerBuffer, stream->maxFramesPerHostBuffer, stream->streamRepresentation.streamInfo.inputLatency, stream->streamRepresentation.streamInfo.outputLatency));
+        stream->streamRepresentation.streamInfo.outputLatency = outputLatency + PaUtil_GetBufferProcessorOutputLatency(
+                &stream->bufferProcessor );
 
     *s = (PaStream*)stream;
 
@@ -2157,7 +2035,7 @@ static void SilenceBuffer( PaAlsaStream *stream )
  * Depending on wether the stream is in callback or blocking mode, we will respectively start or simply
  * prepare the playback pcm. If the buffer has _not_ been primed, we will in callback mode prepare and
  * silence the buffer before starting playback. In blocking mode we simply prepare, as the playback will
- * be started automatically as the user writes to output.
+ * be started automatically as the user writes to output. 
  *
  * The capture pcm, however, will simply be prepared and started.
  */
@@ -2173,11 +2051,9 @@ static PaError AlsaStart( PaAlsaStream *stream, int priming )
             {
                 /* Buffer isn't primed, so prepare and silence */
                 ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
-                if( stream->playback.canMmap )
-                    SilenceBuffer( stream );
+                SilenceBuffer( stream );
             }
-            if( stream->playback.canMmap )
-                ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+            ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
         }
         else
             ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
@@ -2266,7 +2142,7 @@ error:
         AbortStream( stream );
     }
     stream->isActive = 0;
-
+    
     goto end;
 }
 
@@ -2275,9 +2151,7 @@ error:
 static PaError AlsaStop( PaAlsaStream *stream, int abort )
 {
     PaError result = paNoError;
-    /* XXX: snd_pcm_drain tends to lock up, avoid it until we find out more */
-    abort = 1;
-    /*
+    /* XXX: Seems that draining the dmix device may trigger a race condition in ALSA */
     if( stream->capture.pcm && !strcmp( Pa_GetDeviceInfo( stream->capture.device )->name,
                 "dmix" ) )
     {
@@ -2288,7 +2162,6 @@ static PaError AlsaStop( PaAlsaStream *stream, int abort )
     {
         abort = 1;
     }
-    */
 
     if( abort )
     {
@@ -2444,7 +2317,6 @@ static double GetStreamCpuLoad( PaStream* s )
 
 static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate )
 {
-    PaError result = paNoError;
     unsigned long approx = (unsigned long) sampleRate;
     int dir = 0;
     double fraction = sampleRate - approx;
@@ -2462,29 +2334,14 @@ static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwPara
             dir = 1;
     }
 
-    ENSURE_( snd_pcm_hw_params_set_rate( pcm, hwParams, approx, dir ), paUnanticipatedHostError );
-
-end:
-    return result;
-
-error:
-
-    /* Log */
-    {
-        unsigned int _min = 0, _max = 0; int _dir = 0;
-        ENSURE_( snd_pcm_hw_params_get_rate_min( hwParams, &_min, &_dir ), paUnanticipatedHostError );
-        ENSURE_( snd_pcm_hw_params_get_rate_max( hwParams, &_max, &_dir ), paUnanticipatedHostError );
-        PA_DEBUG(( "%s: SR min = %d, max = %d, req = %lu\n", __FUNCTION__, _min, _max, approx ));
-    }
-
-    goto end;
+    return snd_pcm_hw_params_set_rate( pcm, hwParams, approx, dir );
 }
 
 /* Return exact sample rate in param sampleRate */
 static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate )
 {
     unsigned int num, den;
-    int err;
+    int err; 
 
     assert( hwParams );
 
@@ -2522,7 +2379,6 @@ static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
     snd_pcm_status_t *st;
     PaTime now = PaUtil_GetTime();
     snd_timestamp_t t;
-    int restartAlsa = 0; /* do not restart Alsa by default */
 
     snd_pcm_status_alloca( &st );
 
@@ -2533,17 +2389,6 @@ static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
         {
             snd_pcm_status_get_trigger_tstamp( st, &t );
             self->underrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
-
-            if (!self->playback.canMmap)
-            {
-                if (snd_pcm_recover( self->playback.pcm, -EPIPE, 0 ) < 0)
-                {
-                    PA_DEBUG(( "%s: [playback] non-MMAP-PCM failed recovering from XRUN, will restart Alsa\n", __FUNCTION__ ));
-                    ++ restartAlsa; /* did not manage to recover */
-                }
-            }
-            else
-                ++ restartAlsa; /* always restart MMAPed device */
         }
     }
     if( self->capture.pcm )
@@ -2553,25 +2398,10 @@ static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
         {
             snd_pcm_status_get_trigger_tstamp( st, &t );
             self->overrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
-
-            if (!self->capture.canMmap)
-            {
-                if (snd_pcm_recover( self->capture.pcm, -EPIPE, 0 ) < 0)
-                {
-                    PA_DEBUG(( "%s: [capture] non-MMAP-PCM failed recovering from XRUN, will restart Alsa\n", __FUNCTION__ ));
-                    ++ restartAlsa; /* did not manage to recover */
-                }
-            }
-            else
-                ++ restartAlsa; /* always restart MMAPed device */
         }
     }
 
-    if( restartAlsa )
-    {
-        PA_DEBUG(( "%s: restarting Alsa to recover from XRUN\n", __FUNCTION__ ));
-        PA_ENSURE( AlsaRestart( self ) );
-    }
+    PA_ENSURE( AlsaRestart( self ) );
 
 end:
     return result;
@@ -2580,7 +2410,7 @@ error:
 }
 
 /** Decide if we should continue polling for specified direction, eventually adjust the poll timeout.
- *
+ * 
  */
 static PaError ContinuePoll( const PaAlsaStream *stream, StreamDirection streamDir, int *pollTimeout, int *continuePoll )
 {
@@ -2651,7 +2481,7 @@ static void OnExit( void *data )
     stream->callback_finished = 1;  /* Let the outside world know stream was stopped in callback */
     PA_DEBUG(( "%s: Stopping ALSA handles\n", __FUNCTION__ ));
     AlsaStop( stream, stream->callbackAbort );
-
+    
     PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ ));
 
     /* Eventually notify user all buffers have played */
@@ -2722,7 +2552,7 @@ static void CalculateTimeInfo( PaAlsaStream *stream, PaStreamCallbackTimeInfo *t
 static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self, unsigned long numFrames, int *xrun )
 {
     PaError result = paNoError;
-    int res = 0;
+    int res;
 
     /* @concern FullDuplex It is possible that only one direction is marked ready after polling, and processed
      * afterwards
@@ -2730,36 +2560,7 @@ static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self,
     if( !self->ready )
         goto end;
 
-    if( !self->canMmap && StreamDirection_Out == self->streamDir )
-    {
-        /* Play sound */
-        if( self->hostInterleaved )
-            res = snd_pcm_writei( self->pcm, self->nonMmapBuffer, numFrames );
-        else
-        {
-            void *bufs[self->numHostChannels];
-            int bufsize = snd_pcm_format_size( self->nativeFormat, self->framesPerBuffer + 1 );
-            unsigned char *buffer = self->nonMmapBuffer;
-            int i;
-            for( i = 0; i < self->numHostChannels; ++i )
-            {
-                bufs[i] = buffer;
-                buffer += bufsize;
-            }
-            res = snd_pcm_writen( self->pcm, bufs, numFrames );
-        }
-    }
-
-    if( self->canMmap )
-        res = snd_pcm_mmap_commit( self->pcm, self->offset, numFrames );
-    else
-    {
-        /* using realloc for optimisation
-        free( self->nonMmapBuffer );
-        self->nonMmapBuffer = NULL;
-        */
-    }
-
+    res = snd_pcm_mmap_commit( self->pcm, self->offset, numFrames );
     if( res == -EPIPE || res == -ESTRPIPE )
     {
         *xrun = 1;
@@ -2799,7 +2600,7 @@ static PaError PaAlsaStreamComponent_DoChannelAdaption( PaAlsaStreamComponent *s
     if( self->hostInterleaved )
     {
         int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
-        unsigned char *buffer = self->canMmap ? ExtractAddress( self->channelAreas, self->offset ) : self->nonMmapBuffer;
+        unsigned char *buffer = ExtractAddress( self->channelAreas, self->offset );
 
         /* Start after the last user channel */
         p = buffer + self->numUserChannels * swidth;
@@ -2930,12 +2731,6 @@ static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, st
         {
             *xrun = 1;
         }
-        else
-        if( revents & POLLHUP )
-        {
-            *xrun = 1;
-            PA_DEBUG(( "%s: revents has POLLHUP, processing as XRUN\n", __FUNCTION__ ));
-        }
         else
             self->ready = 1;
 
@@ -3012,14 +2807,13 @@ error:
  *
  * @param framesAvail Return the number of available frames
  * @param xrunOccurred Return whether an xrun has occurred
- */
+ */ 
 static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *framesAvail, int *xrunOccurred )
 {
     PaError result = paNoError;
     int pollPlayback = self->playback.pcm != NULL, pollCapture = self->capture.pcm != NULL;
     int pollTimeout = self->pollTimeout;
-    int xrun = 0, timeouts = 0;
-    int pollResults;
+    int xrun = 0;
 
     assert( self );
     assert( framesAvail );
@@ -3065,68 +2859,32 @@ static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *fr
             PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->playback, playbackPfds ) );
             totalFds += self->playback.nfds;
         }
-
-        pollResults = poll( self->pfds, totalFds, pollTimeout );
-
-        if( pollResults < 0 )
+        
+        if( poll( self->pfds, totalFds, pollTimeout ) < 0 )
         {
             /*  XXX: Depend on preprocessor condition? */
             if( errno == EINTR )
             {
                 /* gdb */
-                Pa_Sleep( 1 ); /* avoid hot loop */
                 continue;
             }
 
             /* TODO: Add macro for checking system calls */
             PA_ENSURE( paInternalError );
         }
-        else
-        if (pollResults == 0)
-        {
 
-           /* Suspended, paused or failed device can provide 0 poll results. To avoid deadloop in such situation
-            * we simply run counter 'timeouts' which detects 0 poll result and accumulates. As soon as 64 timouts
-            * are achieved we simply fail function with paTimedOut to notify waiting methods that device is not capable
-            * of providing audio data anymore and needs some corresponding recovery action.
-            * Note that 'timeouts' is reset to 0 if poll() managed to return non 0 results.
-            */
-
-            /*PA_DEBUG(( "%s: poll == 0 results, timed out, %d times left\n", __FUNCTION__, 64 - timeouts ));*/
-
-            ++ timeouts;
-            if (timeouts > 1) /* sometimes device times out, but normally once, so we do not sleep any time */
-            {
-                Pa_Sleep( 1 ); /* avoid hot loop */
-            }
-            /* not else ! */
-            if (timeouts >= 64) /* audio device not working, shall return error to notify waiters */
-            {
-				*framesAvail = 0; /* no frames available for processing */
-
-                PA_DEBUG(( "%s: poll timed out, returning error\n", __FUNCTION__, timeouts ));
-                PA_ENSURE( paTimedOut );
-            }
+        /* check the return status of our pfds */
+        if( pollCapture )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) );
         }
-        else
-        if (pollResults > 0)
+        if( pollPlayback )
         {
-            /* reset timouts counter */
-            timeouts = 0;
-
-            /* check the return status of our pfds */
-            if( pollCapture )
-            {
-                PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) );
-            }
-            if( pollPlayback )
-            {
-                PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) );
-            }
-            if( xrun )
-            {
-                break;
-            }
+            PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) );
+        }
+        if( xrun )
+        {
+            break;
         }
 
         /* @concern FullDuplex If only one of two pcms is ready we may want to compromise between the two.
@@ -3200,7 +2958,7 @@ error:
  *
  * Mmapped buffer space is acquired from ALSA, and registered with the buffer processor. Differences between the
  * number of host and user channels is taken into account.
- *
+ * 
  * @param numFrames On entrance the number of requested frames, on exit the number of contiguously accessible frames.
  */
 static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp,
@@ -3222,31 +2980,13 @@ static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* se
         goto end;
     }
 
-    if( self->canMmap )
-    {
-        ENSURE_( snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError );
-        /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */
-        self->channelAreas = (snd_pcm_channel_area_t *)areas;
-    }
-    else
-    {
-        unsigned int bufferSize = self->numHostChannels * snd_pcm_format_size( self->nativeFormat, *numFrames );
-        if (bufferSize > self->nonMmapBufferSize)
-        {
-            self->nonMmapBuffer = realloc(self->nonMmapBuffer, (self->nonMmapBufferSize = bufferSize));
-            if (!self->nonMmapBuffer)
-            {
-                result = paInsufficientMemory;
-                goto error;
-            }
-        }
-    }
+    ENSURE_( snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError );
 
     if( self->hostInterleaved )
     {
         int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
 
-        p = buffer = self->canMmap ? ExtractAddress( areas, self->offset ) : self->nonMmapBuffer;
+        p = buffer = ExtractAddress( areas, self->offset );
         for( i = 0; i < self->numUserChannels; ++i )
         {
             /* We're setting the channels up to userChannels, but the stride will be hostChannels samples */
@@ -3256,52 +2996,16 @@ static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* se
     }
     else
     {
-        if( self->canMmap )
+        for( i = 0; i < self->numUserChannels; ++i )
         {
-            for( i = 0; i < self->numUserChannels; ++i )
-            {
-                area = areas + i;
-                buffer = ExtractAddress( area, self->offset );
-                setChannel( bp, i, buffer, 1 );
-            }
-        }
-        else
-        {
-            unsigned int buf_per_ch_size = self->nonMmapBufferSize / self->numHostChannels;
-            buffer = self->nonMmapBuffer;
-            for( i = 0; i < self->numUserChannels; ++i )
-            {
-                setChannel( bp, i, buffer, 1 );
-                buffer += buf_per_ch_size;
-            }
+            area = areas + i;
+            buffer = ExtractAddress( area, self->offset );
+            setChannel( bp, i, buffer, 1 );
         }
     }
 
-    if( !self->canMmap && StreamDirection_In == self->streamDir )
-    {
-        /* Read sound */
-        int res;
-        if( self->hostInterleaved )
-            res = snd_pcm_readi( self->pcm, self->nonMmapBuffer, *numFrames );
-        else
-        {
-            void *bufs[self->numHostChannels];
-            unsigned int buf_per_ch_size = self->nonMmapBufferSize / self->numHostChannels;
-            unsigned char *buffer = self->nonMmapBuffer;
-            int i;
-            for( i = 0; i < self->numHostChannels; ++i )
-            {
-                bufs[i] = buffer;
-                buffer += buf_per_ch_size;
-            }
-            res = snd_pcm_readn( self->pcm, bufs, *numFrames );
-        }
-        if( res == -EPIPE || res == -ESTRPIPE )
-        {
-            *xrun = 1;
-            *numFrames = 0;
-        }
-    }
+    /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */
+    self->channelAreas = (snd_pcm_channel_area_t *)areas;
 
 end:
 error:
@@ -3338,13 +3042,13 @@ static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* num
     if( self->capture.pcm && self->capture.ready )
     {
         captureFrames = *numFrames;
-        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames,
+        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames, 
                     &xrun ) );
     }
     if( self->playback.pcm && self->playback.ready )
     {
         playbackFrames = *numFrames;
-        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames,
+        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames, 
                     &xrun ) );
     }
     if( xrun )
@@ -3369,7 +3073,7 @@ static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* num
         {
             PA_DEBUG(( "%s: playbackFrames: %lu, playback.ready: %d\n", __FUNCTION__, playbackFrames, self->playback.ready ));
         }
-
+        
         commonFrames = 0;
         goto end;
     }
@@ -3406,7 +3110,7 @@ static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* num
             PaUtil_SetNoOutput( &self->bufferProcessor );
         }
     }
-
+    
 end:
     *numFrames = commonFrames;
 error:
@@ -3452,7 +3156,7 @@ static void *CallbackThreadFunc( void *userData )
     if( stream->primeBuffers )
     {
         snd_pcm_sframes_t avail;
-
+        
         if( stream->playback.pcm )
             ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
         if( stream->capture.pcm && !stream->pcmsSynced )
@@ -3495,7 +3199,7 @@ static void *CallbackThreadFunc( void *userData )
             stream->callbackAbort = (paAbort == callbackResult);
             if( stream->callbackAbort ||
                     /** @concern BlockAdaption: Go on if adaption buffers are empty */
-                    PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+                    PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) 
             {
                 goto end;
             }
@@ -3682,7 +3386,7 @@ static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frame
     snd_pcm_uframes_t framesGot, framesAvail;
     const void *userBuffer;
     snd_pcm_t *save = stream->capture.pcm;
-
+    
     assert( stream );
 
     PA_UNLESS( stream->playback.pcm, paCanNotWriteToAnInputOnlyStream );
@@ -3815,31 +3519,10 @@ void PaAlsa_EnableWatchdog( PaStream *s, int enable )
 }
 #endif
 
-static PaError GetAlsaStreamPointer( PaStream* s, PaAlsaStream** stream )
-{
-    PaError result = paNoError;
-    PaUtilHostApiRepresentation* hostApi;
-    PaAlsaHostApiRepresentation* alsaHostApi;
-
-    PA_ENSURE( PaUtil_ValidateStreamPointer( s ) );
-    PA_ENSURE( PaUtil_GetHostApiRepresentation( &hostApi, paALSA ) );
-    alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
-
-    PA_UNLESS( PA_STREAM_REP( s )->streamInterface == &alsaHostApi->callbackStreamInterface
-            || PA_STREAM_REP( s )->streamInterface == &alsaHostApi->blockingStreamInterface,
-        paIncompatibleStreamHostApi );
-
-    *stream = (PaAlsaStream*)s;
-error:
-    return paNoError;
-}
-
 PaError PaAlsa_GetStreamInputCard(PaStream* s, int* card) {
-    PaAlsaStream *stream;
-    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream *) s;
     snd_pcm_info_t* pcmInfo;
-
-    PA_ENSURE( GetAlsaStreamPointer( s, &stream ) );
+    PaError result = paNoError;
 
     /* XXX: More descriptive error? */
     PA_UNLESS( stream->capture.pcm, paDeviceUnavailable );
@@ -3853,11 +3536,9 @@ error:
 }
 
 PaError PaAlsa_GetStreamOutputCard(PaStream* s, int* card) {
-    PaAlsaStream *stream;
-    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream *) s;
     snd_pcm_info_t* pcmInfo;
-
-    PA_ENSURE( GetAlsaStreamPointer( s, &stream ) );
+    PaError result = paNoError;
 
     /* XXX: More descriptive error? */
     PA_UNLESS( stream->playback.pcm, paDeviceUnavailable );
@@ -3869,9 +3550,3 @@ PaError PaAlsa_GetStreamOutputCard(PaStream* s, int* card) {
 error:
     return result;
 }
-
-PaError PaAlsa_SetRetriesBusy( int retries )
-{
-    busyRetries_ = retries;
-    return paNoError;
-}
diff --git a/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp b/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp
index 08c55eacf..8dfefbd67 100644
--- a/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp
+++ b/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp
@@ -156,7 +156,7 @@
 // We only need IASIOThiscallResolver at all if we are on Win32. For other
 // platforms we simply bypass the IASIOThiscallResolver definition to allow us
 // to be safely #include'd whatever the platform to keep client code portable
-#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(_WIN64)
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
 
 
 // If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
@@ -276,7 +276,6 @@ extern IASIO* theAsioDriver;
                           "call *"#funcOffset"(%%edx)\n\t"                  \
                           :"=a"(resultName) /* Output Operands */           \
                           :"c"(thisPtr)     /* Input Operands */            \
-                          : "%edx" /* Clobbered Registers */                \
                          );                                                 \
 
 
@@ -287,7 +286,6 @@ extern IASIO* theAsioDriver;
                           :                 /* Output Operands */           \
                           :"r"(param1),     /* Input Operands */            \
                            "c"(thisPtr)                                     \
-                          : "%edx" /* Clobbered Registers */                \
                          );                                                 \
 
 
@@ -298,25 +296,20 @@ extern IASIO* theAsioDriver;
                           :"=a"(resultName) /* Output Operands */           \
                           :"r"(param1),     /* Input Operands */            \
                            "c"(thisPtr)                                     \
-                          : "%edx" /* Clobbered Registers */                \
                           );                                                \
 
 
 #define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )   \
-    do {                                                                    \
-    double param1f64 = param1; /* Cast explicitly to double */              \
-    double *param1f64Ptr = &param1f64; /* Make pointer to address */        \
-     __asm__ __volatile__ ("pushl 4(%1)\n\t"                                \
-                           "pushl (%1)\n\t"                                 \
-                           "movl (%2), %%edx\n\t"                           \
-                           "call *"#funcOffset"(%%edx);\n\t"                \
-                           : "=a"(resultName) /* Output Operands */         \
-                           : "r"(param1f64Ptr),  /* Input Operands */       \
-                           "c"(thisPtr),                                    \
-                           "m"(*param1f64Ptr) /* Using address */           \
-                           : "%edx" /* Clobbered Registers */               \
-                           );                                               \
-    } while (0);                                                            \
+    __asm__ __volatile__ ("pushl 4(%1)\n\t"                                 \
+                          "pushl (%1)\n\t"                                  \
+                          "movl (%2), %%edx\n\t"                            \
+                          "call *"#funcOffset"(%%edx);\n\t"                 \
+                          :"=a"(resultName) /* Output Operands */           \
+                          :"a"(&param1),    /* Input Operands */            \
+                           /* Note: Using "r" above instead of "a" fails */ \
+                           /* when using GCC 3.3.3, and maybe later versions*/\
+                           "c"(thisPtr)                                     \
+                          );                                                \
 
 
 #define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )  \
@@ -328,7 +321,6 @@ extern IASIO* theAsioDriver;
                           :"r"(param2),     /* Input Operands */            \
                            "r"(param1),                                     \
                            "c"(thisPtr)                                     \
-                          : "%edx" /* Clobbered Registers */                \
                           );                                                \
 
 
@@ -345,7 +337,6 @@ extern IASIO* theAsioDriver;
                            "r"(param2),                                     \
                            "r"(param1),                                     \
                            "c"(thisPtr)                                     \
-                          : "%edx" /* Clobbered Registers */                \
                           );                                                \
 
 #endif
diff --git a/portaudio/src/hostapi/asio/iasiothiscallresolver.h b/portaudio/src/hostapi/asio/iasiothiscallresolver.h
index 21d53b320..2ecfed799 100644
--- a/portaudio/src/hostapi/asio/iasiothiscallresolver.h
+++ b/portaudio/src/hostapi/asio/iasiothiscallresolver.h
@@ -111,7 +111,7 @@
 // We only need IASIOThiscallResolver at all if we are on Win32. For other
 // platforms we simply bypass the IASIOThiscallResolver definition to allow us
 // to be safely #include'd whatever the platform to keep client code portable
-#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) && !defined(_WIN64)
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
 
 
 // If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
diff --git a/portaudio/src/hostapi/asio/pa_asio.cpp b/portaudio/src/hostapi/asio/pa_asio.cpp
index f4786ee3e..4b3fb68e0 100644
--- a/portaudio/src/hostapi/asio/pa_asio.cpp
+++ b/portaudio/src/hostapi/asio/pa_asio.cpp
@@ -1,12 +1,10 @@
 /*
- * $Id: pa_asio.cpp 1525 2010-07-14 06:45:25Z rossb $
+ * $Id: pa_asio.cpp 1230 2007-06-15 16:16:33Z rossb $
  * Portable Audio I/O Library for ASIO Drivers
  *
  * Author: Stephane Letz
  * Based on the Open Source API proposed by Ross Bencina
  * Copyright (c) 2000-2002 Stephane Letz, Phil Burk, Ross Bencina
- * Blocking i/o implementation by Sven Fischer, Institute of Hearing
- * Technology and Audiology (www.hoertechnik-audiologie.de)
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -73,18 +71,18 @@
 */
 
 /** @file
-    @ingroup hostapi_src
+	@ingroup hostapi_src
 
     Note that specific support for paInputUnderflow, paOutputOverflow and
     paNeverDropInput is not necessary or possible with this driver due to the
     synchronous full duplex double-buffered architecture of ASIO.
 
-    @todo implement host api specific extension to set i/o buffer sizes in frames
+    @todo check that CoInitialize()/CoUninitialize() are always correctly
+        paired, even in error cases.
 
-    @todo review ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable
+    @todo implement host api specific extension to set i/o buffer sizes in frames
 
-    @todo review Blocking i/o latency computations in OpenStream(), changing ring 
-          buffer to a non-power-of-two structure could reduce blocking i/o latency.
+    @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable
 
     @todo implement IsFormatSupported
 
@@ -122,7 +120,6 @@
 #include <assert.h>
 #include <string.h>
 //#include <values.h>
-#include <new>
 
 #include <windows.h>
 #include <mmsystem.h>
@@ -136,7 +133,6 @@
 #include "pa_cpuload.h"
 #include "pa_process.h"
 #include "pa_debugprint.h"
-#include "pa_ringbuffer.h"
 
 /* This version of pa_asio.cpp is currently only targetted at Win32,
    It would require a few tweaks to work with pre-OS X Macintosh.
@@ -168,32 +164,18 @@
 #endif
 */
 
-
-/* winmm.lib is needed for timeGetTime() (this is in winmm.a if you're using gcc) */
-#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
-#pragma comment(lib, "winmm.lib")
-#endif
-
-
-/* external reference to ASIO SDK's asioDrivers.
-
- This is a bit messy because we want to explicitly manage 
- allocation/deallocation of this structure, but some layers of the SDK 
- which we currently use (eg the implementation in asio.cpp) still
- use this global version.
-
- For now we keep it in sync with our local instance in the host
- API representation structure, but later we should be able to remove
- all dependence on it.
-*/
-extern AsioDrivers* asioDrivers;
+/* external references */
+extern AsioDrivers* asioDrivers ;
+bool loadAsioDriver(char *name);
 
 
 /* We are trying to be compatible with CARBON but this has not been thoroughly tested. */
-/* not tested at all since new V19 code was introduced. */
+/* not tested at all since new code was introduced. */
 #define CARBON_COMPATIBLE  (0)
 
 
+
+
 /* prototypes for functions declared in this file */
 
 extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex );
@@ -224,14 +206,6 @@ static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long
 static signed long GetStreamReadAvailable( PaStream* stream );
 static signed long GetStreamWriteAvailable( PaStream* stream );
 
-/* Blocking i/o callback function. */
-static int BlockingIoPaCallback(const void                     *inputBuffer    ,
-                                      void                     *outputBuffer   ,
-                                      unsigned long             framesPerBuffer,
-                                const PaStreamCallbackTimeInfo *timeInfo       ,
-                                      PaStreamCallbackFlags     statusFlags    ,
-                                      void                     *userData       );
-
 /* our ASIO callback functions */
 
 static void bufferSwitch(long index, ASIOBool processNow);
@@ -296,12 +270,12 @@ static const char* PaAsio_GetAsioErrorText( ASIOError asioError )
 
 // Atomic increment and decrement operations
 #if MAC
-    /* need to be implemented on Mac */
-    inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));}
-    inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));}
+	/* need to be implemented on Mac */
+	inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));}
+	inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));}
 #elif WINDOWS
-    inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));}
-    inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));}
+	inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));}
+	inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));}
 #endif
 
 
@@ -326,7 +300,6 @@ typedef struct
 
     PaUtilAllocationGroup *allocations;
 
-    AsioDrivers *asioDrivers;
     void *systemSpecific;
     
     /* the ASIO C API only allows one ASIO driver to be open at a time,
@@ -350,7 +323,7 @@ PaAsioHostApiRepresentation;
     Retrieve <driverCount> driver names from ASIO, returned in a char**
     allocated in <group>.
 */
-static char **GetAsioDriverNames( PaAsioHostApiRepresentation *asioHostApi, PaUtilAllocationGroup *group, long driverCount )
+static char **GetAsioDriverNames( PaUtilAllocationGroup *group, long driverCount )
 {
     char **result = 0;
     int i;
@@ -368,7 +341,7 @@ static char **GetAsioDriverNames( PaAsioHostApiRepresentation *asioHostApi, PaUt
     for( i=0; i<driverCount; ++i )
         result[i] = result[0] + (32 * i);
 
-    asioHostApi->asioDrivers->getDriverNames( result, driverCount );
+    asioDrivers->getDriverNames( result, driverCount );
 
 error:
     return result;
@@ -944,7 +917,7 @@ PaAsioDeviceInfo;
 
 
 PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device,
-        long *minLatency, long *maxLatency, long *preferredLatency, long *granularity )
+		long *minLatency, long *maxLatency, long *preferredLatency, long *granularity )
 {
     PaError result;
     PaUtilHostApiRepresentation *hostApi;
@@ -971,45 +944,23 @@ PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device,
     return result;
 }
 
-/* Unload whatever we loaded in LoadAsioDriver().
-   Also balance the call to CoInitialize(0).
-*/
-static void UnloadAsioDriver( void )
-{
-	ASIOExit();
-	CoUninitialize();
-}
+
 
 /*
     load the asio driver named by <driverName> and return statistics about
     the driver in info. If no error occurred, the driver will remain open
-    and must be closed by the called by calling UnloadAsioDriver() - if an error
-    is returned the driver will already be unloaded.
+    and must be closed by the called by calling ASIOExit() - if an error
+    is returned the driver will already be closed.
 */
-static PaError LoadAsioDriver( PaAsioHostApiRepresentation *asioHostApi, const char *driverName,
+static PaError LoadAsioDriver( const char *driverName,
         PaAsioDriverInfo *driverInfo, void *systemSpecific )
 {
     PaError result = paNoError;
     ASIOError asioError;
     int asioIsInitialized = 0;
 
-    /* 
-	ASIO uses CoCreateInstance() to load a driver. That requires that
-	CoInitialize(0) be called for every thread that loads a driver.
-	It is OK to call CoInitialize(0) multiple times form one thread as long
-	as it is balanced by a call to CoUninitialize(). See UnloadAsioDriver().
-
-	The V18 version called CoInitialize() starting on 2/19/02.
-	That was removed from PA V19 for unknown reasons.
-	Phil Burk added it back on 6/27/08 so that JSyn would work.
-    */
-	CoInitialize( 0 );
-
-    if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(driverName) ) )
+    if( !loadAsioDriver( const_cast<char*>(driverName) ) )
     {
-		/* If this returns an error then it might be because CoInitialize(0) was removed.
-		  It should be called right before this.
-	    */
         result = paUnanticipatedHostError;
         PA_ASIO_SET_LAST_HOST_ERROR( 0, "Failed to load ASIO driver" );
         goto error;
@@ -1055,10 +1006,8 @@ static PaError LoadAsioDriver( PaAsioHostApiRepresentation *asioHostApi, const c
 
 error:
     if( asioIsInitialized )
-	{
-		ASIOExit();
-	}
-	CoUninitialize();
+        ASIOExit();
+
     return result;
 }
 
@@ -1090,8 +1039,6 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
         goto error;
     }
 
-    asioHostApi->asioDrivers = 0; /* avoid surprises in our error handler below */
-
     asioHostApi->allocations = PaUtil_CreateAllocationGroup();
     if( !asioHostApi->allocations )
     {
@@ -1099,25 +1046,6 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
         goto error;
     }
 
-    /* Allocate the AsioDrivers() driver list (class from ASIO SDK) */
-    try
-    {
-        asioHostApi->asioDrivers = new AsioDrivers(); /* calls CoInitialize(0) */
-    } 
-    catch (std::bad_alloc)
-    {
-        asioHostApi->asioDrivers = 0;
-    }
-    /* some implementations of new (ie MSVC, see http://support.microsoft.com/?kbid=167733)
-       don't throw std::bad_alloc, so we also explicitly test for a null return. */
-    if( asioHostApi->asioDrivers == 0 )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    asioDrivers = asioHostApi->asioDrivers; /* keep SDK global in sync until we stop depending on it */
-
     asioHostApi->systemSpecific = 0;
     asioHostApi->openAsioDeviceIndex = paNoDevice;
 
@@ -1131,19 +1059,23 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
     #ifdef WINDOWS
         /* use desktop window as system specific ptr */
         asioHostApi->systemSpecific = GetDesktopWindow();
+        CoInitialize(NULL);
     #endif
 
+    /* MUST BE CHECKED : to force fragments loading on Mac */
+    loadAsioDriver( "dummy" ); 
+
     /* driverCount is the number of installed drivers - not necessarily
         the number of installed physical devices. */
     #if MAC
-        driverCount = asioHostApi->asioDrivers->getNumFragments();
+        driverCount = asioDrivers->getNumFragments();
     #elif WINDOWS
-        driverCount = asioHostApi->asioDrivers->asioGetNumDev();
+        driverCount = asioDrivers->asioGetNumDev();
     #endif
 
     if( driverCount > 0 )
     {
-        names = GetAsioDriverNames( asioHostApi, asioHostApi->allocations, driverCount );
+        names = GetAsioDriverNames( asioHostApi->allocations, driverCount );
         if( !names )
         {
             result = paInsufficientMemory;
@@ -1170,7 +1102,7 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
             goto error;
         }
 
-        IsDebuggerPresent_ = (IsDebuggerPresentPtr)GetProcAddress( LoadLibrary( "Kernel32.dll" ), "IsDebuggerPresent" );
+		IsDebuggerPresent_ = GetProcAddress( LoadLibrary( "Kernel32.dll" ), "IsDebuggerPresent" );
 
         for( i=0; i < driverCount; ++i )
         {
@@ -1188,6 +1120,7 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
                 || strcmp (names[i],"ASIO Multimedia Driver")          == 0
                 || strncmp(names[i],"Premiere",8)                      == 0   //"Premiere Elements Windows Sound 1.0"
                 || strncmp(names[i],"Adobe",5)                         == 0   //"Adobe Default Windows Sound 1.5"
+                || strncmp(names[i],"ReaRoute ASIO",13)                == 0   //Reaper www.reaper.fm <- fix your stuff man.
                )
             {
                 PA_DEBUG(("BLACKLISTED!!!\n"));
@@ -1208,7 +1141,7 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
 
 
             /* Attempt to load the asio driver... */
-            if( LoadAsioDriver( asioHostApi, names[i], &paAsioDriverInfo, asioHostApi->systemSpecific ) == paNoError )
+            if( LoadAsioDriver( names[i], &paAsioDriverInfo, asioHostApi->systemSpecific ) == paNoError )
             {
                 PaAsioDeviceInfo *asioDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
                 PaDeviceInfo *deviceInfo = &asioDeviceInfo->commonDeviceInfo;
@@ -1300,7 +1233,7 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
                 if( !asioDeviceInfo->asioChannelInfos )
                 {
                     result = paInsufficientMemory;
-                    goto error_unload;
+                    goto error;
                 }
 
                 int a;
@@ -1313,7 +1246,7 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
                     {
                         result = paUnanticipatedHostError;
                         PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
-                        goto error_unload;
+                        goto error;
                     }
                 }
 
@@ -1326,13 +1259,13 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
                     {
                         result = paUnanticipatedHostError;
                         PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
-                        goto error_unload;
+                        goto error;
                     }
                 }
 
 
                 /* unload the driver */
-                UnloadAsioDriver();
+                ASIOExit();
 
                 (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
                 ++(*hostApi)->info.deviceCount;
@@ -1369,9 +1302,6 @@ PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
 
     return result;
 
-error_unload:
-	UnloadAsioDriver();
-
 error:
     if( asioHostApi )
     {
@@ -1381,9 +1311,6 @@ error:
             PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
         }
 
-        delete asioHostApi->asioDrivers;
-        asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */
-
         PaUtil_FreeMemory( asioHostApi );
     }
     return result;
@@ -1396,7 +1323,7 @@ static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
 
     /*
         IMPLEMENT ME:
-            - clean up any resources not handled by the allocation group (need to review if there are any)
+            - clean up any resources not handled by the allocation group
     */
 
     if( asioHostApi->allocations )
@@ -1405,9 +1332,6 @@ static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
         PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
     }
 
-    delete asioHostApi->asioDrivers; /* calls CoUninitialize() */
-    asioDrivers = 0; /* keep SDK global in sync until we stop depending on it */
-
     PaUtil_FreeMemory( asioHostApi );
 }
 
@@ -1494,7 +1418,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
     /* if an ASIO device is open we can only get format information for the currently open device */
 
     if( asioHostApi->openAsioDeviceIndex != paNoDevice 
-            && asioHostApi->openAsioDeviceIndex != asioDeviceIndex )
+			&& asioHostApi->openAsioDeviceIndex != asioDeviceIndex )
     {
         return paDeviceUnavailable;
     }
@@ -1506,7 +1430,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
     /* open the device if it's not already open */
     if( asioHostApi->openAsioDeviceIndex == paNoDevice )
     {
-        result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
+        result = LoadAsioDriver( asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
                 driverInfo, asioHostApi->systemSpecific );
         if( result != paNoError )
             return result;
@@ -1544,7 +1468,7 @@ done:
     /* close the device if it wasn't already open */
     if( asioHostApi->openAsioDeviceIndex == paNoDevice )
     {
-        UnloadAsioDriver(); /* not sure if we should check for errors here */
+        ASIOExit(); /* not sure if we should check for errors here */
     }
 
     if( result == paNoError )
@@ -1555,40 +1479,6 @@ done:
 
 
 
-/** A data structure specifically for storing blocking i/o related data. */
-typedef struct PaAsioStreamBlockingState
-{
-    int stopFlag; /**< Flag indicating that block processing is to be stopped. */
-
-    unsigned long writeBuffersRequested; /**< The number of available output buffers, requested by the #WriteStream() function. */
-    unsigned long readFramesRequested;   /**< The number of available input frames, requested by the #ReadStream() function. */
-
-    int writeBuffersRequestedFlag; /**< Flag to indicate that #WriteStream() has requested more output buffers to be available. */
-    int readFramesRequestedFlag;   /**< Flag to indicate that #ReadStream() requires more input frames to be available. */
-
-    HANDLE writeBuffersReadyEvent; /**< Event to signal that requested output buffers are available. */
-    HANDLE readFramesReadyEvent;   /**< Event to signal that requested input frames are available. */
-
-    void *writeRingBufferData; /**< The actual ring buffer memory, used by the output ring buffer. */
-    void *readRingBufferData;  /**< The actual ring buffer memory, used by the input ring buffer. */
-
-    PaUtilRingBuffer writeRingBuffer; /**< Frame-aligned blocking i/o ring buffer to store output data (interleaved user format). */
-    PaUtilRingBuffer readRingBuffer;  /**< Frame-aligned blocking i/o ring buffer to store input data (interleaved user format). */
-
-    long writeRingBufferInitialFrames; /**< The initial number of silent frames within the output ring buffer. */
-
-    const void **writeStreamBuffer; /**< Temp buffer, used by #WriteStream() for handling non-interleaved data. */
-    void **readStreamBuffer; /**< Temp buffer, used by #ReadStream() for handling non-interleaved data. */
-
-    PaUtilBufferProcessor bufferProcessor; /**< Buffer processor, used to handle the blocking i/o ring buffers. */
-
-    int outputUnderflowFlag; /**< Flag to signal an output underflow from within the callback function. */
-    int inputOverflowFlag; /**< Flag to signal an input overflow from within the callback function. */
-}
-PaAsioStreamBlockingState;
-
-
-
 /* PaAsioStream - a stream data structure specifically for this implementation */
 
 typedef struct PaAsioStream
@@ -1625,7 +1515,6 @@ typedef struct PaAsioStream
     HANDLE completedBuffersPlayedEvent;
 
     bool streamFinishedCallbackCalled;
-    int isStopped;
     volatile int isActive;
     volatile bool zeroOutput; /* all future calls to the callback will output silence */
 
@@ -1633,8 +1522,6 @@ typedef struct PaAsioStream
     volatile long reenterError;
 
     PaStreamCallbackFlags callbackFlags;
-
-    PaAsioStreamBlockingState *blockingState; /**< Blocking i/o data struct, or NULL when using callback interface. */
 }
 PaAsioStream;
 
@@ -1734,15 +1621,15 @@ static PaError ValidateAsioSpecificStreamInfo(
         int deviceChannelCount,
         int **channelSelectors )
 {
-    if( streamInfo )
-    {
-        if( streamInfo->size != sizeof( PaAsioStreamInfo )
-                || streamInfo->version != 1 )
-        {
-            return paIncompatibleHostApiSpecificStreamInfo;
-        }
+	if( streamInfo )
+	{
+	    if( streamInfo->size != sizeof( PaAsioStreamInfo )
+	            || streamInfo->version != 1 )
+	    {
+	        return paIncompatibleHostApiSpecificStreamInfo;
+	    }
 
-        if( streamInfo->flags & paAsioUseChannelSelectors )
+	    if( streamInfo->flags & paAsioUseChannelSelectors )
             *channelSelectors = streamInfo->channelSelectors;
 
         if( !(*channelSelectors) )
@@ -1754,101 +1641,9 @@ static PaError ValidateAsioSpecificStreamInfo(
                 return paInvalidChannelCount;
              }           
         }
-    }
-
-    return paNoError;
-}
-
-
-static bool IsUsingExternalClockSource()
-{
-    bool result = false;
-    ASIOError asioError;
-    ASIOClockSource clocks[32];
-    long numSources=32;
-
-    /* davidv: listing ASIO Clock sources. there is an ongoing investigation by
-       me about whether or not to call ASIOSetSampleRate if an external Clock is
-       used. A few drivers expected different things here */
-    
-    asioError = ASIOGetClockSources(clocks, &numSources);
-    if( asioError != ASE_OK ){
-        PA_DEBUG(("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText(asioError) ));
-    }else{
-        PA_DEBUG(("INFO ASIOGetClockSources listing %d clocks\n", numSources ));
-        for (int i=0;i<numSources;++i){
-            PA_DEBUG(("ASIOClockSource%d %s current:%d\n", i, clocks[i].name, clocks[i].isCurrentSource ));
-           
-            if (clocks[i].isCurrentSource)
-                result = true;
-        }
-    }
+	}
 
-    return result;
-}
-
-
-static PaError ValidateAndSetSampleRate( double sampleRate )
-{
-    PaError result = paNoError;
-    ASIOError asioError;
-
-    // check that the device supports the requested sample rate 
-
-    asioError = ASIOCanSampleRate( sampleRate );
-    PA_DEBUG(("ASIOCanSampleRate(%f):%d\n", sampleRate, asioError ));
-
-    if( asioError != ASE_OK )
-    {
-        result = paInvalidSampleRate;
-        PA_DEBUG(("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
-        goto error;
-    }
-
-    // retrieve the current sample rate, we only change to the requested
-    // sample rate if the device is not already in that rate.
-
-    ASIOSampleRate oldRate;
-    asioError = ASIOGetSampleRate(&oldRate);
-    if( asioError != ASE_OK )
-    {
-        result = paInvalidSampleRate;
-        PA_DEBUG(("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
-        goto error;
-    }
-    PA_DEBUG(("ASIOGetSampleRate:%f\n",oldRate));
-
-    if (oldRate != sampleRate){
-        /* Set sample rate */
-
-        PA_DEBUG(("before ASIOSetSampleRate(%f)\n",sampleRate));
-
-        /*
-            If you have problems with some drivers when externally clocked, 
-            try switching on the following line and commenting out the one after it.
-            See IsUsingExternalClockSource() for more info.
-        */
-        //if( IsUsingExternalClockSource() ){
-        if( false ){
-            asioError = ASIOSetSampleRate( 0 );
-        }else{
-            asioError = ASIOSetSampleRate( sampleRate );
-        }
-        if( asioError != ASE_OK )
-        {
-            result = paInvalidSampleRate;
-            PA_DEBUG(("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
-            goto error;
-        }
-        PA_DEBUG(("after ASIOSetSampleRate(%f)\n",sampleRate));
-    }
-    else
-    {
-        PA_DEBUG(("No Need to change SR\n"));
-    }
-
-error:
-    return result;
+	return paNoError;
 }
 
 
@@ -1883,38 +1678,23 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     PaAsioDriverInfo *driverInfo;
     int *inputChannelSelectors = 0;
     int *outputChannelSelectors = 0;
-
-    /* Are we using blocking i/o interface? */
-    int usingBlockingIo = ( !streamCallback ) ? TRUE : FALSE;
-    /* Blocking i/o stuff */
-    long lBlockingBufferSize     = 0; /* Desired ring buffer size in samples. */
-    long lBlockingBufferSizePow2 = 0; /* Power-of-2 rounded ring buffer size. */
-    long lBytesPerFrame          = 0; /* Number of bytes per input/output frame. */
-    int blockingWriteBuffersReadyEventInitialized = 0; /* Event init flag. */
-    int blockingReadFramesReadyEventInitialized   = 0; /* Event init flag. */
-
-    int callbackBufferProcessorInited = FALSE;
-    int blockingBufferProcessorInited = FALSE;
+    bool isExternal = false;
 
     /* unless we move to using lower level ASIO calls, we can only have
         one device open at a time */
-    if( asioHostApi->openAsioDeviceIndex != paNoDevice )
-    {
+    if( asioHostApi->openAsioDeviceIndex != paNoDevice ){
         PA_DEBUG(("OpenStream paDeviceUnavailable\n"));
         return paDeviceUnavailable;
     }
 
-    assert( theAsioStream == 0 );
-
     if( inputParameters && outputParameters )
     {
         /* full duplex ASIO stream must use the same device for input and output */
 
-        if( inputParameters->device != outputParameters->device )
-        {
+        if( inputParameters->device != outputParameters->device ){
             PA_DEBUG(("OpenStream paBadIODeviceCombination\n"));
             return paBadIODeviceCombination;
-        }
+    }
     }
 
     if( inputParameters )
@@ -1982,12 +1762,12 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     /* NOTE: we load the driver and use its current settings
         rather than the ones in our device info structure which may be stale */
 
-    result = LoadAsioDriver( asioHostApi, asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
+    result = LoadAsioDriver( asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
             driverInfo, asioHostApi->systemSpecific );
     if( result == paNoError )
         asioIsInitialized = 1;
     else{
-        PA_DEBUG(("OpenStream ERROR1 - LoadAsioDriver returned %d\n", result));
+        PA_DEBUG(("OpenStream ERROR1\n"));
         goto error;
     }
 
@@ -2013,9 +1793,76 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
         }
     }
 
-    result = ValidateAndSetSampleRate( sampleRate );
-    if( result != paNoError )
+
+    /* davidv: listing ASIO Clock sources, there is an ongoing investigation by
+       me about whether or not call ASIOSetSampleRate if an external Clock is
+       used. A few drivers expected different things here */
+    {
+        ASIOClockSource clocks[32];
+        long numSources=32;
+        asioError = ASIOGetClockSources(clocks, &numSources);
+        if( asioError != ASE_OK ){
+            PA_DEBUG(("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+        }else{
+            PA_DEBUG(("INFO ASIOGetClockSources listing %d clocks\n", numSources ));
+            for (int i=0;i<numSources;++i){
+                PA_DEBUG(("ASIOClockSource%d %s current:%d\n", i,clocks[i].name, clocks[i].isCurrentSource ));
+               
+                /*
+                  If you have problems with some drivers when externally clocked, 
+                  uncomment the next two lines
+                 */
+                //if (clocks[i].isCurrentSource)
+                //    isExternal = true;
+            }
+        }
+    }
+
+    // check that the device supports the requested sample rate 
+
+    asioError = ASIOCanSampleRate( sampleRate );
+    PA_DEBUG(("ASIOCanSampleRate(%f):%d\n",sampleRate, asioError ));
+
+    if( asioError != ASE_OK )
+    {
+        result = paInvalidSampleRate;
+        PA_DEBUG(("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+        goto error;
+    }
+
+
+    // retrieve the current sample rate, we only change to the requested
+    // sample rate if the device is not already in that rate.
+
+    ASIOSampleRate oldRate;
+    asioError = ASIOGetSampleRate(&oldRate);
+    if( asioError != ASE_OK )
+    {
+        result = paInvalidSampleRate;
+        PA_DEBUG(("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
         goto error;
+    }
+    PA_DEBUG(("ASIOGetSampleRate:%f\n",oldRate));
+
+    if (oldRate != sampleRate){
+
+        PA_DEBUG(("before ASIOSetSampleRate(%f)\n",sampleRate));
+
+        asioError = ASIOSetSampleRate( isExternal?0:sampleRate );
+        /* Set sample rate */
+        if( asioError != ASE_OK )
+        {
+            result = paInvalidSampleRate;
+            PA_DEBUG(("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+            goto error;
+        }
+        PA_DEBUG(("after ASIOSetSampleRate(%f)\n",sampleRate));
+    }
+    else
+    {
+        PA_DEBUG(("No Need to change SR\n"));
+    }
+
 
     /*
         IMPLEMENT ME:
@@ -2037,8 +1884,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
         PA_DEBUG(("OpenStream ERROR5\n"));
         goto error;
     }
-    stream->blockingState = NULL; /* Blocking i/o not initialized, yet. */
-
 
     stream->completedBuffersPlayedEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
     if( stream->completedBuffersPlayedEvent == NULL )
@@ -2055,19 +1900,15 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     stream->asioChannelInfos = 0; /* for deallocation in error */
     stream->bufferPtrs = 0; /* for deallocation in error */
 
-    /* Using blocking i/o interface... */
-    if( usingBlockingIo )
+    if( streamCallback )
     {
-        /* Blocking i/o is implemented by running callback mode, using a special blocking i/o callback. */
-        streamCallback = BlockingIoPaCallback; /* Setup PA to use the ASIO blocking i/o callback. */
-        userData       = &theAsioStream;       /* The callback user data will be the PA ASIO stream. */
         PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
-                                               &asioHostApi->blockingStreamInterface, streamCallback, userData );
+                                               &asioHostApi->callbackStreamInterface, streamCallback, userData );
     }
-    else /* Using callback interface... */
+    else
     {
         PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
-                                               &asioHostApi->callbackStreamInterface, streamCallback, userData );
+                                               &asioHostApi->blockingStreamInterface, streamCallback, userData );
     }
 
 
@@ -2118,24 +1959,13 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     }
 
 
-    /* Using blocking i/o interface... */
-    if( usingBlockingIo )
-    {
-/** @todo REVIEW selection of host buffer size for blocking i/o */
-        /* Use default host latency for blocking i/o. */
-        framesPerHostBuffer = SelectHostBufferSize( 0, driverInfo );
-
-    }
-    else /* Using callback interface... */
-    {
-        framesPerHostBuffer = SelectHostBufferSize(
-                (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames )
-                        ? suggestedInputLatencyFrames : suggestedOutputLatencyFrames),
-                driverInfo );
-    }
+    framesPerHostBuffer = SelectHostBufferSize(
+            (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames )
+                    ? suggestedInputLatencyFrames : suggestedOutputLatencyFrames),
+            driverInfo );
 
 
-    PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n",  framesPerHostBuffer));
+	PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n",  framesPerHostBuffer));
 
     asioError = ASIOCreateBuffers( stream->asioBufferInfos,
             inputChannelCount+outputChannelCount,
@@ -2273,302 +2103,43 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
         stream->outputBufferConverter = 0;
     }
 
+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+                    sampleRate, streamFlags, framesPerBuffer,
+                    framesPerHostBuffer, paUtilFixedHostBufferSize,
+                    streamCallback, userData );
+    if( result != paNoError ){
+        PA_DEBUG(("OpenStream ERROR13\n"));
+        goto error;
+    }
 
-    ASIOGetLatencies( &stream->inputLatency, &stream->outputLatency );
-
-
-    /* Using blocking i/o interface... */
-    if( usingBlockingIo )
-    {
-        /* Allocate the blocking i/o input ring buffer memory. */
-        stream->blockingState = (PaAsioStreamBlockingState*)PaUtil_AllocateMemory( sizeof(PaAsioStreamBlockingState) );
-        if( !stream->blockingState )
-        {
-            result = paInsufficientMemory;
-            PA_DEBUG(("ERROR! Blocking i/o interface struct allocation failed in OpenStream()\n"));
-            goto error;
-        }
-
-        /* Initialize blocking i/o interface struct. */
-        stream->blockingState->readFramesReadyEvent   = NULL; /* Uninitialized, yet. */
-        stream->blockingState->writeBuffersReadyEvent = NULL; /* Uninitialized, yet. */
-        stream->blockingState->readRingBufferData     = NULL; /* Uninitialized, yet. */
-        stream->blockingState->writeRingBufferData    = NULL; /* Uninitialized, yet. */
-        stream->blockingState->readStreamBuffer       = NULL; /* Uninitialized, yet. */
-        stream->blockingState->writeStreamBuffer      = NULL; /* Uninitialized, yet. */
-        stream->blockingState->stopFlag               = TRUE; /* Not started, yet. */
-
-
-        /* If the user buffer is unspecified */
-        if( framesPerBuffer == paFramesPerBufferUnspecified )
-        {
-            /* Make the user buffer the same size as the host buffer. */
-            framesPerBuffer = framesPerHostBuffer;
-        }
-
-
-        /* Initialize callback buffer processor. */
-        result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor               ,
-                                                    inputChannelCount                     ,
-                                                    inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */
-                                                    hostInputSampleFormat                 , /* Host format. */
-                                                    outputChannelCount                    ,
-                                                    outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */
-                                                    hostOutputSampleFormat                , /* Host format. */
-                                                    sampleRate                            ,
-                                                    streamFlags                           ,
-                                                    framesPerBuffer                       , /* Frames per ring buffer block. */
-                                                    framesPerHostBuffer                   , /* Frames per asio buffer. */
-                                                    paUtilFixedHostBufferSize             ,
-                                                    streamCallback                        ,
-                                                    userData                               );
-        if( result != paNoError ){
-            PA_DEBUG(("OpenStream ERROR13\n"));
-            goto error;
-        }
-        callbackBufferProcessorInited = TRUE;
-
-        /* Initialize the blocking i/o buffer processor. */
-        result = PaUtil_InitializeBufferProcessor(&stream->blockingState->bufferProcessor,
-                                                   inputChannelCount                     ,
-                                                   inputSampleFormat                     , /* User format. */
-                                                   inputSampleFormat & ~paNonInterleaved , /* Ring buffer. */
-                                                   outputChannelCount                    ,
-                                                   outputSampleFormat                    , /* User format. */
-                                                   outputSampleFormat & ~paNonInterleaved, /* Ring buffer. */
-                                                   sampleRate                            ,
-                                                   paClipOff | paDitherOff               , /* Don't use dither nor clipping. */
-                                                   framesPerBuffer                       , /* Frames per user buffer. */
-                                                   framesPerBuffer                       , /* Frames per ring buffer block. */
-                                                   paUtilBoundedHostBufferSize           ,
-                                                   NULL, NULL                            );/* No callback! */
-        if( result != paNoError ){
-            PA_DEBUG(("ERROR! Blocking i/o buffer processor initialization failed in OpenStream()\n"));
-            goto error;
-        }
-        blockingBufferProcessorInited = TRUE;
-
-        /* If input is requested. */
-        if( inputChannelCount )
-        {
-            /* Create the callback sync-event. */
-            stream->blockingState->readFramesReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
-            if( stream->blockingState->readFramesReadyEvent == NULL )
-            {
-                result = paUnanticipatedHostError;
-                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-                PA_DEBUG(("ERROR! Blocking i/o \"read frames ready\" event creation failed in OpenStream()\n"));
-                goto error;
-            }
-            blockingReadFramesReadyEventInitialized = 1;
-
-
-            /* Create pointer buffer to access non-interleaved data in ReadStream() */
-            stream->blockingState->readStreamBuffer = (void**)PaUtil_AllocateMemory( sizeof(void*) * inputChannelCount );
-            if( !stream->blockingState->readStreamBuffer )
-            {
-                result = paInsufficientMemory;
-                PA_DEBUG(("ERROR! Blocking i/o read stream buffer allocation failed in OpenStream()\n"));
-                goto error;
-            }
-
-            /* The ring buffer should store as many data blocks as needed
-               to achieve the requested latency. Whereas it must be large
-               enough to store at least two complete data blocks.
-
-               1) Determine the amount of latency to be added to the
-                  prefered ASIO latency.
-               2) Make sure we have at lest one additional latency frame.
-               3) Divide the number of frames by the desired block size to
-                  get the number (rounded up to pure integer) of blocks to
-                  be stored in the buffer.
-               4) Add one additional block for block processing and convert
-                  to samples frames.
-               5) Get the next larger (or equal) power-of-two buffer size.
-             */
-            lBlockingBufferSize = suggestedInputLatencyFrames - stream->inputLatency;
-            lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1;
-            lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer;
-            lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer;
-
-            /* Get the next larger or equal power-of-two buffersize. */
-            lBlockingBufferSizePow2 = 1;
-            while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) );
-            lBlockingBufferSize = lBlockingBufferSizePow2;
-
-            /* Compute total intput latency in seconds */
-            stream->streamRepresentation.streamInfo.inputLatency =
-                (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor               )
-                        + PaUtil_GetBufferProcessorInputLatency(&stream->blockingState->bufferProcessor)
-                        + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer
-                        + stream->inputLatency )
-                / sampleRate;
-
-            /* The code below prints the ASIO latency which doesn't include
-               the buffer processor latency nor the blocking i/o latency. It
-               reports the added latency separately.
-            */
-            PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms),\n         added buffProc:%ld (%ld ms),\n         added blocking:%ld (%ld ms)\n",
-                stream->inputLatency,
-                (long)( stream->inputLatency * (1000.0 / sampleRate) ),
-                PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor),
-                (long)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) * (1000.0 / sampleRate) ),
-                PaUtil_GetBufferProcessorInputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer,
-                (long)( (PaUtil_GetBufferProcessorInputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) )
-                ));
-
-            /* Determine the size of ring buffer in bytes. */
-            lBytesPerFrame = inputChannelCount * Pa_GetSampleSize(inputSampleFormat );
-
-            /* Allocate the blocking i/o input ring buffer memory. */
-            stream->blockingState->readRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame );
-            if( !stream->blockingState->readRingBufferData )
-            {
-                result = paInsufficientMemory;
-                PA_DEBUG(("ERROR! Blocking i/o input ring buffer allocation failed in OpenStream()\n"));
-                goto error;
-            }
-
-            /* Initialize the input ring buffer struct. */
-            PaUtil_InitializeRingBuffer( &stream->blockingState->readRingBuffer    ,
-                                          lBytesPerFrame                           ,
-                                          lBlockingBufferSize                      ,
-                                          stream->blockingState->readRingBufferData );
-        }
-
-        /* If output is requested. */
-        if( outputChannelCount )
-        {
-            stream->blockingState->writeBuffersReadyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
-            if( stream->blockingState->writeBuffersReadyEvent == NULL )
-            {
-                result = paUnanticipatedHostError;
-                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-                PA_DEBUG(("ERROR! Blocking i/o \"write buffers ready\" event creation failed in OpenStream()\n"));
-                goto error;
-            }
-            blockingWriteBuffersReadyEventInitialized = 1;
-
-            /* Create pointer buffer to access non-interleaved data in WriteStream() */
-            stream->blockingState->writeStreamBuffer = (const void**)PaUtil_AllocateMemory( sizeof(const void*) * outputChannelCount );
-            if( !stream->blockingState->writeStreamBuffer )
-            {
-                result = paInsufficientMemory;
-                PA_DEBUG(("ERROR! Blocking i/o write stream buffer allocation failed in OpenStream()\n"));
-                goto error;
-            }
-
-            /* The ring buffer should store as many data blocks as needed
-               to achieve the requested latency. Whereas it must be large
-               enough to store at least two complete data blocks.
-
-               1) Determine the amount of latency to be added to the
-                  prefered ASIO latency.
-               2) Make sure we have at lest one additional latency frame.
-               3) Divide the number of frames by the desired block size to
-                  get the number (rounded up to pure integer) of blocks to
-                  be stored in the buffer.
-               4) Add one additional block for block processing and convert
-                  to samples frames.
-               5) Get the next larger (or equal) power-of-two buffer size.
-             */
-            lBlockingBufferSize = suggestedOutputLatencyFrames - stream->outputLatency;
-            lBlockingBufferSize = (lBlockingBufferSize > 0) ? lBlockingBufferSize : 1;
-            lBlockingBufferSize = (lBlockingBufferSize + framesPerBuffer - 1) / framesPerBuffer;
-            lBlockingBufferSize = (lBlockingBufferSize + 1) * framesPerBuffer;
-
-            /* The buffer size (without the additional block) corresponds
-               to the initial number of silent samples in the output ring
-               buffer. */
-            stream->blockingState->writeRingBufferInitialFrames = lBlockingBufferSize - framesPerBuffer;
-
-            /* Get the next larger or equal power-of-two buffersize. */
-            lBlockingBufferSizePow2 = 1;
-            while( lBlockingBufferSize > (lBlockingBufferSizePow2<<=1) );
-            lBlockingBufferSize = lBlockingBufferSizePow2;
-
-            /* Compute total output latency in seconds */
-            stream->streamRepresentation.streamInfo.outputLatency =
-                (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor               )
-                        + PaUtil_GetBufferProcessorOutputLatency(&stream->blockingState->bufferProcessor)
-                        + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer
-                        + stream->outputLatency )
-                / sampleRate;
-
-            /* The code below prints the ASIO latency which doesn't include
-               the buffer processor latency nor the blocking i/o latency. It
-               reports the added latency separately.
-            */
-            PA_DEBUG(("PaAsio : ASIO OutputLatency = %ld (%ld ms),\n         added buffProc:%ld (%ld ms),\n         added blocking:%ld (%ld ms)\n",
-                stream->outputLatency,
-                (long)( stream->inputLatency * (1000.0 / sampleRate) ),
-                PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor),
-                (long)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) * (1000.0 / sampleRate) ),
-                PaUtil_GetBufferProcessorOutputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer,
-                (long)( (PaUtil_GetBufferProcessorOutputLatency(&stream->blockingState->bufferProcessor) + (lBlockingBufferSize / framesPerBuffer - 1) * framesPerBuffer) * (1000.0 / sampleRate) )
-                ));
-
-            /* Determine the size of ring buffer in bytes. */
-            lBytesPerFrame = outputChannelCount * Pa_GetSampleSize(outputSampleFormat);
-
-            /* Allocate the blocking i/o output ring buffer memory. */
-            stream->blockingState->writeRingBufferData = (void*)PaUtil_AllocateMemory( lBlockingBufferSize * lBytesPerFrame );
-            if( !stream->blockingState->writeRingBufferData )
-            {
-                result = paInsufficientMemory;
-                PA_DEBUG(("ERROR! Blocking i/o output ring buffer allocation failed in OpenStream()\n"));
-                goto error;
-            }
-
-            /* Initialize the output ring buffer struct. */
-            PaUtil_InitializeRingBuffer( &stream->blockingState->writeRingBuffer    ,
-                                          lBytesPerFrame                            ,
-                                          lBlockingBufferSize                       ,
-                                          stream->blockingState->writeRingBufferData );
-        }
-
-        stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
 
+    ASIOGetLatencies( &stream->inputLatency, &stream->outputLatency );
 
-    }
-    else /* Using callback interface... */
-    {
-        result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
-                        inputChannelCount, inputSampleFormat, (hostInputSampleFormat | paNonInterleaved),
-                        outputChannelCount, outputSampleFormat, (hostOutputSampleFormat | paNonInterleaved),
-                        sampleRate, streamFlags, framesPerBuffer,
-                        framesPerHostBuffer, paUtilFixedHostBufferSize,
-                        streamCallback, userData );
-        if( result != paNoError ){
-            PA_DEBUG(("OpenStream ERROR13\n"));
-            goto error;
-        }
-        callbackBufferProcessorInited = TRUE;
-
-        stream->streamRepresentation.streamInfo.inputLatency =
-                (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)
-                    + stream->inputLatency) / sampleRate;   // seconds
-        stream->streamRepresentation.streamInfo.outputLatency =
-                (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)
-                    + stream->outputLatency) / sampleRate; // seconds
-        stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
-
-        // the code below prints the ASIO latency which doesn't include the
-        // buffer processor latency. it reports the added latency separately
-        PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
-                stream->inputLatency,
-                (long)((stream->inputLatency*1000)/ sampleRate),  
-                PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor),
-                (long)((PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)*1000)/ sampleRate)
-                ));
-
-        PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
-                stream->outputLatency,
-                (long)((stream->outputLatency*1000)/ sampleRate), 
-                PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor),
-                (long)((PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)*1000)/ sampleRate)
-                ));
-    }
+    stream->streamRepresentation.streamInfo.inputLatency =
+            (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)
+                + stream->inputLatency) / sampleRate;   // seconds
+    stream->streamRepresentation.streamInfo.outputLatency =
+            (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)
+                + stream->outputLatency) / sampleRate; // seconds
+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+    // the code below prints the ASIO latency which doesn't include the
+    // buffer processor latency. it reports the added latency separately
+    PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
+            stream->inputLatency,
+            (long)((stream->inputLatency*1000)/ sampleRate),  
+            PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor),
+            (long)((PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)*1000)/ sampleRate)
+            ));
+
+    PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
+            stream->outputLatency,
+            (long)((stream->outputLatency*1000)/ sampleRate), 
+            PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor),
+            (long)((PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)*1000)/ sampleRate)
+            ));
 
     stream->asioHostApi = asioHostApi;
     stream->framesPerHostCallback = framesPerHostBuffer;
@@ -2576,12 +2147,10 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     stream->inputChannelCount = inputChannelCount;
     stream->outputChannelCount = outputChannelCount;
     stream->postOutput = driverInfo->postOutput;
-    stream->isStopped = 1;
     stream->isActive = 0;
-    
+
     asioHostApi->openAsioDeviceIndex = asioDeviceIndex;
 
-    theAsioStream = stream;
     *s = (PaStream*)stream;
 
     return result;
@@ -2590,31 +2159,6 @@ error:
     PA_DEBUG(("goto errored\n"));
     if( stream )
     {
-        if( stream->blockingState )
-        {
-            if( blockingBufferProcessorInited )
-                PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor );
-
-            if( stream->blockingState->writeRingBufferData )
-                PaUtil_FreeMemory( stream->blockingState->writeRingBufferData );
-            if( stream->blockingState->writeStreamBuffer )
-                PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer );
-            if( blockingWriteBuffersReadyEventInitialized )
-                CloseHandle( stream->blockingState->writeBuffersReadyEvent );
-
-            if( stream->blockingState->readRingBufferData )
-                PaUtil_FreeMemory( stream->blockingState->readRingBufferData );
-            if( stream->blockingState->readStreamBuffer )
-                PaUtil_FreeMemory( stream->blockingState->readStreamBuffer );
-            if( blockingReadFramesReadyEventInitialized )
-                CloseHandle( stream->blockingState->readFramesReadyEvent );
-
-            PaUtil_FreeMemory( stream->blockingState );
-        }
-
-        if( callbackBufferProcessorInited )
-            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
-
         if( completedBuffersPlayedEventInited )
             CloseHandle( stream->completedBuffersPlayedEvent );
 
@@ -2634,9 +2178,8 @@ error:
         ASIODisposeBuffers();
 
     if( asioIsInitialized )
-	{
-		UnloadAsioDriver();
-	}
+        ASIOExit();
+
     return result;
 }
 
@@ -2662,34 +2205,13 @@ static PaError CloseStream( PaStream* s )
 
     CloseHandle( stream->completedBuffersPlayedEvent );
 
-    /* Using blocking i/o interface... */
-    if( stream->blockingState )
-    {
-        PaUtil_TerminateBufferProcessor( &stream->blockingState->bufferProcessor );
-
-        if( stream->inputChannelCount ) {
-            PaUtil_FreeMemory( stream->blockingState->readRingBufferData );
-            PaUtil_FreeMemory( stream->blockingState->readStreamBuffer  );
-            CloseHandle( stream->blockingState->readFramesReadyEvent );
-        }
-        if( stream->outputChannelCount ) {
-            PaUtil_FreeMemory( stream->blockingState->writeRingBufferData );
-            PaUtil_FreeMemory( stream->blockingState->writeStreamBuffer );
-            CloseHandle( stream->blockingState->writeBuffersReadyEvent );
-        }
-
-        PaUtil_FreeMemory( stream->blockingState );
-    }
-
     PaUtil_FreeMemory( stream->asioBufferInfos );
     PaUtil_FreeMemory( stream->asioChannelInfos );
     PaUtil_FreeMemory( stream->bufferPtrs );
     PaUtil_FreeMemory( stream );
 
     ASIODisposeBuffers();
-    UnloadAsioDriver();
-
-    theAsioStream = 0;
+    ASIOExit();
 
     return result;
 }
@@ -2723,10 +2245,10 @@ static void bufferSwitch(long index, ASIOBool directProcess)
 
 // conversion from 64 bit ASIOSample/ASIOTimeStamp to double float
 #if NATIVE_INT64
-    #define ASIO64toDouble(a)  (a)
+	#define ASIO64toDouble(a)  (a)
 #else
-    const double twoRaisedTo32 = 4294967296.;
-    #define ASIO64toDouble(a)  ((a).lo + (a).hi * twoRaisedTo32)
+	const double twoRaisedTo32 = 4294967296.;
+	#define ASIO64toDouble(a)  ((a).lo + (a).hi * twoRaisedTo32)
 #endif
 
 static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool directProcess )
@@ -2908,9 +2430,7 @@ previousIndex = index;
                 paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - theAsioStream->streamRepresentation.streamInfo.inputLatency;
                 paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + theAsioStream->streamRepresentation.streamInfo.outputLatency;
                 */
-
-/* Disabled! Stopping and re-starting the stream causes an input overflow / output undeflow. S.Fischer */
-#if 0
+#if 1
 // detect underflows by checking inter-callback time > 2 buffer period
 static double previousTime = -1;
 if( previousTime > 0 ){
@@ -3114,7 +2634,6 @@ static PaError StartStream( PaStream *s )
 {
     PaError result = paNoError;
     PaAsioStream *stream = (PaAsioStream*)s;
-    PaAsioStreamBlockingState *blockingState = stream->blockingState;
     ASIOError asioError;
 
     if( stream->outputChannelCount > 0 )
@@ -3139,72 +2658,18 @@ static PaError StartStream( PaStream *s )
         PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
     }
 
-
-    /* Using blocking i/o interface... */
-    if( blockingState )
-    {
-        /* Reset blocking i/o buffer processor. */
-        PaUtil_ResetBufferProcessor( &blockingState->bufferProcessor );
-
-        /* If we're about to process some input data. */
-        if( stream->inputChannelCount )
-        {
-            /* Reset callback-ReadStream sync event. */
-            if( ResetEvent( blockingState->readFramesReadyEvent ) == 0 )
-            {
-                result = paUnanticipatedHostError;
-                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-            }
-
-            /* Flush blocking i/o ring buffer. */
-            PaUtil_FlushRingBuffer( &blockingState->readRingBuffer );
-            (*blockingState->bufferProcessor.inputZeroer)( blockingState->readRingBuffer.buffer, 1, blockingState->bufferProcessor.inputChannelCount * blockingState->readRingBuffer.bufferSize );
-        }
-
-        /* If we're about to process some output data. */
-        if( stream->outputChannelCount )
-        {
-            /* Reset callback-WriteStream sync event. */
-            if( ResetEvent( blockingState->writeBuffersReadyEvent ) == 0 )
-            {
-                result = paUnanticipatedHostError;
-                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-            }
-
-            /* Flush blocking i/o ring buffer. */
-            PaUtil_FlushRingBuffer( &blockingState->writeRingBuffer );
-            (*blockingState->bufferProcessor.outputZeroer)( blockingState->writeRingBuffer.buffer, 1, blockingState->bufferProcessor.outputChannelCount * blockingState->writeRingBuffer.bufferSize );
-
-            /* Initialize the output ring buffer to "silence". */
-            PaUtil_AdvanceRingBufferWriteIndex( &blockingState->writeRingBuffer, blockingState->writeRingBufferInitialFrames );
-        }
-
-        /* Clear requested frames / buffers count. */
-        blockingState->writeBuffersRequested     = 0;
-        blockingState->readFramesRequested       = 0;
-        blockingState->writeBuffersRequestedFlag = FALSE;
-        blockingState->readFramesRequestedFlag   = FALSE;
-        blockingState->outputUnderflowFlag       = FALSE;
-        blockingState->inputOverflowFlag         = FALSE;
-        blockingState->stopFlag                  = FALSE;
-    }
-
-
     if( result == paNoError )
     {
-        assert( theAsioStream == stream ); /* theAsioStream should be set correctly in OpenStream */
-
-        /* initialize these variables before the callback has a chance to be invoked */
-        stream->isStopped = 0;
-        stream->isActive = 1;
-        stream->streamFinishedCallbackCalled = false;
-
+        theAsioStream = stream;
         asioError = ASIOStart();
-        if( asioError != ASE_OK )
+        if( asioError == ASE_OK )
         {
-            stream->isStopped = 1;
-            stream->isActive = 0;
-
+            stream->isActive = 1;
+            stream->streamFinishedCallbackCalled = false;
+        }
+        else
+        {
+            theAsioStream = 0;
             result = paUnanticipatedHostError;
             PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
         }
@@ -3213,59 +2678,15 @@ static PaError StartStream( PaStream *s )
     return result;
 }
 
-static void EnsureCallbackHasCompleted( PaAsioStream *stream )
-{
-    // make sure that the callback is not still in-flight after ASIOStop()
-    // returns. This has been observed to happen on the Hoontech DSP24 for
-    // example.
-    int count = 2000;  // only wait for 2 seconds, rather than hanging.
-    while( stream->reenterCount != -1 && count > 0 )
-    {
-        Sleep(1);
-        --count;
-    }
-}
 
 static PaError StopStream( PaStream *s )
 {
     PaError result = paNoError;
     PaAsioStream *stream = (PaAsioStream*)s;
-    PaAsioStreamBlockingState *blockingState = stream->blockingState;
     ASIOError asioError;
 
     if( stream->isActive )
     {
-        /* If blocking i/o output is in use */
-        if( blockingState && stream->outputChannelCount )
-        {
-            /* Request the whole output buffer to be available. */
-            blockingState->writeBuffersRequested = blockingState->writeRingBuffer.bufferSize;
-            /* Signalize that additional buffers are need. */
-            blockingState->writeBuffersRequestedFlag = TRUE;
-            /* Set flag to indicate the playback is to be stopped. */
-            blockingState->stopFlag = TRUE;
-
-            /* Wait until requested number of buffers has been freed. Time
-               out after twice the blocking i/o ouput buffer could have
-               been consumed. */
-            DWORD timeout = (DWORD)( 2 * blockingState->writeRingBuffer.bufferSize * 1000
-                                       / stream->streamRepresentation.streamInfo.sampleRate );
-            DWORD waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout );
-
-            /* If something seriously went wrong... */
-            if( waitResult == WAIT_FAILED )
-            {
-                PA_DEBUG(("WaitForSingleObject() failed in StopStream()\n"));
-                result = paUnanticipatedHostError;
-                PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-            }
-            else if( waitResult == WAIT_TIMEOUT )
-            {
-                PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n"));
-                result = paTimedOut;
-            }
-        }
-
         stream->stopProcessing = true;
 
         /* wait for the stream to finish playing out enqueued buffers.
@@ -3275,26 +2696,22 @@ static PaError StopStream( PaStream *s )
             length is longer than the asio buffer size then that should
             be taken into account.
         */
-        if( WaitForSingleObject( stream->completedBuffersPlayedEvent,
+        if( WaitForSingleObject( theAsioStream->completedBuffersPlayedEvent,
                 (DWORD)(stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.) )
-                    == WAIT_TIMEOUT )
+                    == WAIT_TIMEOUT	 )
         {
             PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n" ));
         }
     }
 
     asioError = ASIOStop();
-    if( asioError == ASE_OK )
-    {
-        EnsureCallbackHasCompleted( stream );
-    }
-    else
+    if( asioError != ASE_OK )
     {
         result = paUnanticipatedHostError;
         PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
     }
 
-    stream->isStopped = 1;
+    theAsioStream = 0;
     stream->isActive = 0;
 
     if( !stream->streamFinishedCallbackCalled )
@@ -3306,6 +2723,7 @@ static PaError StopStream( PaStream *s )
     return result;
 }
 
+
 static PaError AbortStream( PaStream *s )
 {
     PaError result = paNoError;
@@ -3315,17 +2733,31 @@ static PaError AbortStream( PaStream *s )
     stream->zeroOutput = true;
 
     asioError = ASIOStop();
-    if( asioError == ASE_OK )
+    if( asioError != ASE_OK )
     {
-        EnsureCallbackHasCompleted( stream );
+        result = paUnanticipatedHostError;
+        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
     }
     else
     {
-        result = paUnanticipatedHostError;
-        PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+        // make sure that the callback is not still in-flight when ASIOStop()
+        // returns. This has been observed to happen on the Hoontech DSP24 for
+        // example.
+        int count = 2000;  // only wait for 2 seconds, rather than hanging.
+        while( theAsioStream->reenterCount != -1 && count > 0 )
+        {
+            Sleep(1);
+            --count;
+        }
     }
 
-    stream->isStopped = 1;
+    /* it is questionable whether we should zero theAsioStream if ASIOStop()
+        returns an error, because the callback could still be active. We assume
+        not - this is based on the fact that ASIOStop is unlikely to fail
+        if the callback is running - it's more likely to fail because the
+        callback is not running. */
+        
+    theAsioStream = 0;
     stream->isActive = 0;
 
     if( !stream->streamFinishedCallbackCalled )
@@ -3340,9 +2772,9 @@ static PaError AbortStream( PaStream *s )
 
 static PaError IsStreamStopped( PaStream *s )
 {
-    PaAsioStream *stream = (PaAsioStream*)s;
-    
-    return stream->isStopped;
+    //PaAsioStream *stream = (PaAsioStream*)s;
+    (void) s; /* unused parameter */
+    return theAsioStream == 0;
 }
 
 
@@ -3375,348 +2807,33 @@ static double GetStreamCpuLoad( PaStream* s )
     for blocking streams.
 */
 
-static PaError ReadStream( PaStream      *s     ,
-                           void          *buffer,
-                           unsigned long  frames )
+static PaError ReadStream( PaStream* s,
+                           void *buffer,
+                           unsigned long frames )
 {
-    PaError result = paNoError; /* Initial return value. */
-    PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */
-
-    /* Pointer to the blocking i/o data struct. */
-    PaAsioStreamBlockingState *blockingState = stream->blockingState;
-
-    /* Get blocking i/o buffer processor and ring buffer pointers. */
-    PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
-    PaUtilRingBuffer      *pRb = &blockingState->readRingBuffer;
-
-    /* Ring buffer segment(s) used for writing. */
-    void *pRingBufferData1st = NULL; /* First segment. (Mandatory) */
-    void *pRingBufferData2nd = NULL; /* Second segment. (Optional) */
-
-    /* Number of frames per ring buffer segment. */
-    long lRingBufferSize1st = 0; /* First segment. (Mandatory) */
-    long lRingBufferSize2nd = 0; /* Second segment. (Optional) */
-
-    /* Get number of frames to be processed per data block. */
-    unsigned long lFramesPerBlock = stream->bufferProcessor.framesPerUserBuffer;
-    /* Actual number of frames that has been copied into the ring buffer. */
-    unsigned long lFramesCopied = 0;
-    /* The number of remaining unprocessed dtat frames. */
-    unsigned long lFramesRemaining = frames;
-
-    /* Copy the input argument to avoid pointer increment! */
-    const void *userBuffer;
-    unsigned int i; /* Just a counter. */
-
-    /* About the time, needed to process 8 data blocks. */
-    DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate );
-    DWORD waitResult = 0;
-
-
-    /* Check if the stream is still available ready to gather new data. */
-    if( blockingState->stopFlag || !stream->isActive )
-    {
-        PA_DEBUG(("Warning! Stream no longer available for reading in ReadStream()\n"));
-        result = paStreamIsStopped;
-        return result;
-    }
-
-    /* If the stream is a input stream. */
-    if( stream->inputChannelCount )
-    {
-        /* Prepare buffer access. */
-        if( !pBp->userOutputIsInterleaved )
-        {
-            userBuffer = blockingState->readStreamBuffer;
-            for( i = 0; i<pBp->inputChannelCount; ++i )
-            {
-                ((void**)userBuffer)[i] = ((void**)buffer)[i];
-            }
-        } /* Use the unchanged buffer. */
-        else { userBuffer = buffer; }
-
-        do /* Internal block processing for too large user data buffers. */
-        {
-            /* Get the size of the current data block to be processed. */
-            lFramesPerBlock =(lFramesPerBlock < lFramesRemaining)
-                            ? lFramesPerBlock : lFramesRemaining;
-            /* Use predefined block size for as long there are enough
-               buffers available, thereafter reduce the processing block
-               size to match the number of remaining buffers. So the final
-               data block is processed although it may be incomplete. */
-
-            /* If the available amount of data frames is insufficient. */
-            if( PaUtil_GetRingBufferReadAvailable(pRb) < (long) lFramesPerBlock )
-            {
-                /* Make sure, the event isn't already set! */
-                /* ResetEvent( blockingState->readFramesReadyEvent ); */
-
-                /* Set the number of requested buffers. */
-                blockingState->readFramesRequested = lFramesPerBlock;
-
-                /* Signalize that additional buffers are need. */
-                blockingState->readFramesRequestedFlag = TRUE;
-
-                /* Wait until requested number of buffers has been freed. */
-                waitResult = WaitForSingleObject( blockingState->readFramesReadyEvent, timeout );
-
-                /* If something seriously went wrong... */
-                if( waitResult == WAIT_FAILED )
-                {
-                    PA_DEBUG(("WaitForSingleObject() failed in ReadStream()\n"));
-                    result = paUnanticipatedHostError;
-                    PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-                    return result;
-                }
-                else if( waitResult == WAIT_TIMEOUT )
-                {
-                    PA_DEBUG(("WaitForSingleObject() timed out in ReadStream()\n"));
-
-                    /* If block processing has stopped, abort! */
-                    if( blockingState->stopFlag ) { return result = paStreamIsStopped; }
-
-                    /* If a timeout is encountered, give up eventually. */
-                    return result = paTimedOut;
-                }
-            }
-            /* Now, the ring buffer contains the required amount of data
-               frames.
-               (Therefor we don't need to check the return argument of
-               PaUtil_GetRingBufferReadRegions(). ;-) )
-            */
-
-            /* Retrieve pointer(s) to the ring buffer's current write
-               position(s). If the first buffer segment is too small to
-               store the requested number of bytes, an additional second
-               segment is returned. Otherwise, i.e. if the first segment
-               is large enough, the second segment's pointer will be NULL.
-            */
-            PaUtil_GetRingBufferReadRegions(pRb                ,
-                                            lFramesPerBlock    ,
-                                            &pRingBufferData1st,
-                                            &lRingBufferSize1st,
-                                            &pRingBufferData2nd,
-                                            &lRingBufferSize2nd);
-
-            /* Set number of frames to be copied from the ring buffer. */
-            PaUtil_SetInputFrameCount( pBp, lRingBufferSize1st ); 
-            /* Setup ring buffer access. */
-            PaUtil_SetInterleavedInputChannels(pBp               ,  /* Buffer processor. */
-                                               0                 ,  /* The first channel's index. */
-                                               pRingBufferData1st,  /* First ring buffer segment. */
-                                               0                 ); /* Use all available channels. */
-
-            /* If a second ring buffer segment is required. */
-            if( lRingBufferSize2nd ) {
-                /* Set number of frames to be copied from the ring buffer. */
-                PaUtil_Set2ndInputFrameCount( pBp, lRingBufferSize2nd );
-                /* Setup ring buffer access. */
-                PaUtil_Set2ndInterleavedInputChannels(pBp               ,  /* Buffer processor. */
-                                                      0                 ,  /* The first channel's index. */
-                                                      pRingBufferData2nd,  /* Second ring buffer segment. */
-                                                      0                 ); /* Use all available channels. */
-            }
-
-            /* Let the buffer processor handle "copy and conversion" and
-               update the ring buffer indices manually. */
-            lFramesCopied = PaUtil_CopyInput( pBp, &buffer, lFramesPerBlock );
-            PaUtil_AdvanceRingBufferReadIndex( pRb, lFramesCopied );
-
-            /* Decrease number of unprocessed frames. */
-            lFramesRemaining -= lFramesCopied;
-
-        } /* Continue with the next data chunk. */
-        while( lFramesRemaining );
-
-
-        /* If there has been an input overflow within the callback */
-        if( blockingState->inputOverflowFlag )
-        {
-            blockingState->inputOverflowFlag = FALSE;
-
-            /* Return the corresponding error code. */
-            result = paInputOverflowed;
-        }
+    PaAsioStream *stream = (PaAsioStream*)s;
 
-    } /* If this is not an input stream. */
-    else {
-        result = paCanNotReadFromAnOutputOnlyStream;
-    }
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    (void) stream; /* unused parameters */
+    (void) buffer;
+    (void) frames;
 
-    return result;
+    return paNoError;
 }
 
-static PaError WriteStream( PaStream      *s     ,
-                            const void    *buffer,
-                            unsigned long  frames )
-{
-    PaError result = paNoError; /* Initial return value. */
-    PaAsioStream *stream = (PaAsioStream*)s; /* The PA ASIO stream. */
-
-    /* Pointer to the blocking i/o data struct. */
-    PaAsioStreamBlockingState *blockingState = stream->blockingState;
 
-    /* Get blocking i/o buffer processor and ring buffer pointers. */
-    PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
-    PaUtilRingBuffer      *pRb = &blockingState->writeRingBuffer;
-
-    /* Ring buffer segment(s) used for writing. */
-    void *pRingBufferData1st = NULL; /* First segment. (Mandatory) */
-    void *pRingBufferData2nd = NULL; /* Second segment. (Optional) */
-
-    /* Number of frames per ring buffer segment. */
-    long lRingBufferSize1st = 0; /* First segment. (Mandatory) */
-    long lRingBufferSize2nd = 0; /* Second segment. (Optional) */
-
-    /* Get number of frames to be processed per data block. */
-    unsigned long lFramesPerBlock = stream->bufferProcessor.framesPerUserBuffer;
-    /* Actual number of frames that has been copied into the ring buffer. */
-    unsigned long lFramesCopied = 0;
-    /* The number of remaining unprocessed dtat frames. */
-    unsigned long lFramesRemaining = frames;
-
-    /* About the time, needed to process 8 data blocks. */
-    DWORD timeout = (DWORD)( 8 * lFramesPerBlock * 1000 / stream->streamRepresentation.streamInfo.sampleRate );
-    DWORD waitResult = 0;
-
-    /* Copy the input argument to avoid pointer increment! */
-    const void *userBuffer;
-    unsigned int i; /* Just a counter. */
-
-
-    /* Check if the stream ist still available ready to recieve new data. */
-    if( blockingState->stopFlag || !stream->isActive )
-    {
-        PA_DEBUG(("Warning! Stream no longer available for writing in WriteStream()\n"));
-        result = paStreamIsStopped;
-        return result;
-    }
-
-    /* If the stream is a output stream. */
-    if( stream->outputChannelCount )
-    {
-        /* Prepare buffer access. */
-        if( !pBp->userOutputIsInterleaved )
-        {
-            userBuffer = blockingState->writeStreamBuffer;
-            for( i = 0; i<pBp->outputChannelCount; ++i )
-            {
-                ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
-            }
-        } /* Use the unchanged buffer. */
-        else { userBuffer = buffer; }
-
-
-        do /* Internal block processing for too large user data buffers. */
-        {
-            /* Get the size of the current data block to be processed. */
-            lFramesPerBlock =(lFramesPerBlock < lFramesRemaining)
-                            ? lFramesPerBlock : lFramesRemaining;
-            /* Use predefined block size for as long there are enough
-               frames available, thereafter reduce the processing block
-               size to match the number of remaining frames. So the final
-               data block is processed although it may be incomplete. */
-
-            /* If the available amount of buffers is insufficient. */
-            if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) lFramesPerBlock )
-            {
-                /* Make sure, the event isn't already set! */
-                /* ResetEvent( blockingState->writeBuffersReadyEvent ); */
-
-                /* Set the number of requested buffers. */
-                blockingState->writeBuffersRequested = lFramesPerBlock;
-
-                /* Signalize that additional buffers are need. */
-                blockingState->writeBuffersRequestedFlag = TRUE;
-
-                /* Wait until requested number of buffers has been freed. */
-                waitResult = WaitForSingleObject( blockingState->writeBuffersReadyEvent, timeout );
-
-                /* If something seriously went wrong... */
-                if( waitResult == WAIT_FAILED )
-                {
-                    PA_DEBUG(("WaitForSingleObject() failed in WriteStream()\n"));
-                    result = paUnanticipatedHostError;
-                    PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
-                    return result;
-                }
-                else if( waitResult == WAIT_TIMEOUT )
-                {
-                    PA_DEBUG(("WaitForSingleObject() timed out in WriteStream()\n"));
-
-                    /* If block processing has stopped, abort! */
-                    if( blockingState->stopFlag ) { return result = paStreamIsStopped; }
-                    
-                    /* If a timeout is encountered, give up eventually. */
-                    return result = paTimedOut;
-                }
-            }
-            /* Now, the ring buffer contains the required amount of free
-               space to store the provided number of data frames.
-               (Therefor we don't need to check the return argument of
-               PaUtil_GetRingBufferWriteRegions(). ;-) )
-            */
-
-            /* Retrieve pointer(s) to the ring buffer's current write
-               position(s). If the first buffer segment is too small to
-               store the requested number of bytes, an additional second
-               segment is returned. Otherwise, i.e. if the first segment
-               is large enough, the second segment's pointer will be NULL.
-            */
-            PaUtil_GetRingBufferWriteRegions(pRb                ,
-                                             lFramesPerBlock    ,
-                                             &pRingBufferData1st,
-                                             &lRingBufferSize1st,
-                                             &pRingBufferData2nd,
-                                             &lRingBufferSize2nd);
-
-            /* Set number of frames to be copied to the ring buffer. */
-            PaUtil_SetOutputFrameCount( pBp, lRingBufferSize1st ); 
-            /* Setup ring buffer access. */
-            PaUtil_SetInterleavedOutputChannels(pBp               ,  /* Buffer processor. */
-                                                0                 ,  /* The first channel's index. */
-                                                pRingBufferData1st,  /* First ring buffer segment. */
-                                                0                 ); /* Use all available channels. */
-
-            /* If a second ring buffer segment is required. */
-            if( lRingBufferSize2nd ) {
-                /* Set number of frames to be copied to the ring buffer. */
-                PaUtil_Set2ndOutputFrameCount( pBp, lRingBufferSize2nd );
-                /* Setup ring buffer access. */
-                PaUtil_Set2ndInterleavedOutputChannels(pBp               ,  /* Buffer processor. */
-                                                       0                 ,  /* The first channel's index. */
-                                                       pRingBufferData2nd,  /* Second ring buffer segment. */
-                                                       0                 ); /* Use all available channels. */
-            }
-
-            /* Let the buffer processor handle "copy and conversion" and
-               update the ring buffer indices manually. */
-            lFramesCopied = PaUtil_CopyOutput( pBp, &userBuffer, lFramesPerBlock );
-            PaUtil_AdvanceRingBufferWriteIndex( pRb, lFramesCopied );
-
-            /* Decrease number of unprocessed frames. */
-            lFramesRemaining -= lFramesCopied;
-
-        } /* Continue with the next data chunk. */
-        while( lFramesRemaining );
-
-
-        /* If there has been an output underflow within the callback */
-        if( blockingState->outputUnderflowFlag )
-        {
-            blockingState->outputUnderflowFlag = FALSE;
-
-            /* Return the corresponding error code. */
-            result = paOutputUnderflowed;
-        }
+static PaError WriteStream( PaStream* s,
+                            const void *buffer,
+                            unsigned long frames )
+{
+    PaAsioStream *stream = (PaAsioStream*)s;
 
-    } /* If this is not an output stream. */
-    else
-    {
-        result = paCanNotWriteToAnInputOnlyStream;
-    }
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    (void) stream; /* unused parameters */
+    (void) buffer;
+    (void) frames;
 
-    return result;
+    return paNoError;
 }
 
 
@@ -3724,8 +2841,10 @@ static signed long GetStreamReadAvailable( PaStream* s )
 {
     PaAsioStream *stream = (PaAsioStream*)s;
 
-    /* Call buffer utility routine to get the number of available frames. */
-    return PaUtil_GetRingBufferReadAvailable( &stream->blockingState->readRingBuffer );
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    (void) stream; /* unused parameter */
+
+    return 0;
 }
 
 
@@ -3733,130 +2852,20 @@ static signed long GetStreamWriteAvailable( PaStream* s )
 {
     PaAsioStream *stream = (PaAsioStream*)s;
 
-    /* Call buffer utility routine to get the number of empty buffers. */
-    return PaUtil_GetRingBufferWriteAvailable( &stream->blockingState->writeRingBuffer );
-}
-
-
-/* This routine will be called by the PortAudio engine when audio is needed.
-** It may called at interrupt level on some machines so don't do anything
-** that could mess up the system like calling malloc() or free().
-*/
-static int BlockingIoPaCallback(const void                     *inputBuffer    ,
-                                      void                     *outputBuffer   ,
-                                      unsigned long             framesPerBuffer,
-                                const PaStreamCallbackTimeInfo *timeInfo       ,
-                                      PaStreamCallbackFlags     statusFlags    ,
-                                      void                     *userData       )
-{
-    PaError result = paNoError; /* Initial return value. */
-    PaAsioStream *stream = *(PaAsioStream**)userData; /* The PA ASIO stream. */
-    PaAsioStreamBlockingState *blockingState = stream->blockingState; /* Persume blockingState is valid, otherwise the callback wouldn't be running. */
-
-    /* Get a pointer to the stream's blocking i/o buffer processor. */
-    PaUtilBufferProcessor *pBp = &blockingState->bufferProcessor;
-    PaUtilRingBuffer      *pRb = NULL;
-
-    /* If output data has been requested. */
-    if( stream->outputChannelCount )
-    {
-        /* If the callback input argument signalizes a output underflow,
-           make sure the WriteStream() function knows about it, too! */
-        if( statusFlags & paOutputUnderflowed ) {
-            blockingState->outputUnderflowFlag = TRUE;
-        }
-
-        /* Access the corresponding ring buffer. */
-        pRb = &blockingState->writeRingBuffer;
-
-        /* If the blocking i/o buffer contains enough output data, */
-        if( PaUtil_GetRingBufferReadAvailable(pRb) >= (long) framesPerBuffer )
-        {
-            /* Extract the requested data from the ring buffer. */
-            PaUtil_ReadRingBuffer( pRb, outputBuffer, framesPerBuffer );
-        }
-        else /* If no output data is available :-( */
-        {
-            /* Signalize a write-buffer underflow. */
-            blockingState->outputUnderflowFlag = TRUE;
-
-            /* Fill the output buffer with silence. */
-            (*pBp->outputZeroer)( outputBuffer, 1, pBp->outputChannelCount * framesPerBuffer );
+    /* IMPLEMENT ME, see portaudio.h for required behavior*/
+    (void) stream; /* unused parameter */
 
-            /* If playback is to be stopped */
-            if( blockingState->stopFlag && PaUtil_GetRingBufferReadAvailable(pRb) < (long) framesPerBuffer )
-            {
-                /* Extract all the remaining data from the ring buffer,
-                   whether it is a complete data block or not. */
-                PaUtil_ReadRingBuffer( pRb, outputBuffer, PaUtil_GetRingBufferReadAvailable(pRb) );
-            }
-        }
-
-        /* Set blocking i/o event? */
-        if( blockingState->writeBuffersRequestedFlag && PaUtil_GetRingBufferWriteAvailable(pRb) >= (long) blockingState->writeBuffersRequested )
-        {
-            /* Reset buffer request. */
-            blockingState->writeBuffersRequestedFlag = FALSE;
-            blockingState->writeBuffersRequested     = 0;
-            /* Signalize that requested buffers are ready. */
-            SetEvent( blockingState->writeBuffersReadyEvent );
-            /* What do we do if SetEvent() returns zero, i.e. the event
-               could not be set? How to return errors from within the
-               callback? - S.Fischer */
-        }
-    }
-
-    /* If input data has been supplied. */
-    if( stream->inputChannelCount )
-    {
-        /* If the callback input argument signalizes a input overflow,
-           make sure the ReadStream() function knows about it, too! */
-        if( statusFlags & paInputOverflowed ) {
-            blockingState->inputOverflowFlag = TRUE;
-        }
-
-        /* Access the corresponding ring buffer. */
-        pRb = &blockingState->readRingBuffer;
-
-        /* If the blocking i/o buffer contains not enough input buffers */
-        if( PaUtil_GetRingBufferWriteAvailable(pRb) < (long) framesPerBuffer )
-        {
-            /* Signalize a read-buffer overflow. */
-            blockingState->inputOverflowFlag = TRUE;
-
-            /* Remove some old data frames from the buffer. */
-            PaUtil_AdvanceRingBufferReadIndex( pRb, framesPerBuffer );
-        }
-
-        /* Insert the current input data into the ring buffer. */
-        PaUtil_WriteRingBuffer( pRb, inputBuffer, framesPerBuffer );
-
-        /* Set blocking i/o event? */
-        if( blockingState->readFramesRequestedFlag && PaUtil_GetRingBufferReadAvailable(pRb) >= (long) blockingState->readFramesRequested )
-        {
-            /* Reset buffer request. */
-            blockingState->readFramesRequestedFlag = FALSE;
-            blockingState->readFramesRequested     = 0;
-            /* Signalize that requested buffers are ready. */
-            SetEvent( blockingState->readFramesReadyEvent );
-            /* What do we do if SetEvent() returns zero, i.e. the event
-               could not be set? How to return errors from within the
-               callback? - S.Fischer */
-            /** @todo report an error with PA_DEBUG */
-        }
-    }
-
-    return paContinue;
+    return 0;
 }
 
 
 PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific )
 {
-    PaError result = paNoError;
+	PaError result = paNoError;
     PaUtilHostApiRepresentation *hostApi;
     PaDeviceIndex hostApiDevice;
     ASIODriverInfo asioDriverInfo;
-    ASIOError asioError;
+	ASIOError asioError;
     int asioIsInitialized = 0;
     PaAsioHostApiRepresentation *asioHostApi;
     PaAsioDeviceInfo *asioDeviceInfo;
@@ -3887,10 +2896,7 @@ PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific )
 
     asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
 
-    /* See notes about CoInitialize(0) in LoadAsioDriver(). */
-	CoInitialize(0);
-
-    if( !asioHostApi->asioDrivers->loadDriver( const_cast<char*>(asioDeviceInfo->commonDeviceInfo.name) ) )
+    if( !loadAsioDriver( const_cast<char*>(asioDeviceInfo->commonDeviceInfo.name) ) )
     {
         result = paUnanticipatedHostError;
         goto error;
@@ -3938,19 +2944,15 @@ PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErr
         goto error;
     }
 
-	CoUninitialize();
 PA_DEBUG(("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
 
-    return result;
+	return result;
 
 error:
     if( asioIsInitialized )
-	{
-		ASIOExit();
-	}
-	CoUninitialize();
+        ASIOExit();
 
-    return result;
+	return result;
 }
 
 
@@ -4019,53 +3021,3 @@ PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
 error:
     return result;
 }
-
-
-/* NOTE: the following functions are ASIO-stream specific, and are called directly
-    by client code. We need to check for many more error conditions here because
-    we don't have the benefit of pa_front.c's parameter checking.
-*/
-
-static PaError GetAsioStreamPointer( PaAsioStream **stream, PaStream *s )
-{
-    PaError result;
-    PaUtilHostApiRepresentation *hostApi;
-    PaAsioHostApiRepresentation *asioHostApi;
-    
-    result = PaUtil_ValidateStreamPointer( s );
-    if( result != paNoError )
-        return result;
-
-    result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
-    if( result != paNoError )
-        return result;
-
-    asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
-    
-    if( PA_STREAM_REP( s )->streamInterface == &asioHostApi->callbackStreamInterface
-            || PA_STREAM_REP( s )->streamInterface == &asioHostApi->blockingStreamInterface )
-    {
-        /* s is an ASIO  stream */
-        *stream = (PaAsioStream *)s;
-        return paNoError;
-    }
-    else
-    {
-        return paIncompatibleStreamHostApi;
-    }
-}
-
-
-PaError PaAsio_SetStreamSampleRate( PaStream* s, double sampleRate )
-{
-    PaAsioStream *stream;
-    PaError result = GetAsioStreamPointer( &stream, s );
-    if( result != paNoError )
-        return result;
-
-    if( stream != theAsioStream )
-        return paBadStreamPtr;
-
-    return ValidateAndSetSampleRate( sampleRate );
-}
-
diff --git a/portaudio/src/hostapi/coreaudio/notes.txt b/portaudio/src/hostapi/coreaudio/notes.txt
index 145afe154..ffe969625 100644
--- a/portaudio/src/hostapi/coreaudio/notes.txt
+++ b/portaudio/src/hostapi/coreaudio/notes.txt
@@ -73,24 +73,17 @@ the stream with it. See below for creating a channel map.
 
 Known issues:
 
-- Buffering: No buffering beyond that provided by core audio is provided
-except where absolutely needed for the implementation to work. This may cause
-issues with large framesPerBuffer settings and it also means that no additional
-latency will be provided even if a large latency setting is selected.
-
-- Latency: Latency settings are generally ignored. They may be used as a
-hint for buffer size in paHostFramesPerBufferUnspecified, or the value may
-be used in cases where additional buffering is needed, such as doing input and
-output on seperate devices. Latency settings are always automatically bound
-to "safe" values, however, so setting extreme values here should not be
+- Latency: Latency settings are ignored in most cases. Exceptions are when
+doing I/O between different devices and as a hint for selecting a realtively
+low or relatively high latency in conjunction with
+paHostFramesPerBufferUnspecified. Latency settings are always automatically
+bound to "safe" values, however, so setting extreme values here should not be
 an issue.
 
 - Buffer Size: paHostFramesPerBufferUnspecified and specific host buffer sizes
 are supported. paHostFramesPerBufferUnspecified works best in "pro" mode,
 where the buffer size and sample rate of the audio device is most likely
-to match the expected values. In the case of paHostFramesPerBuffer, an
-appropriate framesPerBuffer value will be used that guarantees minimum
-requested latency if that's possible.
+to match the expected values.
 
 - Timing info. It reports on stream time, but I'm probably doing something
 wrong since patest_sine_time often reports negative latency numbers. Also,
@@ -118,7 +111,8 @@ render quyality property is used to set the sample rate conversion quality
 as "documented" here:
 http://lists.apple.com/archives/coreaudio-api/2004/Jan/msg00141.html
 
-- x86/Universal Binary: Universal binaries can be build.
+- x86/Universal Binary: to build a universal binary, be sure to use
+the darwin makefile and not the usual configure && make combo.
 
 
 
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core.c b/portaudio/src/hostapi/coreaudio/pa_mac_core.c
index dde93d300..7c887bd6c 100644
--- a/portaudio/src/hostapi/coreaudio/pa_mac_core.c
+++ b/portaudio/src/hostapi/coreaudio/pa_mac_core.c
@@ -65,7 +65,6 @@
 #include "pa_mac_core_internal.h"
 
 #include <string.h> /* strlen(), memcmp() etc. */
-#include <libkern/OSAtomic.h>
 
 #include "pa_mac_core.h"
 #include "pa_mac_core_utilities.h"
@@ -128,8 +127,6 @@ const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input )
    OSStatus error;
    err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
    assert(err == paNoError);
-   if( err != paNoError )
-      return NULL;
    PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
    AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device];
 
@@ -249,6 +246,7 @@ static PaError AbortStream( PaStream *stream );
 static PaError IsStreamStopped( PaStream *s );
 static PaError IsStreamActive( PaStream *stream );
 static PaTime GetStreamTime( PaStream *stream );
+static void setStreamStartTime( PaStream *stream );
 static OSStatus AudioIOProc( void *inRefCon,
                                AudioUnitRenderActionFlags *ioActionFlags,
                                const AudioTimeStamp *inTimeStamp,
@@ -263,12 +261,11 @@ static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
                                int isInput);
 
 static PaError OpenAndSetupOneAudioUnit(
-                                   const PaMacCoreStream *stream,
                                    const PaStreamParameters *inStreamParams,
                                    const PaStreamParameters *outStreamParams,
-                                   const UInt32 requestedFramesPerBuffer,
-                                   UInt32 *actualInputFramesPerBuffer,
-                                   UInt32 *actualOutputFramesPerBuffer,
+                                   const unsigned long requestedFramesPerBuffer,
+                                   unsigned long *actualInputFramesPerBuffer,
+                                   unsigned long *actualOutputFramesPerBuffer,
                                    const PaMacAUHAL *auhalHostApi,
                                    AudioUnit *audioUnit,
                                    AudioConverterRef *srConverter,
@@ -280,37 +277,6 @@ static PaError OpenAndSetupOneAudioUnit(
 #define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \
     PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText )
 
-/*
- * Callback called when starting or stopping a stream.
- */
-static void startStopCallback(
-   void *               inRefCon,
-   AudioUnit            ci,
-   AudioUnitPropertyID  inID,
-   AudioUnitScope       inScope,
-   AudioUnitElement     inElement )
-{
-   PaMacCoreStream *stream = (PaMacCoreStream *) inRefCon;
-   UInt32 isRunning;
-   UInt32 size = sizeof( isRunning );
-   OSStatus err;
-   err = AudioUnitGetProperty( ci, kAudioOutputUnitProperty_IsRunning, inScope, inElement, &isRunning, &size );
-   assert( !err );
-   if( err )
-      isRunning = false; //it's very unclear what to do in case of error here. There's no real way to notify the user, and crashing seems unreasonable.
-   if( isRunning )
-      return; //We are only interested in when we are stopping
-   // -- if we are using 2 I/O units, we only need one notification!
-   if( stream->inputUnit && stream->outputUnit && stream->inputUnit != stream->outputUnit && ci == stream->inputUnit )
-      return;
-   PaStreamFinishedCallback *sfc = stream->streamRepresentation.streamFinishedCallback;
-   if( stream->state == STOPPING )
-      stream->state = STOPPED ;
-   if( sfc )
-      sfc( stream->streamRepresentation.userData );
-}
-
-
 /*currently, this is only used in initialization, but it might be modified
   to be used when the list of devices changes.*/
 static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi)
@@ -529,31 +495,10 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn
 {
     PaError result = paNoError;
     int i;
-    PaMacAUHAL *auhalHostApi = NULL;
+    PaMacAUHAL *auhalHostApi;
     PaDeviceInfo *deviceInfoArray;
-    int unixErr;
 
     VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex));
-	
-	SInt32 major;
-	SInt32 minor;
-	Gestalt(gestaltSystemVersionMajor, &major);
-	Gestalt(gestaltSystemVersionMinor, &minor);
-	
-	// Starting with 10.6 systems, the HAL notification thread is created internally
-	if (major == 10 && minor >= 6) {
-		CFRunLoopRef theRunLoop = NULL;
-		AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
-		OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
-		if (osErr != noErr) {
-			goto error;
-		}
-	}
-	
-    unixErr = initializeXRunListenerList();
-    if( 0 != unixErr ) {
-       return UNIX_ERR(unixErr);
-    }
 
     auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) );
     if( !auhalHostApi )
@@ -673,16 +618,10 @@ error:
 
 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
 {
-    int unixErr;
-
     PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
 
     VVDBUG(("Terminate()\n"));
 
-    unixErr = destroyXRunListenerList();
-    if( 0 != unixErr )
-       UNIX_ERR(unixErr);
-
     /*
         IMPLEMENT ME:
             - clean up any resources not handled by the allocation group
@@ -797,82 +736,12 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
     return paFormatIsSupported;
 }
 
-
-static void UpdateReciprocalOfActualOutputSampleRateFromDeviceProperty( PaMacCoreStream *stream )
-{
-	/* FIXME: not sure if this should be the sample rate of the output device or the output unit */
-	Float64 actualOutputSampleRate = stream->outDeviceSampleRate;
-	UInt32 propSize = sizeof(Float64);
-	OSStatus osErr = AudioDeviceGetProperty( stream->outputDevice, 0, /* isInput = */ FALSE, kAudioDevicePropertyActualSampleRate, &propSize, &actualOutputSampleRate);
-	if( osErr != noErr || actualOutputSampleRate < .01 ) // avoid divide by zero if there's an error
-		actualOutputSampleRate = stream->outDeviceSampleRate;
-	
-	stream->recipricalOfActualOutputSampleRate = 1. / actualOutputSampleRate;
-}
-
-static OSStatus AudioDevicePropertyActualSampleRateListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
-{
-	PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
-	
-	pthread_mutex_lock( &stream->timingInformationMutex );
-	UpdateReciprocalOfActualOutputSampleRateFromDeviceProperty( stream );
-	pthread_mutex_unlock( &stream->timingInformationMutex );
-
-	return noErr;
-}
-
-static void UpdateOutputLatencySamplesFromDeviceProperty( PaMacCoreStream *stream )
-{
-	UInt32 deviceOutputLatencySamples = 0;
-	UInt32 propSize = sizeof(UInt32);
-	OSStatus osErr = AudioDeviceGetProperty( stream->outputDevice, 0, /* isInput= */ FALSE, kAudioDevicePropertyLatency, &propSize, &deviceOutputLatencySamples);
-	if( osErr != noErr )
-		deviceOutputLatencySamples = 0;
-	
-	stream->deviceOutputLatencySamples = deviceOutputLatencySamples;
-}
-
-static OSStatus AudioDevicePropertyOutputLatencySamplesListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
-{
-	PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
-	
-	pthread_mutex_lock( &stream->timingInformationMutex );
-	UpdateOutputLatencySamplesFromDeviceProperty( stream );
-	pthread_mutex_unlock( &stream->timingInformationMutex );
-
-	return noErr;
-}
-
-static void UpdateInputLatencySamplesFromDeviceProperty( PaMacCoreStream *stream )
-{
-	UInt32 deviceInputLatencySamples = 0;
-	UInt32 propSize = sizeof(UInt32);
-	OSStatus osErr = AudioDeviceGetProperty( stream->inputDevice, 0, /* isInput= */ TRUE, kAudioDevicePropertyLatency, &propSize, &deviceInputLatencySamples);
-	if( osErr != noErr )
-		deviceInputLatencySamples = 0;
-	
-	stream->deviceInputLatencySamples = deviceInputLatencySamples;
-}
-
-static OSStatus AudioDevicePropertyInputLatencySamplesListenerProc( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, void *inClientData )
-{
-	PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
-	
-	pthread_mutex_lock( &stream->timingInformationMutex );
-	UpdateInputLatencySamplesFromDeviceProperty( stream );
-	pthread_mutex_unlock( &stream->timingInformationMutex );
-
-	return noErr;
-}
-
-
 static PaError OpenAndSetupOneAudioUnit(
-                                   const PaMacCoreStream *stream,
                                    const PaStreamParameters *inStreamParams,
                                    const PaStreamParameters *outStreamParams,
-                                   const UInt32 requestedFramesPerBuffer,
-                                   UInt32 *actualInputFramesPerBuffer,
-                                   UInt32 *actualOutputFramesPerBuffer,
+                                   const unsigned long requestedFramesPerBuffer,
+                                   unsigned long *actualInputFramesPerBuffer,
+                                   unsigned long *actualOutputFramesPerBuffer,
                                    const PaMacAUHAL *auhalHostApi,
                                    AudioUnit *audioUnit,
                                    AudioConverterRef *srConverter,
@@ -884,7 +753,7 @@ static PaError OpenAndSetupOneAudioUnit(
     Component comp;
     /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/
     AudioStreamBasicDescription desiredFormat;
-    OSStatus result = noErr;
+    OSErr result = noErr;
     PaError paResult = paNoError;
     int line = 0;
     UInt32 callbackKey;
@@ -1012,7 +881,7 @@ static PaError OpenAndSetupOneAudioUnit(
                     audioDevice,
                     sizeof(AudioDeviceID) ) );
     }
-    if( outStreamParams && outStreamParams != inStreamParams )
+    if( outStreamParams )
     {
        *audioDevice = auhalHostApi->devIds[outStreamParams->device] ;
        ERR_WRAP( AudioUnitSetProperty( *audioUnit,
@@ -1022,24 +891,6 @@ static PaError OpenAndSetupOneAudioUnit(
                     audioDevice,
                     sizeof(AudioDeviceID) ) );
     }
-    /* -- add listener for dropouts -- */
-    result = AudioDeviceAddPropertyListener( *audioDevice,
-                                             0,
-                                             outStreamParams ? false : true,
-                                             kAudioDeviceProcessorOverload,
-                                             xrunCallback,
-                                             addToXRunListenerList( (void *)stream ) ) ;
-    if( result == kAudioHardwareIllegalOperationError ) {
-       // -- already registered, we're good
-    } else {
-       // -- not already registered, just check for errors
-       ERR_WRAP( result );
-    }
-    /* -- listen for stream start and stop -- */
-    ERR_WRAP( AudioUnitAddPropertyListener( *audioUnit,
-                                            kAudioOutputUnitProperty_IsRunning,
-                                            startStopCallback,
-                                            (void *)stream ) );
 
     /* -- set format -- */
     bzero( &desiredFormat, sizeof(desiredFormat) );
@@ -1159,7 +1010,7 @@ static PaError OpenAndSetupOneAudioUnit(
                             kAudioUnitScope_Input,
                             OUTPUT_ELEMENT,
                             actualOutputFramesPerBuffer,
-                            sizeof(*actualOutputFramesPerBuffer) ) );
+                            sizeof(unsigned long) ) );
        ERR_WRAP( AudioUnitGetProperty( *audioUnit,
                             kAudioUnitProperty_MaximumFramesPerSlice,
                             kAudioUnitScope_Global,
@@ -1174,7 +1025,7 @@ static PaError OpenAndSetupOneAudioUnit(
                             kAudioUnitScope_Output,
                             INPUT_ELEMENT,
                             actualInputFramesPerBuffer,
-                            sizeof(*actualInputFramesPerBuffer) ) );
+                            sizeof(unsigned long) ) );
 /* Don't know why this causes problems
        ERR_WRAP( AudioUnitGetProperty( *audioUnit,
                             kAudioUnitProperty_MaximumFramesPerSlice,
@@ -1424,7 +1275,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     stream->inputFramesPerBuffer = 0;
     stream->outputFramesPerBuffer = 0;
     stream->bufferProcessorIsInitialized = FALSE;
-	stream->timingInformationMutexIsInitialized = 0;
 
     /* assert( streamCallback ) ; */ /* only callback mode is implemented */
     if( streamCallback )
@@ -1455,7 +1305,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
           /*requested a realtively low latency. make sure this is in range of devices */
           /*try to get the device's min natural buffer size and use that (but no smaller than 64).*/
           AudioValueRange audioRange;
-          UInt32 size = sizeof( audioRange );
+          size_t size = sizeof( audioRange );
           if( inputParameters ) {
              WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device],
                                           0,
@@ -1465,7 +1315,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
              if( result )
                 requested = MAX( requested, audioRange.mMinimum );
           }
-          size = sizeof( audioRange );
           if( outputParameters ) {
              WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device],
                                           0,
@@ -1479,7 +1328,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
           /* requested a realtively high latency. make sure this is in range of devices */
           /*try to get the device's max natural buffer size and use that (but no larger than 1024).*/
           AudioValueRange audioRange;
-          UInt32 size = sizeof( audioRange );
+          size_t size = sizeof( audioRange );
           requested = MIN( requested, 1024 );
           if( inputParameters ) {
              WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device],
@@ -1490,7 +1339,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
              if( result )
                 requested = MIN( requested, audioRange.mMaximum );
           }
-          size = sizeof( audioRange );
           if( outputParameters ) {
              WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device],
                                           0,
@@ -1511,22 +1359,17 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     /* -- Now we actually open and setup streams. -- */
     if( inputParameters && outputParameters && outputParameters->device == inputParameters->device )
     { /* full duplex. One device. */
-       UInt32 inputFramesPerBuffer  = (UInt32) stream->inputFramesPerBuffer;
-       UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
-       result = OpenAndSetupOneAudioUnit( stream,
-                                          inputParameters,
+       result = OpenAndSetupOneAudioUnit( inputParameters,
                                           outputParameters,
                                           framesPerBuffer,
-                                          &inputFramesPerBuffer,
-                                          &outputFramesPerBuffer,
+                                          &(stream->inputFramesPerBuffer),
+                                          &(stream->outputFramesPerBuffer),
                                           auhalHostApi,
                                           &(stream->inputUnit),
                                           &(stream->inputSRConverter),
                                           &(stream->inputDevice),
                                           sampleRate,
                                           stream );
-       stream->inputFramesPerBuffer = inputFramesPerBuffer;
-       stream->outputFramesPerBuffer = outputFramesPerBuffer;
        stream->outputUnit = stream->inputUnit;
        stream->outputDevice = stream->inputDevice;
        if( result != paNoError )
@@ -1534,14 +1377,11 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     }
     else
     { /* full duplex, different devices OR simplex */
-       UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
-       UInt32 inputFramesPerBuffer  = (UInt32) stream->inputFramesPerBuffer;
-       result = OpenAndSetupOneAudioUnit( stream,
-                                          NULL,
+       result = OpenAndSetupOneAudioUnit( NULL,
                                           outputParameters,
                                           framesPerBuffer,
                                           NULL,
-                                          &outputFramesPerBuffer,
+                                          &(stream->outputFramesPerBuffer),
                                           auhalHostApi,
                                           &(stream->outputUnit),
                                           NULL,
@@ -1550,11 +1390,10 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                                           stream );
        if( result != paNoError )
            goto error;
-       result = OpenAndSetupOneAudioUnit( stream,
-                                          inputParameters,
+       result = OpenAndSetupOneAudioUnit( inputParameters,
                                           NULL,
                                           framesPerBuffer,
-                                          &inputFramesPerBuffer,
+                                          &(stream->inputFramesPerBuffer),
                                           NULL,
                                           auhalHostApi,
                                           &(stream->inputUnit),
@@ -1564,8 +1403,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                                           stream );
        if( result != paNoError )
            goto error;
-       stream->inputFramesPerBuffer = inputFramesPerBuffer;
-       stream->outputFramesPerBuffer = outputFramesPerBuffer;
     }
 
     if( stream->inputUnit ) {
@@ -1619,16 +1456,8 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
           }
 
           /* now we can initialize the ring buffer */
-          //FIXME: element size whould probably be szfl*inputchan
-          //       but that will require some work all over the
-          //       place to patch up. szfl may be sufficient and would
-          //       be way easier to handle, but it seems clear from the
-          //       discussion that buffer processor compatibility
-          //       requires szfl*inputchan.
-          //       See revision 1346 and discussion:
-          //       http://techweb.rfa.org/pipermail/portaudio/2008-February/008295.html
           PaUtil_InitializeRingBuffer( &stream->inputRingBuffer,
-                                   1, ringSize*szfl, data ) ;
+                                   ringSize*szfl, data ) ;
           /* advance the read point a little, so we are reading from the
              middle of the buffer */
           if( stream->outputUnit )
@@ -1725,39 +1554,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     stream->userInChan  = inputChannelCount;
     stream->userOutChan = outputChannelCount;
 
-	pthread_mutex_init( &stream->timingInformationMutex, NULL );
-	stream->timingInformationMutexIsInitialized = 1;
-	
-	if( stream->outputUnit ) {
-		UpdateReciprocalOfActualOutputSampleRateFromDeviceProperty( stream );
-		stream->recipricalOfActualOutputSampleRate_ioProcCopy = stream->recipricalOfActualOutputSampleRate;
-		
-		AudioDeviceAddPropertyListener( stream->outputDevice, 0, /* isInput = */ FALSE, kAudioDevicePropertyActualSampleRate, 
-									   AudioDevicePropertyActualSampleRateListenerProc, stream );
-									   		
-		UpdateOutputLatencySamplesFromDeviceProperty( stream );
-		stream->deviceOutputLatencySamples_ioProcCopy = stream->deviceOutputLatencySamples;
-		
-		AudioDeviceAddPropertyListener( stream->outputDevice, 0, /* isInput = */ FALSE, kAudioDevicePropertyLatency, 
-									   AudioDevicePropertyOutputLatencySamplesListenerProc, stream );
-		
-	}else{
-		stream->recipricalOfActualOutputSampleRate = 1.;
-		stream->recipricalOfActualOutputSampleRate_ioProcCopy = 0.;
-		stream->deviceOutputLatencySamples_ioProcCopy = 0;
-	}
-	
-	if( stream->inputUnit ) {
-		UpdateInputLatencySamplesFromDeviceProperty( stream );
-		stream->deviceInputLatencySamples_ioProcCopy = stream->deviceInputLatencySamples;
-		
-		AudioDeviceAddPropertyListener( stream->inputDevice, 0, /* isInput = */ TRUE, kAudioDevicePropertyLatency, 
-									   AudioDevicePropertyInputLatencySamplesListenerProc, stream );
-	}else{
-		stream->deviceInputLatencySamples = 0;
-		stream->deviceInputLatencySamples_ioProcCopy = 0;
-	}
-	
+    stream->isTimeSet   = FALSE;
     stream->state = STOPPED;
     stream->xrunFlags = 0;
 
@@ -1770,12 +1567,56 @@ error:
     return result;
 }
 
+PaTime GetStreamTime( PaStream *s )
+{
+   /* FIXME: I am not at all sure this timing info stuff is right.
+             patest_sine_time reports negative latencies, which is wierd.*/
+    PaMacCoreStream *stream = (PaMacCoreStream*)s;
+    AudioTimeStamp timeStamp;
 
-#define HOST_TIME_TO_PA_TIME( x ) ( AudioConvertHostTimeToNanos( (x) ) * 1.0E-09) /* convert to nanoseconds and then to seconds */
+    VVDBUG(("GetStreamTime()\n"));
 
-PaTime GetStreamTime( PaStream *s )
+    if ( !stream->isTimeSet )
+        return (PaTime)0;
+
+    if ( stream->outputDevice ) {
+        AudioDeviceGetCurrentTime( stream->outputDevice, &timeStamp);
+        return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->outDeviceSampleRate;
+    } else if ( stream->inputDevice ) {
+        AudioDeviceGetCurrentTime( stream->inputDevice, &timeStamp);
+    return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->inDeviceSampleRate;
+    } else {
+        return (PaTime)0;
+    }
+}
+
+static void setStreamStartTime( PaStream *stream )
+{
+   /* FIXME: I am not at all sure this timing info stuff is right.
+             patest_sine_time reports negative latencies, which is wierd.*/
+   PaMacCoreStream *s = (PaMacCoreStream *) stream;
+   VVDBUG(("setStreamStartTime()\n"));
+   if( s->outputDevice )
+      AudioDeviceGetCurrentTime( s->outputDevice, &s->startTime);
+   else if( s->inputDevice )
+      AudioDeviceGetCurrentTime( s->inputDevice, &s->startTime);
+   else
+      bzero( &s->startTime, sizeof( s->startTime ) );
+
+   //FIXME: we need a memory barier here
+
+   s->isTimeSet = TRUE;
+}
+
+
+static PaTime TimeStampToSecs(PaMacCoreStream *stream, const AudioTimeStamp* timeStamp)
 {
-	return HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); 
+    VVDBUG(("TimeStampToSecs()\n"));
+    //printf( "ATS: %lu, %g, %g\n", timeStamp->mFlags, timeStamp->mSampleTime, timeStamp->mRateScalar );
+    if (timeStamp->mFlags & kAudioTimeStampSampleTimeValid)
+        return (timeStamp->mSampleTime / stream->sampleRate);
+    else
+        return 0;
 }
 
 #define RING_BUFFER_EMPTY (1000)
@@ -1786,19 +1627,19 @@ static OSStatus ringBufferIOProc( AudioConverterRef inAudioConverter,
                              void*inUserData )
 {
    void *dummyData;
-   ring_buffer_size_t dummySize;
+   long dummySize;
    PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData;
 
    VVDBUG(("ringBufferIOProc()\n"));
 
+   assert( sizeof( UInt32 ) == sizeof( long ) );
    if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) {
       *outData = NULL;
       *ioDataSize = 0;
       return RING_BUFFER_EMPTY;
    }
-   assert(sizeof(UInt32) == sizeof(ring_buffer_size_t));
    PaUtil_GetRingBufferReadRegions( rb, *ioDataSize,
-                                    outData, (ring_buffer_size_t *)ioDataSize, 
+                                    outData, (long *)ioDataSize, 
                                     &dummyData, &dummySize );
       
    assert( *ioDataSize );
@@ -1856,68 +1697,24 @@ static OSStatus AudioIOProc( void *inRefCon,
    }
       ----------------------------------------------------------------- */
 
-	/* compute PaStreamCallbackTimeInfo */
-	
-	if( pthread_mutex_trylock( &stream->timingInformationMutex ) == 0 ){
-		/* snapshot the ioproc copy of timing information */
-		stream->deviceOutputLatencySamples_ioProcCopy = stream->deviceOutputLatencySamples;
-		stream->recipricalOfActualOutputSampleRate_ioProcCopy = stream->recipricalOfActualOutputSampleRate;
-		stream->deviceInputLatencySamples_ioProcCopy = stream->deviceInputLatencySamples;
-		pthread_mutex_unlock( &stream->timingInformationMutex );
-	}
-	
-	/* For timeInfo.currentTime we could calculate current time backwards from the HAL audio 
-	 output time to give a more accurate impression of the current timeslice but it doesn't 
-	 seem worth it at the moment since other PA host APIs don't do any better.
-	 */
-	timeInfo.currentTime = HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() );
-	
-	/*
-	 For an input HAL AU, inTimeStamp is the time the samples are received from the hardware,
-	 for an output HAL AU inTimeStamp is the time the samples are sent to the hardware. 
-	 PA expresses timestamps in terms of when the samples enter the ADC or leave the DAC
-	 so we add or subtract kAudioDevicePropertyLatency below.
-	 */
-	
-	/* FIXME: not sure what to do below if the host timestamps aren't valid (kAudioTimeStampHostTimeValid isn't set)
-	 Could ask on CA mailing list if it is possible for it not to be set. If so, could probably grab a now timestamp
-	 at the top and compute from there (modulo scheduling jitter) or ask on mailing list for other options. */
-	
-	if( isRender )
-	{
-		if( stream->inputUnit ) /* full duplex */
-		{
-			if( stream->inputUnit == stream->outputUnit ) /* full duplex AUHAL IOProc */
-			{
-				/* FIXME: review. i'm not sure this computation of inputBufferAdcTime is correct for a full-duplex AUHAL */
-				timeInfo.inputBufferAdcTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime) 
-						- stream->deviceInputLatencySamples_ioProcCopy * stream->recipricalOfActualOutputSampleRate_ioProcCopy; // FIXME should be using input sample rate here?
-				timeInfo.outputBufferDacTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime) 
-						+ stream->deviceOutputLatencySamples_ioProcCopy * stream->recipricalOfActualOutputSampleRate_ioProcCopy;
-			}
-			else /* full duplex with ring-buffer from a separate input AUHAL ioproc */
-			{
-				/* FIXME: review. this computation of inputBufferAdcTime is definitely wrong since it doesn't take the ring buffer latency into account */
-				timeInfo.inputBufferAdcTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime) 
-						- stream->deviceInputLatencySamples_ioProcCopy * stream->recipricalOfActualOutputSampleRate_ioProcCopy; // FIXME should be using input sample rate here?
-				timeInfo.outputBufferDacTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime)
-						+ stream->deviceOutputLatencySamples_ioProcCopy * stream->recipricalOfActualOutputSampleRate_ioProcCopy;
-			}
-		}
-		else /* output only */
-		{
-			timeInfo.inputBufferAdcTime = 0;
-			timeInfo.outputBufferDacTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime)
-					+ stream->deviceOutputLatencySamples_ioProcCopy * stream->recipricalOfActualOutputSampleRate_ioProcCopy;
-		}
-	}
-	else /* input only */
-	{
-		timeInfo.inputBufferAdcTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime) 
-				- stream->deviceInputLatencySamples_ioProcCopy * stream->recipricalOfActualOutputSampleRate_ioProcCopy; // FIXME should be using input sample rate here?
-		timeInfo.outputBufferDacTime = 0;
-	}
-	
+   if( !stream->isTimeSet )
+      setStreamStartTime( stream );
+
+   if( isRender ) {
+      AudioTimeStamp currentTime;
+      timeInfo.outputBufferDacTime = TimeStampToSecs(stream, inTimeStamp);
+      AudioDeviceGetCurrentTime(stream->outputDevice, &currentTime);
+      timeInfo.currentTime = TimeStampToSecs(stream, &currentTime);
+   }
+   if( isRender && stream->inputUnit == stream->outputUnit )
+      timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp);
+   if( !isRender ) {
+      AudioTimeStamp currentTime;
+      timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp);
+      AudioDeviceGetCurrentTime(stream->inputDevice, &currentTime);
+      timeInfo.currentTime = TimeStampToSecs(stream, &currentTime);
+   }
+
    //printf( "---%g, %g, %g\n", timeInfo.inputBufferAdcTime, timeInfo.currentTime, timeInfo.outputBufferDacTime );
 
    if( isRender && stream->inputUnit == stream->outputUnit
@@ -1930,14 +1727,14 @@ static OSStatus AudioIOProc( void *inRefCon,
        * we do not use the input SR converter or the input ring buffer.
        *
        */
-      OSStatus err = 0;
+      OSErr err = 0;
       unsigned long frames;
 
       /* -- start processing -- */
       PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
                                     &timeInfo,
                                     stream->xrunFlags );
-      stream->xrunFlags = 0; //FIXME: this flag also gets set outside by a callback, which calls the xrunCallback function. It should be in the same thread as the main audio callback, but the apple docs just use the word "usually" so it may be possible to loose an xrun notification, if that callback happens here.
+      stream->xrunFlags = 0;
 
       /* -- compute frames. do some checks -- */
       assert( ioData->mNumberBuffers == 1 );
@@ -1951,8 +1748,7 @@ static OSStatus AudioIOProc( void *inRefCon,
                     INPUT_ELEMENT,
                     inNumberFrames,
                     &stream->inputAudioBufferList );
-      /* FEEDBACK: I'm not sure what to do when this call fails. There's nothing in the PA API to
-       * do about failures in the callback system. */
+      /* FEEDBACK: I'm not sure what to do when this call fails */
       assert( !err );
 
       PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
@@ -2054,7 +1850,7 @@ static OSStatus AudioIOProc( void *inRefCon,
                because we have to do a little buffer processing that the
                AudioConverter would otherwise handle for us. */
             void *data1, *data2;
-            ring_buffer_size_t size1, size2;
+            long size1, size2;
             PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer,
                                              inChan*frames*flsz,
                                              &data1, &size1,
@@ -2072,7 +1868,7 @@ static OSStatus AudioIOProc( void *inRefCon,
                PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1 );
             } else if( ( size1 + size2 ) / ( flsz * inChan ) < frames ) {
                /*we underflowed. take what data we can, zero the rest.*/
-               unsigned char data[frames*inChan*flsz];
+               float data[frames*inChan];
                if( size1 )
                   memcpy( data, data1, size1 );
                if( size2 )
@@ -2126,7 +1922,7 @@ static OSStatus AudioIOProc( void *inRefCon,
        * if this is an input-only stream, we need to process it more,
        * otherwise, we let the output case deal with it.
        */
-      OSStatus err = 0;
+      OSErr err = 0;
       int chan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels ;
       /* FIXME: looping here may not actually be necessary, but it was something I tried in testing. */
       do {
@@ -2229,6 +2025,7 @@ static OSStatus AudioIOProc( void *inRefCon,
    case paContinue: break;
    case paComplete:
    case paAbort:
+      stream->isTimeSet = FALSE;
       stream->state = CALLBACK_STOPPED ;
       if( stream->outputUnit )
          AudioOutputUnitStop(stream->outputUnit);
@@ -2257,37 +2054,6 @@ static PaError CloseStream( PaStream* s )
     VDBUG( ( "Closing stream.\n" ) );
 
     if( stream ) {
-		
-		if( stream->outputUnit ) {
-			AudioDeviceRemovePropertyListener( stream->outputDevice, 0, /* isInput = */ FALSE, kAudioDevicePropertyActualSampleRate, 
-											  AudioDevicePropertyActualSampleRateListenerProc );
-			AudioDeviceRemovePropertyListener( stream->outputDevice, 0, /* isInput = */ FALSE, kAudioDevicePropertyLatency, 
-											  AudioDevicePropertyOutputLatencySamplesListenerProc );
-		}
-		
-		if( stream->inputUnit ) {
-			AudioDeviceRemovePropertyListener( stream->inputDevice, 0, /* isInput = */ TRUE, kAudioDevicePropertyLatency, 
-											  AudioDevicePropertyInputLatencySamplesListenerProc );
-		}
-		
-       if( stream->outputUnit ) {
-          int count = removeFromXRunListenerList( stream );
-          if( count == 0 )
-             AudioDeviceRemovePropertyListener( stream->outputDevice,
-                                                0,
-                                                false,
-                                                kAudioDeviceProcessorOverload,
-                                                xrunCallback );
-       }
-       if( stream->inputUnit && stream->outputUnit != stream->inputUnit ) {
-          int count = removeFromXRunListenerList( stream );
-          if( count == 0 )
-             AudioDeviceRemovePropertyListener( stream->inputDevice,
-                                                0,
-                                                true,
-                                                kAudioDeviceProcessorOverload,
-                                                xrunCallback );
-       }
        if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
           AudioUnitUninitialize( stream->outputUnit );
           CloseComponent( stream->outputUnit );
@@ -2316,10 +2082,6 @@ static PaError CloseStream( PaStream* s )
           return result;
        if( stream->bufferProcessorIsInitialized )
           PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
-		
-       if( stream->timingInformationMutexIsInitialized )
-          pthread_mutex_destroy( &stream->timingInformationMutex );
-
        PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
        PaUtil_FreeMemory( stream );
     }
@@ -2327,10 +2089,11 @@ static PaError CloseStream( PaStream* s )
     return result;
 }
 
+
 static PaError StartStream( PaStream *s )
 {
     PaMacCoreStream *stream = (PaMacCoreStream*)s;
-    OSStatus result = noErr;
+    OSErr result = noErr;
     VVDBUG(("StartStream()\n"));
     VDBUG( ( "Starting stream.\n" ) );
 
@@ -2349,7 +2112,10 @@ static PaError StartStream( PaStream *s )
     if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
        ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) );
     }
-	
+
+    //setStreamStartTime( stream );
+    //stream->isTimeSet = TRUE;
+
     return paNoError;
 #undef ERR_WRAP
 }
@@ -2372,7 +2138,7 @@ static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioU
 static PaError StopStream( PaStream *s )
 {
     PaMacCoreStream *stream = (PaMacCoreStream*)s;
-    OSStatus result = noErr;
+    OSErr result = noErr;
     PaError paErr;
     VVDBUG(("StopStream()\n"));
 
@@ -2380,6 +2146,7 @@ static PaError StopStream( PaStream *s )
     waitUntilBlioWriteBufferIsFlushed( &stream->blio );
     VDBUG( ( "Stopping stream.\n" ) );
 
+    stream->isTimeSet = FALSE;
     stream->state = STOPPING;
 
 #define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
@@ -2427,6 +2194,10 @@ static PaError StopStream( PaStream *s )
     if( paErr )
        return paErr;
 
+/*
+    //stream->isTimeSet = FALSE;
+*/
+
     VDBUG( ( "Stream Stopped.\n" ) );
     return paNoError;
 #undef ERR_WRAP
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c
index 6d31a713d..3b81389d3 100644
--- a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c
+++ b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c
@@ -53,7 +53,7 @@
 
 /**
  @file
- @ingroup hostapi_src
+ @ingroup hostaip_src
 
  This file contains the implementation
  required for blocking I/O. It is separated from pa_mac_core.c simply to ease
@@ -85,22 +85,6 @@ static size_t computeSampleSizeFromFormat( PaSampleFormat format )
    default: return 0;
    }
 }
-/*
- * Same as computeSampleSizeFromFormat, except that if
- * the size is not a power of two, it returns the next power of two up
- */
-static size_t computeSampleSizeFromFormatPow2( PaSampleFormat format )
-{
-   switch( format ) {
-   case paFloat32: return 4;
-   case paInt32: return 4;
-   case paInt24: return 4;
-   case paInt16: return 2;
-   case paInt8: case paUInt8: return 1;
-   default: return 0;
-   }
-}
-
 
 
 /*
@@ -121,7 +105,6 @@ PaError initializeBlioRingBuffers(
 {
    void *data;
    int result;
-   OSStatus err;
 
    /* zeroify things */
    bzero( blio, sizeof( PaMacBlio ) );
@@ -131,14 +114,10 @@ PaError initializeBlioRingBuffers(
    blio->outputRingBuffer.buffer = NULL;
 
    /* initialize simple data */
-   blio->ringBufferFrames = ringBufferSize;
    blio->inputSampleFormat = inputSampleFormat;
-   blio->inputSampleSizeActual = computeSampleSizeFromFormat(inputSampleFormat);
-   blio->inputSampleSizePow2 = computeSampleSizeFromFormatPow2(inputSampleFormat);
+   blio->inputSampleSize = computeSampleSizeFromFormat(inputSampleFormat);
    blio->outputSampleFormat = outputSampleFormat;
-   blio->outputSampleSizeActual = computeSampleSizeFromFormat(outputSampleFormat);
-   blio->outputSampleSizePow2 = computeSampleSizeFromFormatPow2(outputSampleFormat);
-
+   blio->outputSampleSize = computeSampleSizeFromFormat(outputSampleFormat);
    blio->framesPerBuffer = framesPerBuffer;
    blio->inChan = inChan;
    blio->outChan = outChan;
@@ -163,32 +142,30 @@ PaError initializeBlioRingBuffers(
    result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) );
 #endif
    if( inChan ) {
-      data = calloc( ringBufferSize, blio->inputSampleSizePow2*inChan );
+      data = calloc( ringBufferSize, blio->inputSampleSize );
       if( !data )
       {
          result = paInsufficientMemory;
          goto error;
       }
 
-      err = PaUtil_InitializeRingBuffer(
+      assert( 0 == PaUtil_InitializeRingBuffer(
             &blio->inputRingBuffer,
-            1, ringBufferSize*blio->inputSampleSizePow2*inChan,
-            data );
-      assert( !err );
+            ringBufferSize*blio->inputSampleSize,
+            data ) );
    }
    if( outChan ) {
-      data = calloc( ringBufferSize, blio->outputSampleSizePow2*outChan );
+      data = calloc( ringBufferSize, blio->outputSampleSize );
       if( !data )
       {
          result = paInsufficientMemory;
          goto error;
       }
 
-      err = PaUtil_InitializeRingBuffer(
+      assert( 0 == PaUtil_InitializeRingBuffer(
             &blio->outputRingBuffer,
-            1, ringBufferSize*blio->outputSampleSizePow2*outChan,
-            data );
-      assert( !err );
+            ringBufferSize*blio->outputSampleSize,
+            data ) );
    }
 
    result = resetBlioRingBuffers( blio );
@@ -270,8 +247,7 @@ PaError resetBlioRingBuffers( PaMacBlio *blio )
       bzero( blio->outputRingBuffer.buffer,
              blio->outputRingBuffer.bufferSize );
       /* Advance buffer */
-      PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->ringBufferFrames*blio->outputSampleSizeActual*blio->outChan );
-      //PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->outputRingBuffer.bufferSize );
+      PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->outputRingBuffer.bufferSize );
 
       /* Update isOutputFull. */
 #ifdef PA_MAC__BLIO_MUTEX
@@ -347,8 +323,6 @@ int BlioCallback( const void *input, void *output, unsigned long frameCount,
    long avail;
    long toRead;
    long toWrite;
-   long read;
-   long written;
 
    /* set flags returned by OS: */
    OSAtomicOr32( statusFlags, &blio->statusFlags ) ;
@@ -358,15 +332,14 @@ int BlioCallback( const void *input, void *output, unsigned long frameCount,
       avail = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer );
 
       /* check for underflow */
-      if( avail < frameCount * blio->inputSampleSizeActual * blio->inChan )
+      if( avail < frameCount * blio->inputSampleSize * blio->inChan )
          OSAtomicOr32( paInputOverflow, &blio->statusFlags );
 
-      toRead = MIN( avail, frameCount * blio->inputSampleSizeActual * blio->inChan );
+      toRead = MIN( avail, frameCount * blio->inputSampleSize * blio->inChan );
 
       /* copy the data */
       /*printf( "reading %d\n", toRead );*/
-      read = PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, toRead );
-      assert( toRead == read );
+      assert( toRead == PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, toRead ) );
 #ifdef PA_MAC__BLIO_MUTEX
       /* Priority inversion. See notes below. */
       blioSetIsInputEmpty( blio, false );
@@ -379,18 +352,17 @@ int BlioCallback( const void *input, void *output, unsigned long frameCount,
       avail = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
 
       /* check for underflow */
-      if( avail < frameCount * blio->outputSampleSizeActual * blio->outChan )
+      if( avail < frameCount * blio->outputSampleSize * blio->outChan )
          OSAtomicOr32( paOutputUnderflow, &blio->statusFlags );
 
-      toWrite = MIN( avail, frameCount * blio->outputSampleSizeActual * blio->outChan );
+      toWrite = MIN( avail, frameCount * blio->outputSampleSize * blio->outChan );
 
-      if( toWrite != frameCount * blio->outputSampleSizeActual * blio->outChan )
+      if( toWrite != frameCount * blio->outputSampleSize * blio->outChan )
          bzero( ((char *)output)+toWrite,
-                frameCount * blio->outputSampleSizeActual * blio->outChan - toWrite );
+                frameCount * blio->outputSampleSize * blio->outChan - toWrite );
       /* copy the data */
       /*printf( "writing %d\n", toWrite );*/
-      written = PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, toWrite );
-      assert( toWrite == written );
+      assert( toWrite == PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, toWrite ) );
 #ifdef PA_MAC__BLIO_MUTEX
       /* We have a priority inversion here. However, we will only have to
          wait if this was true and is now false, which means we've got
@@ -441,11 +413,11 @@ PaError ReadStream( PaStream* stream,
 #endif
           }
        } while( avail == 0 );
-       toRead = MIN( avail, frames * blio->inputSampleSizeActual * blio->inChan );
-       toRead -= toRead % blio->inputSampleSizeActual * blio->inChan ;
+       toRead = MIN( avail, frames * blio->inputSampleSize * blio->inChan );
+       toRead -= toRead % blio->inputSampleSize * blio->inChan ;
        PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, toRead );
        cbuf += toRead;
-       frames -= toRead / ( blio->inputSampleSizeActual * blio->inChan );
+       frames -= toRead / ( blio->inputSampleSize * blio->inChan );
 
        if( toRead == avail ) {
 #ifdef PA_MAC_BLIO_MUTEX
@@ -471,7 +443,7 @@ PaError ReadStream( PaStream* stream,
 
     /* report underflow only once: */
     if( ret ) {
-       OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags );
+       OSAtomicAnd32( ~paInputOverflow, &blio->statusFlags );
        ret = paInputOverflowed;
     }
 
@@ -519,11 +491,11 @@ PaError WriteStream( PaStream* stream,
           }
        } while( avail == 0 );
 
-       toWrite = MIN( avail, frames * blio->outputSampleSizeActual * blio->outChan );
-       toWrite -= toWrite % blio->outputSampleSizeActual * blio->outChan ;
+       toWrite = MIN( avail, frames * blio->outputSampleSize * blio->outChan );
+       toWrite -= toWrite % blio->outputSampleSize * blio->outChan ;
        PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, toWrite );
        cbuf += toWrite;
-       frames -= toWrite / ( blio->outputSampleSizeActual * blio->outChan );
+       frames -= toWrite / ( blio->outputSampleSize * blio->outChan );
 
 #ifdef PA_MAC_BLIO_MUTEX
        if( toWrite == avail ) {
@@ -548,7 +520,7 @@ PaError WriteStream( PaStream* stream,
 
     /* report underflow only once: */
     if( ret ) {
-      OSAtomicAnd32( (uint32_t)(~paOutputUnderflow), &blio->statusFlags );
+      OSAtomicAnd32( ~paOutputUnderflow, &blio->statusFlags );
       ret = paOutputUnderflowed;
     }
 
@@ -577,7 +549,7 @@ signed long GetStreamReadAvailable( PaStream* stream )
     VVDBUG(("GetStreamReadAvailable()\n"));
 
     return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer )
-                         / ( blio->inputSampleSizeActual * blio->inChan );
+                         / ( blio->outputSampleSize * blio->outChan );
 }
 
 
@@ -587,6 +559,6 @@ signed long GetStreamWriteAvailable( PaStream* stream )
     VVDBUG(("GetStreamWriteAvailable()\n"));
 
     return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer )
-                         / ( blio->outputSampleSizeActual * blio->outChan );
+                         / ( blio->outputSampleSize * blio->outChan );
 }
 
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h
index 971223b3c..8ad79eaa7 100644
--- a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h
+++ b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h
@@ -53,7 +53,7 @@
 
 /**
  @file
- @ingroup hostapi_src
+ @ingroup hostaip_src
 */
 
 #ifndef PA_MAC_CORE_BLOCKING_H_
@@ -79,13 +79,10 @@
 typedef struct {
     PaUtilRingBuffer inputRingBuffer;
     PaUtilRingBuffer outputRingBuffer;
-    size_t ringBufferFrames;
     PaSampleFormat inputSampleFormat;
-    size_t inputSampleSizeActual;
-    size_t inputSampleSizePow2;
+    size_t inputSampleSize;
     PaSampleFormat outputSampleFormat;
-    size_t outputSampleSizeActual;
-    size_t outputSampleSizePow2;
+    size_t outputSampleSize;
 
     size_t framesPerBuffer;
 
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h
index 9277321b3..998b819ce 100644
--- a/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h
+++ b/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h
@@ -61,11 +61,10 @@
 #ifndef PA_MAC_CORE_INTERNAL_H__
 #define PA_MAC_CORE_INTERNAL_H__
 
-#include <CoreAudio/CoreAudio.h>
-#include <CoreServices/CoreServices.h>
 #include <AudioUnit/AudioUnit.h>
 #include <AudioToolbox/AudioToolbox.h>
 
+
 #include "portaudio.h"
 #include "pa_util.h"
 #include "pa_hostapi.h"
@@ -140,15 +139,14 @@ typedef struct PaMacCoreStream
     /* We need to preallocate an inputBuffer for reading data. */
     AudioBufferList inputAudioBufferList;
     AudioTimeStamp startTime;
-    /* FIXME: instead of volatile, these should be properly memory barriered */
     volatile PaStreamCallbackFlags xrunFlags;
+    volatile bool isTimeSet;
     volatile enum {
        STOPPED          = 0, /* playback is completely stopped,
                                 and the user has called StopStream(). */
        CALLBACK_STOPPED = 1, /* callback has requested stop,
                                 but user has not yet called StopStream(). */
-       STOPPING         = 2, /* The stream is in the process of closing
-                                because the user has called StopStream.
+       STOPPING         = 2, /* The stream is in the process of closing.
                                 This state is just used internally;
                                 externally it is indistinguishable from
                                 ACTIVE.*/
@@ -158,18 +156,6 @@ typedef struct PaMacCoreStream
     //these may be different from the stream sample rate due to SR conversion:
     double outDeviceSampleRate;
     double inDeviceSampleRate;
-	
-	/* data updated by main thread and notifications, protected by timingInformationMutex */
-	int timingInformationMutexIsInitialized;
-	pthread_mutex_t timingInformationMutex;
-	Float64 recipricalOfActualOutputSampleRate;
-	UInt32 deviceOutputLatencySamples;
-	UInt32 deviceInputLatencySamples;
-	
-	/* while the io proc is active, the following values are only accessed and manipulated by the ioproc */
-	Float64 recipricalOfActualOutputSampleRate_ioProcCopy;
-	UInt32 deviceOutputLatencySamples_ioProcCopy;
-	UInt32 deviceInputLatencySamples_ioProcCopy;
 }
 PaMacCoreStream;
 
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
index b58b82202..374032513 100644
--- a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
+++ b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
@@ -57,11 +57,6 @@
 */
 
 #include "pa_mac_core_utilities.h"
-#include "pa_mac_core_internal.h"
-#include <libkern/OSAtomic.h>
-#include <strings.h>
-#include <pthread.h>
-#include <sys/time.h>
 
 PaError PaMacCore_SetUnixError( int err, int line )
 {
@@ -204,19 +199,10 @@ PaError PaMacCore_SetError(OSStatus error, int line, int isError)
     else
         errorType = "Warning";
 
-    char str[20];
-    // see if it appears to be a 4-char-code
-    *(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error);
-    if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4]))
-    {
-        str[0] = str[5] = '\'';
-        str[6] = '\0';
-    } else {
-        // no, format it as an integer
-        sprintf(str, "%d", (int)error);
-    }
-
-    DBUG(("%s on line %d: err='%s', msg=%s\n", errorType, line, str, errorText));
+    if ((int)error < -99999 || (int)error > 99999)
+        DBUG(("%s on line %d: err='%4s', msg='%s'\n", errorType, line, (const char *)&error, errorText));
+    else
+        DBUG(("%s on line %d: err=%d, 0x%x, msg='%s'\n", errorType, line, (int)error, (unsigned)error, errorText));
 
     PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );
 
@@ -306,13 +292,8 @@ long computeRingBufferSize( const PaStreamParameters *inputParameters,
 /*
  * Durring testing of core audio, I found that serious crashes could occur
  * if properties such as sample rate were changed multiple times in rapid
- * succession. The function below could be used to with a condition variable.
- * to prevent propertychanges from happening until the last property
- * change is acknowledged. Instead, I implemented a busy-wait, which is simpler
- * to implement b/c in second round of testing (nov '09) property changes occured
- * quickly and so there was no real way to test the condition variable implementation.
- * therefore, this function is not used, but it is aluded to in commented code below,
- * since it represents a theoretically better implementation.
+ * succession. The function below has some fancy logic to make sure that changes
+ * are acknowledged before another is requested. That seems to help a lot.
  */
 
 OSStatus propertyProc(
@@ -322,7 +303,9 @@ OSStatus propertyProc(
     AudioDevicePropertyID inPropertyID, 
     void* inClientData )
 {
-   // this is where we would set the condition variable
+   MutexAndBool *mab = (MutexAndBool *) inClientData;
+   mab->once = TRUE;
+   pthread_mutex_unlock( &(mab->mutex) );
    return noErr;
 }
 
@@ -330,11 +313,7 @@ OSStatus propertyProc(
    be acknowledged, and returns the final value, which is not guaranteed
    by this function to be the same as the desired value. Obviously, this
    function can only be used for data whose input and output are the
-   same size and format, and their size and format are known in advance.
-   whether or not the call succeeds, if the data is successfully read,
-   it is returned in outPropertyData. If it is not read successfully,
-   outPropertyData is zeroed, which may or may not be useful in
-   determining if the property was read. */
+   same size and format, and their size and format are known in advance.*/
 PaError AudioDeviceSetPropertyNowAndWaitForChange(
     AudioDeviceID inDevice,
     UInt32 inChannel, 
@@ -345,72 +324,83 @@ PaError AudioDeviceSetPropertyNowAndWaitForChange(
     void *outPropertyData )
 {
    OSStatus macErr;
+   int unixErr;
+   MutexAndBool mab;
    UInt32 outPropertyDataSize = inPropertyDataSize;
 
    /* First, see if it already has that value. If so, return. */
    macErr = AudioDeviceGetProperty( inDevice, inChannel,
                                  isInput, inPropertyID, 
                                  &outPropertyDataSize, outPropertyData );
-   if( macErr ) {
-      memset( outPropertyData, 0, inPropertyDataSize );
-      goto failMac;
-   }
+   if( macErr )
+      goto failMac2;
    if( inPropertyDataSize!=outPropertyDataSize )
       return paInternalError;
    if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
       return paNoError;
 
-   /* Ideally, we'd use a condition variable to determine changes.
-      we could set that up here. */
+   /* setup and lock mutex */
+   mab.once = FALSE;
+   unixErr = pthread_mutex_init( &mab.mutex, NULL );
+   if( unixErr )
+      goto failUnix2;
+   unixErr = pthread_mutex_lock( &mab.mutex );
+   if( unixErr )
+      goto failUnix;
 
-   /* If we were using a cond variable, we'd do something useful here,
-      but for now, this is just to make 10.6 happy. */
+   /* add property listener */
    macErr = AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
                                    inPropertyID, propertyProc,
-                                   NULL ); 
+                                   &mab ); 
    if( macErr )
-      /* we couldn't add a listener. */
       goto failMac;
-
    /* set property */
    macErr  = AudioDeviceSetProperty( inDevice, NULL, inChannel,
                                  isInput, inPropertyID,
                                  inPropertyDataSize, inPropertyData );
+   if( macErr ) {
+      /* we couldn't set the property, so we'll just unlock the mutex
+         and move on. */
+      pthread_mutex_unlock( &mab.mutex );
+   }
+
+   /* wait for property to change */                      
+   unixErr = pthread_mutex_lock( &mab.mutex );
+   if( unixErr )
+      goto failUnix;
+
+   /* now read the property back out */
+   macErr = AudioDeviceGetProperty( inDevice, inChannel,
+                                 isInput, inPropertyID, 
+                                 &outPropertyDataSize, outPropertyData );
    if( macErr )
       goto failMac;
+   /* cleanup */
+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
+                                      inPropertyID, propertyProc );
+   unixErr = pthread_mutex_unlock( &mab.mutex );
+   if( unixErr )
+      goto failUnix2;
+   unixErr = pthread_mutex_destroy( &mab.mutex );
+   if( unixErr )
+      goto failUnix2;
 
-   /* busy-wait up to 30 seconds for the property to change */
-   /* busy-wait is justified here only because the correct alternative (condition variable)
-      was hard to test, since most of the waiting ended up being for setting rather than
-      getting in OS X 10.5. This was not the case in earlier OS versions. */
-   struct timeval tv1, tv2;
-   gettimeofday( &tv1, NULL );
-   memcpy( &tv2, &tv1, sizeof( struct timeval ) );
-   while( tv2.tv_sec - tv1.tv_sec < 30 ) {
-      /* now read the property back out */
-      macErr = AudioDeviceGetProperty( inDevice, inChannel,
-                                    isInput, inPropertyID, 
-                                    &outPropertyDataSize, outPropertyData );
-      if( macErr ) {
-         memset( outPropertyData, 0, inPropertyDataSize );
-         goto failMac;
-      }
-      /* and compare... */
-      if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) {
-         AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc );
-         return paNoError;
-      }
-      /* No match yet, so let's sleep and try again. */
-      Pa_Sleep( 100 );
-      gettimeofday( &tv2, NULL );
-   }
-   DBUG( ("Timeout waiting for device setting.\n" ) );
-   
-   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc );
    return paNoError;
 
+ failUnix:
+   pthread_mutex_destroy( &mab.mutex );
+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
+                                      inPropertyID, propertyProc );
+
+ failUnix2:
+   DBUG( ("Error #%d while setting a device property: %s\n", unixErr, strerror( unixErr ) ) );
+   return paUnanticipatedHostError;
+
  failMac:
-   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc );
+   pthread_mutex_destroy( &mab.mutex );
+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
+                                      inPropertyID, propertyProc );
+ failMac2:
    return ERR( macErr );
 }
 
@@ -428,6 +418,10 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device,
                                     const bool requireExact,
                                     const Float64 desiredSrate )
 {
+   /*FIXME: changing the sample rate is disruptive to other programs using the
+            device, so it might be good to offer a custom flag to not change the
+            sample rate and just do conversion. (in my casual tests, there is
+            no disruption unless the sample rate really does need to change) */
    const bool isInput = isOutput ? 0 : 1;
    Float64 srate;
    UInt32 propsize = sizeof( Float64 );
@@ -439,15 +433,13 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device,
    VDBUG(("Setting sample rate for device %ld to %g.\n",device,(float)desiredSrate));
 
    /* -- try setting the sample rate -- */
-   srate = 0;
    err = AudioDeviceSetPropertyNowAndWaitForChange(
                                  device, 0, isInput,
                                  kAudioDevicePropertyNominalSampleRate,
                                  propsize, &desiredSrate, &srate );
+   if( err )
+      return err;
 
-   /* -- if the rate agrees, and was changed, we are done -- */
-   if( srate != 0 && srate == desiredSrate )
-      return paNoError;
    /* -- if the rate agrees, and we got no errors, we are done -- */
    if( !err && srate == desiredSrate )
       return paNoError;
@@ -500,18 +492,18 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device,
 
    /* -- set the sample rate -- */
    propsize = sizeof( best );
-   srate = 0;
    err = AudioDeviceSetPropertyNowAndWaitForChange(
                                  device, 0, isInput,
                                  kAudioDevicePropertyNominalSampleRate,
                                  propsize, &best, &srate );
-
-   /* -- if the set rate matches, we are done -- */
-   if( srate != 0 && srate == best )
-      return paNoError;
+   if( err )
+      return err;
 
    if( err )
       return ERR( err );
+   /* -- if the set rate matches, we are done -- */
+   if( srate == best )
+      return paNoError;
 
    /* -- otherwise, something wierd happened: we didn't set the rate, and we got no errors. Just bail. */
    return paInternalError;
@@ -528,9 +520,9 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device,
    not usually catastrophic.
 */
 PaError setBestFramesPerBuffer( const AudioDeviceID device,
-                                const bool isOutput,
-                                UInt32 requestedFramesPerBuffer, 
-                                UInt32 *actualFramesPerBuffer )
+                                       const bool isOutput,
+                                       unsigned long requestedFramesPerBuffer, 
+                                       unsigned long *actualFramesPerBuffer )
 {
    UInt32 afpb;
    const bool isInput = !isOutput;
@@ -617,117 +609,3 @@ PaError setBestFramesPerBuffer( const AudioDeviceID device,
 
    return paNoError;
 }
-
-/**********************
- *
- * XRun stuff
- *
- **********************/
-
-struct PaMacXRunListNode_s {
-   PaMacCoreStream *stream;
-   struct PaMacXRunListNode_s *next;
-} ;
-
-typedef struct PaMacXRunListNode_s PaMacXRunListNode;
-
-/** Always empty, so that it can always be the one returned by
-    addToXRunListenerList. note that it's not a pointer. */
-static PaMacXRunListNode firstXRunListNode;
-static int xRunListSize;
-static pthread_mutex_t xrunMutex;
-
-OSStatus xrunCallback(
-    AudioDeviceID inDevice, 
-    UInt32 inChannel, 
-    Boolean isInput, 
-    AudioDevicePropertyID inPropertyID, 
-    void* inClientData)
-{
-   PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData;
-
-   int ret = pthread_mutex_trylock( &xrunMutex ) ;
-
-   if( ret == 0 ) {
-
-      node = node->next ; //skip the first node
-
-      for( ; node; node=node->next ) {
-         PaMacCoreStream *stream = node->stream;
-
-         if( stream->state != ACTIVE )
-            continue; //if the stream isn't active, we don't care if the device is dropping
-
-         if( isInput ) {
-            if( stream->inputDevice == inDevice )
-               OSAtomicOr32( paInputOverflow, (uint32_t *)&(stream->xrunFlags) );
-         } else {
-            if( stream->outputDevice == inDevice )
-               OSAtomicOr32( paOutputUnderflow, (uint32_t *)&(stream->xrunFlags) );
-         }
-      }
-
-      pthread_mutex_unlock( &xrunMutex );
-   }
-
-   return 0;
-}
-
-int initializeXRunListenerList()
-{
-   xRunListSize = 0;
-   bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) );
-   return pthread_mutex_init( &xrunMutex, NULL );
-}
-int destroyXRunListenerList()
-{
-   PaMacXRunListNode *node;
-   node = firstXRunListNode.next;
-   while( node ) {
-      PaMacXRunListNode *tmp = node;
-      node = node->next;
-      free( tmp );
-   }
-   xRunListSize = 0;
-   return pthread_mutex_destroy( &xrunMutex );
-}
-
-void *addToXRunListenerList( void *stream )
-{
-   pthread_mutex_lock( &xrunMutex );
-   PaMacXRunListNode *newNode;
-   // setup new node:
-   newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) );
-   newNode->stream = (PaMacCoreStream *) stream;
-   newNode->next = firstXRunListNode.next;
-   // insert:
-   firstXRunListNode.next = newNode;
-   pthread_mutex_unlock( &xrunMutex );
-
-   return &firstXRunListNode;
-}
-
-int removeFromXRunListenerList( void *stream )
-{
-   pthread_mutex_lock( &xrunMutex );
-   PaMacXRunListNode *node, *prev;
-   prev = &firstXRunListNode;
-   node = firstXRunListNode.next;
-   while( node ) {
-      if( node->stream == stream ) {
-         //found it:
-         --xRunListSize;
-         prev->next = node->next;
-         free( node );
-         pthread_mutex_unlock( &xrunMutex );
-         return xRunListSize;
-      }
-      prev = prev->next;
-      node = node->next;
-   }
-
-   pthread_mutex_unlock( &xrunMutex );
-   // failure
-   return xRunListSize;
-}
-
diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h
index 7c4afe52c..8a69c25a6 100644
--- a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h
+++ b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h
@@ -143,6 +143,18 @@ long computeRingBufferSize( const PaStreamParameters *inputParameters,
                                    long outputFramesPerBuffer,
                                    double sampleRate );
 
+/*
+ * Durring testing of core audio, I found that serious crashes could occur
+ * if properties such as sample rate were changed multiple times in rapid
+ * succession. The function below has some fancy logic to make sure that changes
+ * are acknowledged before another is requested. That seems to help a lot.
+ */
+
+typedef struct {
+   bool once; /* I didn't end up using this. bdr */
+   pthread_mutex_t mutex;
+} MutexAndBool ;
+
 OSStatus propertyProc(
     AudioDeviceID inDevice, 
     UInt32 inChannel, 
@@ -187,32 +199,7 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device,
    not usually catastrophic.
 */
 PaError setBestFramesPerBuffer( const AudioDeviceID device,
-                                const bool isOutput,
-                                UInt32 requestedFramesPerBuffer, 
-                                UInt32 *actualFramesPerBuffer );
-
-
-/*********************
- *
- *  xrun handling
- *
- *********************/
-
-OSStatus xrunCallback(
-    AudioDeviceID inDevice, 
-    UInt32 inChannel, 
-    Boolean isInput, 
-    AudioDevicePropertyID inPropertyID, 
-    void* inClientData ) ;
-
-/** returns zero on success or a unix style error code. */
-int initializeXRunListenerList();
-/** returns zero on success or a unix style error code. */
-int destroyXRunListenerList();
-
-/**Returns the list, so that it can be passed to CorAudio.*/
-void *addToXRunListenerList( void *stream );
-/**Returns the number of Listeners in the list remaining.*/
-int removeFromXRunListenerList( void *stream );
-
+                                       const bool isOutput,
+                                       unsigned long requestedFramesPerBuffer, 
+                                       unsigned long *actualFramesPerBuffer );
 #endif /* PA_MAC_CORE_UTILITIES_H__*/
diff --git a/portaudio/src/hostapi/dsound/pa_win_ds.c b/portaudio/src/hostapi/dsound/pa_win_ds.c
deleted file mode 100644
index 913176071..000000000
--- a/portaudio/src/hostapi/dsound/pa_win_ds.c
+++ /dev/null
@@ -1,2864 +0,0 @@
-/*
- * $Id: pa_win_ds.c 1534 2010-08-03 21:02:52Z dmitrykos $
- * Portable Audio I/O Library DirectSound implementation
- *
- * Authors: Phil Burk, Robert Marsanyi & Ross Bencina
- * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2007 Ross Bencina, Phil Burk, Robert Marsanyi
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/** @file
- @ingroup hostapi_src
-
-    @todo implement paInputOverflow callback status flag
-    
-    @todo implement paNeverDropInput.
-
-    @todo implement host api specific extension to set i/o buffer sizes in frames
-
-    @todo implement initialisation of PaDeviceInfo default*Latency fields (currently set to 0.)
-
-    @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable
-
-    @todo audit handling of DirectSound result codes - in many cases we could convert a HRESULT into
-        a native portaudio error code. Standard DirectSound result codes are documented at msdn.
-
-    @todo implement IsFormatSupported
-
-    @todo call PaUtil_SetLastHostErrorInfo with a specific error string (currently just "DSound error").
-
-    @todo make sure all buffers have been played before stopping the stream
-        when the stream callback returns paComplete
-
-    @todo retrieve default devices using the DRVM_MAPPER_PREFERRED_GET functions used in the wmme api
-        these wave device ids can be aligned with the directsound devices either by retrieving
-        the system interface device name using DRV_QUERYDEVICEINTERFACE or by using the wave device
-        id retrieved in KsPropertySetEnumerateCallback.
-
-    old TODOs from phil, need to work out if these have been done:
-        O- fix "patest_stop.c"
-*/
-
-
-#include <assert.h>
-#include <stdio.h>
-#include <string.h> /* strlen() */
-
-#include <initguid.h> /* make sure ds guids get defined */
-#include <windows.h>
-#include <objbase.h>
-
-/*
-  Use the earliest version of DX required, no need to polute the namespace
-*/
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-#define DIRECTSOUND_VERSION 0x0800
-#else
-#define DIRECTSOUND_VERSION 0x0300
-#endif
-#include <dsound.h>
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-#include <dsconf.h>
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-#include "pa_util.h"
-#include "pa_allocation.h"
-#include "pa_hostapi.h"
-#include "pa_stream.h"
-#include "pa_cpuload.h"
-#include "pa_process.h"
-#include "pa_debugprint.h"
-
-#include "pa_win_ds.h"
-#include "pa_win_ds_dynlink.h"
-#include "pa_win_waveformat.h"
-#include "pa_win_wdmks_utils.h"
-
-
-#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
-#pragma comment( lib, "dsound.lib" )
-#pragma comment( lib, "winmm.lib" )
-#endif
-
-/*
- provided in newer platform sdks and x64
- */
-#ifndef DWORD_PTR
-    #if defined(_WIN64)
-        #define DWORD_PTR unsigned __int64
-    #else
-        #define DWORD_PTR unsigned long
-    #endif
-#endif
-
-#define PRINT(x) PA_DEBUG(x);
-#define ERR_RPT(x) PRINT(x)
-#define DBUG(x)   PRINT(x)
-#define DBUGX(x)  PRINT(x)
-
-#define PA_USE_HIGH_LATENCY   (0)
-#if PA_USE_HIGH_LATENCY
-#define PA_WIN_9X_LATENCY     (500)
-#define PA_WIN_NT_LATENCY     (600)
-#else
-#define PA_WIN_9X_LATENCY     (140)
-#define PA_WIN_NT_LATENCY     (280)
-#endif
-
-#define PA_WIN_WDM_LATENCY       (120)
-
-#define SECONDS_PER_MSEC      (0.001)
-#define MSEC_PER_SECOND       (1000)
-
-/* prototypes for functions declared in this file */
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
-static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
-                           PaStream** s,
-                           const PaStreamParameters *inputParameters,
-                           const PaStreamParameters *outputParameters,
-                           double sampleRate,
-                           unsigned long framesPerBuffer,
-                           PaStreamFlags streamFlags,
-                           PaStreamCallback *streamCallback,
-                           void *userData );
-static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
-                                  const PaStreamParameters *inputParameters,
-                                  const PaStreamParameters *outputParameters,
-                                  double sampleRate );
-static PaError CloseStream( PaStream* stream );
-static PaError StartStream( PaStream *stream );
-static PaError StopStream( PaStream *stream );
-static PaError AbortStream( PaStream *stream );
-static PaError IsStreamStopped( PaStream *s );
-static PaError IsStreamActive( PaStream *stream );
-static PaTime GetStreamTime( PaStream *stream );
-static double GetStreamCpuLoad( PaStream* stream );
-static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
-static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
-static signed long GetStreamReadAvailable( PaStream* stream );
-static signed long GetStreamWriteAvailable( PaStream* stream );
-
-
-/* FIXME: should convert hr to a string */
-#define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \
-    PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" )
-
-/************************************************* DX Prototypes **********/
-static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID,
-                                     LPCTSTR lpszDesc,
-                                     LPCTSTR lpszDrvName,
-                                     LPVOID lpContext );
-
-/************************************************************************************/
-/********************** Structures **************************************************/
-/************************************************************************************/
-/* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */
-
-typedef struct PaWinDsDeviceInfo
-{
-    PaDeviceInfo        inheritedDeviceInfo;
-    GUID                guid;
-    GUID                *lpGUID;
-    double              sampleRates[3];
-    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
-    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
-} PaWinDsDeviceInfo;
-
-typedef struct
-{
-    PaUtilHostApiRepresentation inheritedHostApiRep;
-    PaUtilStreamInterface    callbackStreamInterface;
-    PaUtilStreamInterface    blockingStreamInterface;
-
-    PaUtilAllocationGroup   *allocations;
-
-    /* implementation specific data goes here */
-
-    char                    comWasInitialized;
-
-} PaWinDsHostApiRepresentation;
-
-
-/* PaWinDsStream - a stream data structure specifically for this implementation */
-
-typedef struct PaWinDsStream
-{
-    PaUtilStreamRepresentation streamRepresentation;
-    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
-    PaUtilBufferProcessor bufferProcessor;
-
-/* DirectSound specific data. */
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-    LPDIRECTSOUNDFULLDUPLEX8 pDirectSoundFullDuplex8;
-#endif
-
-/* Output */
-    LPDIRECTSOUND        pDirectSound;
-    LPDIRECTSOUNDBUFFER  pDirectSoundPrimaryBuffer;
-    LPDIRECTSOUNDBUFFER  pDirectSoundOutputBuffer;
-    DWORD                outputBufferWriteOffsetBytes;     /* last write position */
-    INT                  outputBufferSizeBytes;
-    INT                  bytesPerOutputFrame;
-    /* Try to detect play buffer underflows. */
-    LARGE_INTEGER        perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */
-    LARGE_INTEGER        previousPlayTime;
-    DWORD                previousPlayCursor;
-    UINT                 outputUnderflowCount;
-    BOOL                 outputIsRunning;
-    INT                  finalZeroBytesWritten; /* used to determine when we've flushed the whole buffer */
-
-/* Input */
-    LPDIRECTSOUNDCAPTURE pDirectSoundCapture;
-    LPDIRECTSOUNDCAPTUREBUFFER   pDirectSoundInputBuffer;
-    INT                  bytesPerInputFrame;
-    UINT                 readOffset;      /* last read position */
-    UINT                 inputSize;
-
-    
-    MMRESULT         timerID;
-    int              framesPerDSBuffer;
-    double           framesWritten;
-    double           secondsPerHostByte; /* Used to optimize latency calculation for outTime */
-
-    PaStreamCallbackFlags callbackFlags;
-
-    PaStreamFlags    streamFlags;
-    int              callbackResult;
-    HANDLE           processingCompleted;
-    
-/* FIXME - move all below to PaUtilStreamRepresentation */
-    volatile int     isStarted;
-    volatile int     isActive;
-    volatile int     stopProcessing; /* stop thread once existing buffers have been returned */
-    volatile int     abortProcessing; /* stop thread immediately */
-} PaWinDsStream;
-
-
-/************************************************************************************
-** Duplicate the input string using the allocations allocator.
-** A NULL string is converted to a zero length string.
-** If memory cannot be allocated, NULL is returned.
-**/
-static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const char* src )
-{
-    char *result = 0;
-    
-    if( src != NULL )
-    {
-        size_t len = strlen(src);
-        result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );
-        if( result )
-            memcpy( (void *) result, src, len+1 );
-    }
-    else
-    {
-        result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 );
-        if( result )
-            result[0] = '\0';
-    }
-
-    return result;
-}
-
-/************************************************************************************
-** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary
-** information during device enumeration.
-*/
-typedef struct DSDeviceNameAndGUID{
-    char *name; // allocated from parent's allocations, never deleted by this structure
-    GUID guid;
-    LPGUID lpGUID;
-    void *pnpInterface;  // wchar_t* interface path, allocated using the DS host api's allocation group
-} DSDeviceNameAndGUID;
-
-typedef struct DSDeviceNameAndGUIDVector{
-    PaUtilAllocationGroup *allocations;
-    PaError enumerationError;
-
-    int count;
-    int free;
-    DSDeviceNameAndGUID *items; // Allocated using LocalAlloc()
-} DSDeviceNameAndGUIDVector;
-
-typedef struct DSDeviceNamesAndGUIDs{
-    PaWinDsHostApiRepresentation *winDsHostApi;
-    DSDeviceNameAndGUIDVector inputNamesAndGUIDs;
-    DSDeviceNameAndGUIDVector outputNamesAndGUIDs;
-} DSDeviceNamesAndGUIDs;
-
-static PaError InitializeDSDeviceNameAndGUIDVector(
-        DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations )
-{
-    PaError result = paNoError;
-
-    guidVector->allocations = allocations;
-    guidVector->enumerationError = paNoError;
-
-    guidVector->count = 0;
-    guidVector->free = 8;
-    guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free );
-    if( guidVector->items == NULL )
-        result = paInsufficientMemory;
-    
-    return result;
-}
-
-static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
-{
-    PaError result = paNoError;
-    DSDeviceNameAndGUID *newItems;
-    int i;
-    
-    /* double size of vector */
-    int size = guidVector->count + guidVector->free;
-    guidVector->free += size;
-
-    newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 );
-    if( newItems == NULL )
-    {
-        result = paInsufficientMemory;
-    }
-    else
-    {
-        for( i=0; i < guidVector->count; ++i )
-        {
-            newItems[i].name = guidVector->items[i].name;
-            if( guidVector->items[i].lpGUID == NULL )
-            {
-                newItems[i].lpGUID = NULL;
-            }
-            else
-            {
-                newItems[i].lpGUID = &newItems[i].guid;
-                memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );;
-            }
-            newItems[i].pnpInterface = guidVector->items[i].pnpInterface;
-        }
-
-        LocalFree( guidVector->items );
-        guidVector->items = newItems;
-    }                                
-
-    return result;
-}
-
-/*
-    it's safe to call DSDeviceNameAndGUIDVector multiple times
-*/
-static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )
-{
-    PaError result = paNoError;
-
-    if( guidVector->items != NULL )
-    {
-        if( LocalFree( guidVector->items ) != NULL )
-            result = paInsufficientMemory;              /** @todo this isn't the correct error to return from a deallocation failure */
-
-        guidVector->items = NULL;
-    }
-
-    return result;
-}
-
-/************************************************************************************
-** Collect preliminary device information during DirectSound enumeration 
-*/
-static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID,
-                                     LPCTSTR lpszDesc,
-                                     LPCTSTR lpszDrvName,
-                                     LPVOID lpContext )
-{
-    DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext;
-    PaError error;
-
-    (void) lpszDrvName; /* unused variable */
-
-    if( namesAndGUIDs->free == 0 )
-    {
-        error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs );
-        if( error != paNoError )
-        {
-            namesAndGUIDs->enumerationError = error;
-            return FALSE;
-        }
-    }
-    
-    /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */
-    if( lpGUID == NULL )
-    {
-        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL;
-    }
-    else
-    {
-        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID =
-                &namesAndGUIDs->items[namesAndGUIDs->count].guid;
-      
-        memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) );
-    }
-
-    namesAndGUIDs->items[namesAndGUIDs->count].name =
-            DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc );
-    if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL )
-    {
-        namesAndGUIDs->enumerationError = paInsufficientMemory;
-        return FALSE;
-    }
-
-    namesAndGUIDs->items[namesAndGUIDs->count].pnpInterface = 0;
-
-    ++namesAndGUIDs->count;
-    --namesAndGUIDs->free;
-    
-    return TRUE;
-}
-
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-
-static void *DuplicateWCharString( PaUtilAllocationGroup *allocations, wchar_t *source )
-{
-    size_t len;
-    wchar_t *result;
-
-    len = wcslen( source );
-    result = (wchar_t*)PaUtil_GroupAllocateMemory( allocations, (long) ((len+1) * sizeof(wchar_t)) );
-    wcscpy( result, source );
-    return result;
-}
-
-static BOOL CALLBACK KsPropertySetEnumerateCallback( PDSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA data, LPVOID context )
-{
-    int i;
-    DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs = (DSDeviceNamesAndGUIDs*)context;
-
-    if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_RENDER )
-    {
-        for( i=0; i < deviceNamesAndGUIDs->outputNamesAndGUIDs.count; ++i )
-        {
-            if( deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID
-                && memcmp( &data->DeviceId, deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )
-            {
-                deviceNamesAndGUIDs->outputNamesAndGUIDs.items[i].pnpInterface = 
-                        (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );
-                break;
-            }
-        }
-    }
-    else if( data->DataFlow == DIRECTSOUNDDEVICE_DATAFLOW_CAPTURE )
-    {
-        for( i=0; i < deviceNamesAndGUIDs->inputNamesAndGUIDs.count; ++i )
-        {
-            if( deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID
-                && memcmp( &data->DeviceId, deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].lpGUID, sizeof(GUID) ) == 0 )
-            {
-                deviceNamesAndGUIDs->inputNamesAndGUIDs.items[i].pnpInterface = 
-                        (char*)DuplicateWCharString( deviceNamesAndGUIDs->winDsHostApi->allocations, data->Interface );
-                break;
-            }
-        }
-    }
-
-    return TRUE;
-}
-
-
-static GUID pawin_CLSID_DirectSoundPrivate = 
-{ 0x11ab3ec0, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };
-
-static GUID pawin_DSPROPSETID_DirectSoundDevice = 
-{ 0x84624f82, 0x25ec, 0x11d1, 0xa4, 0xd8, 0x00, 0xc0, 0x4f, 0xc2, 0x8a, 0xca };
-
-static GUID pawin_IID_IKsPropertySet = 
-{ 0x31efac30, 0x515c, 0x11d0, 0xa9, 0xaa, 0x00, 0xaa, 0x00, 0x61, 0xbe, 0x93 };
-
-
-/*
-    FindDevicePnpInterfaces fills in the pnpInterface fields in deviceNamesAndGUIDs
-    with UNICODE file paths to the devices. The DS documentation mentions
-    at least two techniques by which these Interface paths can be found using IKsPropertySet on
-    the DirectSound class object. One is using the DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION 
-    property, and the other is using DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE.
-    I tried both methods and only the second worked. I found two postings on the
-    net from people who had the same problem with the first method, so I think the method used here is 
-    more common/likely to work. The probem is that IKsPropertySet_Get returns S_OK
-    but the fields of the device description are not filled in.
-
-    The mechanism we use works by registering an enumeration callback which is called for 
-    every DSound device. Our callback searches for a device in our deviceNamesAndGUIDs list
-    with the matching GUID and copies the pointer to the Interface path.
-    Note that we could have used this enumeration callback to perform the original 
-    device enumeration, however we choose not to so we can disable this step easily.
-
-    Apparently the IKsPropertySet mechanism was added in DirectSound 9c 2004
-    http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2004-12/0099.html
-
-        -- rossb
-*/
-static void FindDevicePnpInterfaces( DSDeviceNamesAndGUIDs *deviceNamesAndGUIDs )
-{
-    IClassFactory *pClassFactory;
-   
-    if( paWinDsDSoundEntryPoints.DllGetClassObject(&pawin_CLSID_DirectSoundPrivate, &IID_IClassFactory, (PVOID *) &pClassFactory) == S_OK ){
-        IKsPropertySet *pPropertySet;
-        if( pClassFactory->lpVtbl->CreateInstance( pClassFactory, NULL, &pawin_IID_IKsPropertySet, (PVOID *) &pPropertySet) == S_OK ){
-            
-            DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W_DATA data;
-            ULONG bytesReturned;
-
-            data.Callback = KsPropertySetEnumerateCallback;
-            data.Context = deviceNamesAndGUIDs;
-
-            IKsPropertySet_Get( pPropertySet,
-                &pawin_DSPROPSETID_DirectSoundDevice,
-                DSPROPERTY_DIRECTSOUNDDEVICE_ENUMERATE_W,
-                NULL,
-                0,
-                &data,
-                sizeof(data),
-                &bytesReturned
-            );
-            
-            IKsPropertySet_Release( pPropertySet );
-        }
-        pClassFactory->lpVtbl->Release( pClassFactory );
-    }
-
-    /*
-        The following code fragment, which I chose not to use, queries for the 
-        device interface for a device with a specific GUID:
-
-        ULONG BytesReturned;
-        DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W_DATA Property;
-
-        memset (&Property, 0, sizeof(Property));
-        Property.DataFlow = DIRECTSOUNDDEVICE_DATAFLOW_RENDER;
-        Property.DeviceId = *lpGUID;  
-
-        hr = IKsPropertySet_Get( pPropertySet,
-            &pawin_DSPROPSETID_DirectSoundDevice,
-            DSPROPERTY_DIRECTSOUNDDEVICE_DESCRIPTION_W,
-            NULL,
-            0,
-            &Property,
-            sizeof(Property),
-            &BytesReturned
-        );
-
-        if( hr == S_OK )
-        {
-            //pnpInterface = Property.Interface;
-        }
-    */
-}
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-
-/* 
-    GUIDs for emulated devices which we blacklist below.
-    are there more than two of them??
-*/
-
-GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01};
-GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02};
-
-
-#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */
-static double defaultSampleRateSearchOrder_[] =
-    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
-        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
-
-/************************************************************************************
-** Extract capabilities from an output device, and add it to the device info list
-** if successful. This function assumes that there is enough room in the
-** device info list to accomodate all entries.
-**
-** The device will not be added to the device list if any errors are encountered.
-*/
-static PaError AddOutputDeviceInfoFromDirectSound(
-        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )
-{
-    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;
-    PaWinDsDeviceInfo            *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];
-    PaDeviceInfo                 *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;
-    HRESULT                       hr;
-    LPDIRECTSOUND                 lpDirectSound;
-    DSCAPS                        caps;
-    int                           deviceOK = TRUE;
-    PaError                       result = paNoError;
-    int                           i;
-
-    /* Copy GUID to the device info structure. Set pointer. */
-    if( lpGUID == NULL )
-    {
-        winDsDeviceInfo->lpGUID = NULL;
-    }
-    else
-    {
-        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
-        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
-    }
-    
-    if( lpGUID )
-    {
-        if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) ||
-            IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) )
-        {
-            PA_DEBUG(("BLACKLISTED: %s \n",name));
-            return paNoError;
-        }
-    }
-
-    /* Create a DirectSound object for the specified GUID
-        Note that using CoCreateInstance doesn't work on windows CE.
-    */
-    hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL );
-
-    /** try using CoCreateInstance because DirectSoundCreate was hanging under
-        some circumstances - note this was probably related to the
-        #define BOOL short bug which has now been fixed
-        @todo delete this comment and the following code once we've ensured
-        there is no bug.
-    */
-    /*
-    hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER,
-            &IID_IDirectSound, (void**)&lpDirectSound );
-
-    if( hr == S_OK )
-    {
-        hr = IDirectSound_Initialize( lpDirectSound, lpGUID );
-    }
-    */
-    
-    if( hr != DS_OK )
-    {
-        if (hr == DSERR_ALLOCATED)
-            PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name));
-        DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr ));
-        if (lpGUID)
-            DBUG(("%s's GUID: {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, 0x%x} \n",
-                 name,
-                 lpGUID->Data1,
-                 lpGUID->Data2,
-                 lpGUID->Data3,
-                 lpGUID->Data4[0],
-                 lpGUID->Data4[1],
-                 lpGUID->Data4[2],
-                 lpGUID->Data4[3],
-                 lpGUID->Data4[4],
-                 lpGUID->Data4[5],
-                 lpGUID->Data4[6],
-                 lpGUID->Data4[7]));
-
-        deviceOK = FALSE;
-    }
-    else
-    {
-        /* Query device characteristics. */
-        memset( &caps, 0, sizeof(caps) ); 
-        caps.dwSize = sizeof(caps);
-        hr = IDirectSound_GetCaps( lpDirectSound, &caps );
-        if( hr != DS_OK )
-        {
-            DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr ));
-            deviceOK = FALSE;
-        }
-        else
-        {
-
-#ifndef PA_NO_WMME
-            if( caps.dwFlags & DSCAPS_EMULDRIVER )
-            {
-                /* If WMME supported, then reject Emulated drivers because they are lousy. */
-                deviceOK = FALSE;
-            }
-#endif
-
-            if( deviceOK )
-            {
-                deviceInfo->maxInputChannels = 0;
-                winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
-
-                /* DS output capabilities only indicate supported number of channels
-                   using two flags which indicate mono and/or stereo.
-                   We assume that stereo devices may support more than 2 channels
-                   (as is the case with 5.1 devices for example) and so
-                   set deviceOutputChannelCountIsKnown to 0 (unknown).
-                   In this case OpenStream will try to open the device
-                   when the user requests more than 2 channels, rather than
-                   returning an error. 
-                */
-                if( caps.dwFlags & DSCAPS_PRIMARYSTEREO )
-                {
-                    deviceInfo->maxOutputChannels = 2;
-                    winDsDeviceInfo->deviceOutputChannelCountIsKnown = 0;
-                }
-                else
-                {
-                    deviceInfo->maxOutputChannels = 1;
-                    winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
-                }
-
-                /* Guess channels count from speaker configuration. We do it only when 
-                   pnpInterface is NULL or when PAWIN_USE_WDMKS_DEVICE_INFO is undefined.
-                */
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-                if( !pnpInterface )
-#endif
-                {
-                    DWORD spkrcfg;
-                    if( SUCCEEDED(IDirectSound_GetSpeakerConfig( lpDirectSound, &spkrcfg )) )
-                    {
-                        int count = 0;
-                        switch (DSSPEAKER_CONFIG(spkrcfg))
-                        {
-                            case DSSPEAKER_HEADPHONE:        count = 2; break;
-                            case DSSPEAKER_MONO:             count = 1; break;
-                            case DSSPEAKER_QUAD:             count = 4; break;
-                            case DSSPEAKER_STEREO:           count = 2; break;
-                            case DSSPEAKER_SURROUND:         count = 4; break;
-                            case DSSPEAKER_5POINT1:          count = 6; break;
-                            case DSSPEAKER_7POINT1:          count = 8; break;
-#ifndef DSSPEAKER_7POINT1_SURROUND
-#define DSSPEAKER_7POINT1_SURROUND 0x00000008
-#endif                            
-                            case DSSPEAKER_7POINT1_SURROUND: count = 8; break;
-#ifndef DSSPEAKER_5POINT1_SURROUND
-#define DSSPEAKER_5POINT1_SURROUND 0x00000009
-#endif
-                            case DSSPEAKER_5POINT1_SURROUND: count = 6; break;
-                        }
-                        if( count )
-                        {
-                            deviceInfo->maxOutputChannels = count;
-                            winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
-                        }
-                    }
-                }
-
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-                if( pnpInterface )
-                {
-                    int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 0  );
-                    if( count > 0 )
-                    {
-                        deviceInfo->maxOutputChannels = count;
-                        winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
-                    }
-                }
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-                deviceInfo->defaultLowInputLatency = 0.;    /** @todo IMPLEMENT ME */
-                deviceInfo->defaultLowOutputLatency = 0.;   /** @todo IMPLEMENT ME */
-                deviceInfo->defaultHighInputLatency = 0.;   /** @todo IMPLEMENT ME */
-                deviceInfo->defaultHighOutputLatency = 0.;  /** @todo IMPLEMENT ME */
-                
-                /* initialize defaultSampleRate */
-                
-                if( caps.dwFlags & DSCAPS_CONTINUOUSRATE )
-                {
-                    /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */
-                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
-
-                    for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
-                    {
-                        if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate
-                                && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate )
-                        {
-                            deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i];
-                            break;
-                        }
-                    }
-                }
-                else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )
-                {
-                    if( caps.dwMinSecondarySampleRate == 0 )
-                    {
-                        /*
-                        ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!
-                        ** But it supports continuous sampling.
-                        ** So fake range of rates, and hope it really supports it.
-                        */
-                        deviceInfo->defaultSampleRate = 44100.0f;
-
-                        DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name ));
-                    }
-                    else
-                    {
-	                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
-                    }
-                }
-                else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )
-                {
-                    /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.
-                    ** But we know that they really support a range of rates!
-                    ** So when we see a ridiculous set of rates, assume it is a range.
-                    */
-                  deviceInfo->defaultSampleRate = 44100.0f;
-                  DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name ));
-                }
-                else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;
-
-
-                //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate );
-                // dwFlags | DSCAPS_CONTINUOUSRATE 
-            }
-        }
-
-        IDirectSound_Release( lpDirectSound );
-    }
-
-    if( deviceOK )
-    {
-        deviceInfo->name = name;
-
-        if( lpGUID == NULL )
-            hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;
-            
-        hostApi->info.deviceCount++;
-    }
-
-    return result;
-}
-
-
-/************************************************************************************
-** Extract capabilities from an input device, and add it to the device info list
-** if successful. This function assumes that there is enough room in the
-** device info list to accomodate all entries.
-**
-** The device will not be added to the device list if any errors are encountered.
-*/
-static PaError AddInputDeviceInfoFromDirectSoundCapture(
-        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID, char *pnpInterface )
-{
-    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;
-    PaWinDsDeviceInfo            *winDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[hostApi->info.deviceCount];
-    PaDeviceInfo                 *deviceInfo = &winDsDeviceInfo->inheritedDeviceInfo;
-    HRESULT                       hr;
-    LPDIRECTSOUNDCAPTURE          lpDirectSoundCapture;
-    DSCCAPS                       caps;
-    int                           deviceOK = TRUE;
-    PaError                       result = paNoError;
-    
-    /* Copy GUID to the device info structure. Set pointer. */
-    if( lpGUID == NULL )
-    {
-        winDsDeviceInfo->lpGUID = NULL;
-    }
-    else
-    {
-        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;
-        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );
-    }
-
-    hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL );
-
-    /** try using CoCreateInstance because DirectSoundCreate was hanging under
-        some circumstances - note this was probably related to the
-        #define BOOL short bug which has now been fixed
-        @todo delete this comment and the following code once we've ensured
-        there is no bug.
-    */
-    /*
-    hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER,
-            &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture );
-    */
-    if( hr != DS_OK )
-    {
-        DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr ));
-        deviceOK = FALSE;
-    }
-    else
-    {
-        /* Query device characteristics. */
-        memset( &caps, 0, sizeof(caps) );
-        caps.dwSize = sizeof(caps);
-        hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );
-        if( hr != DS_OK )
-        {
-            DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr ));
-            deviceOK = FALSE;
-        }
-        else
-        {
-#ifndef PA_NO_WMME
-            if( caps.dwFlags & DSCAPS_EMULDRIVER )
-            {
-                /* If WMME supported, then reject Emulated drivers because they are lousy. */
-                deviceOK = FALSE;
-            }
-#endif
-
-            if( deviceOK )
-            {
-                deviceInfo->maxInputChannels = caps.dwChannels;
-                winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
-
-                deviceInfo->maxOutputChannels = 0;
-                winDsDeviceInfo->deviceOutputChannelCountIsKnown = 1;
-
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-                if( pnpInterface )
-                {
-                    int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( pnpInterface, /* isInput= */ 1  );
-                    if( count > 0 )
-                    {
-                        deviceInfo->maxInputChannels = count;
-                        winDsDeviceInfo->deviceInputChannelCountIsKnown = 1;
-                    }
-                }
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-                deviceInfo->defaultLowInputLatency = 0.;    /** @todo IMPLEMENT ME */
-                deviceInfo->defaultLowOutputLatency = 0.;   /** @todo IMPLEMENT ME */
-                deviceInfo->defaultHighInputLatency = 0.;   /** @todo IMPLEMENT ME */
-                deviceInfo->defaultHighOutputLatency = 0.;  /** @todo IMPLEMENT ME */
-
-/*  constants from a WINE patch by Francois Gouget, see:
-    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
-
-    ---
-    Date: Fri, 14 May 2004 10:38:12 +0200 (CEST)
-    From: Francois Gouget <fgouget@ ... .fr>
-    To: Ross Bencina <rbencina@ ... .au>
-    Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library
-
-    [snip]
-
-    I give you permission to use the patch below under the BSD license.
-    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html
-
-    [snip]
-*/
-#ifndef WAVE_FORMAT_48M08
-#define WAVE_FORMAT_48M08      0x00001000    /* 48     kHz, Mono,   8-bit  */
-#define WAVE_FORMAT_48S08      0x00002000    /* 48     kHz, Stereo, 8-bit  */
-#define WAVE_FORMAT_48M16      0x00004000    /* 48     kHz, Mono,   16-bit */
-#define WAVE_FORMAT_48S16      0x00008000    /* 48     kHz, Stereo, 16-bit */
-#define WAVE_FORMAT_96M08      0x00010000    /* 96     kHz, Mono,   8-bit  */
-#define WAVE_FORMAT_96S08      0x00020000    /* 96     kHz, Stereo, 8-bit  */
-#define WAVE_FORMAT_96M16      0x00040000    /* 96     kHz, Mono,   16-bit */
-#define WAVE_FORMAT_96S16      0x00080000    /* 96     kHz, Stereo, 16-bit */
-#endif
-
-                /* defaultSampleRate */
-                if( caps.dwChannels == 2 )
-                {
-                    if( caps.dwFormats & WAVE_FORMAT_4S16 )
-                        deviceInfo->defaultSampleRate = 44100.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_48S16 )
-                        deviceInfo->defaultSampleRate = 48000.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_2S16 )
-                        deviceInfo->defaultSampleRate = 22050.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_1S16 )
-                        deviceInfo->defaultSampleRate = 11025.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_96S16 )
-                        deviceInfo->defaultSampleRate = 96000.0;
-                    else
-                        deviceInfo->defaultSampleRate = 0.;
-                }
-                else if( caps.dwChannels == 1 )
-                {
-                    if( caps.dwFormats & WAVE_FORMAT_4M16 )
-                        deviceInfo->defaultSampleRate = 44100.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_48M16 )
-                        deviceInfo->defaultSampleRate = 48000.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_2M16 )
-                        deviceInfo->defaultSampleRate = 22050.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_1M16 )
-                        deviceInfo->defaultSampleRate = 11025.0;
-                    else if( caps.dwFormats & WAVE_FORMAT_96M16 )
-                        deviceInfo->defaultSampleRate = 96000.0;
-                    else
-                        deviceInfo->defaultSampleRate = 0.;
-                }
-                else deviceInfo->defaultSampleRate = 0.;
-            }
-        }
-        
-        IDirectSoundCapture_Release( lpDirectSoundCapture );
-    }
-
-    if( deviceOK )
-    {
-        deviceInfo->name = name;
-
-        if( lpGUID == NULL )
-            hostApi->info.defaultInputDevice = hostApi->info.deviceCount;
-
-        hostApi->info.deviceCount++;
-    }
-
-    return result;
-}
-
-
-/***********************************************************************************/
-PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
-{
-    PaError result = paNoError;
-    int i, deviceCount;
-    PaWinDsHostApiRepresentation *winDsHostApi;
-    DSDeviceNamesAndGUIDs deviceNamesAndGUIDs;
-
-    PaWinDsDeviceInfo *deviceInfoArray;
-    char comWasInitialized = 0;
-
-    /*
-        If COM is already initialized CoInitialize will either return
-        FALSE, or RPC_E_CHANGED_MODE if it was initialised in a different
-        threading mode. In either case we shouldn't consider it an error
-        but we need to be careful to not call CoUninitialize() if 
-        RPC_E_CHANGED_MODE was returned.
-    */
-
-    HRESULT hr = CoInitialize(NULL);
-    if( FAILED(hr) && hr != RPC_E_CHANGED_MODE )
-        return paUnanticipatedHostError;
-
-    if( hr != RPC_E_CHANGED_MODE )
-        comWasInitialized = 1;
-
-    /* initialise guid vectors so they can be safely deleted on error */
-    deviceNamesAndGUIDs.winDsHostApi = NULL;
-    deviceNamesAndGUIDs.inputNamesAndGUIDs.items = NULL;
-    deviceNamesAndGUIDs.outputNamesAndGUIDs.items = NULL;
-
-    PaWinDs_InitializeDSoundEntryPoints();
-
-    winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) );
-    if( !winDsHostApi )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    winDsHostApi->comWasInitialized = comWasInitialized;
-
-    winDsHostApi->allocations = PaUtil_CreateAllocationGroup();
-    if( !winDsHostApi->allocations )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    *hostApi = &winDsHostApi->inheritedHostApiRep;
-    (*hostApi)->info.structVersion = 1;
-    (*hostApi)->info.type = paDirectSound;
-    (*hostApi)->info.name = "Windows DirectSound";
-    
-    (*hostApi)->info.deviceCount = 0;
-    (*hostApi)->info.defaultInputDevice = paNoDevice;
-    (*hostApi)->info.defaultOutputDevice = paNoDevice;
-
-    
-/* DSound - enumerate devices to count them and to gather their GUIDs */
-
-    result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs, winDsHostApi->allocations );
-    if( result != paNoError )
-        goto error;
-
-    result = InitializeDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs, winDsHostApi->allocations );
-    if( result != paNoError )
-        goto error;
-
-    paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&deviceNamesAndGUIDs.inputNamesAndGUIDs );
-
-    paWinDsDSoundEntryPoints.DirectSoundEnumerateA( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&deviceNamesAndGUIDs.outputNamesAndGUIDs );
-
-    if( deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError != paNoError )
-    {
-        result = deviceNamesAndGUIDs.inputNamesAndGUIDs.enumerationError;
-        goto error;
-    }
-
-    if( deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError != paNoError )
-    {
-        result = deviceNamesAndGUIDs.outputNamesAndGUIDs.enumerationError;
-        goto error;
-    }
-
-    deviceCount = deviceNamesAndGUIDs.inputNamesAndGUIDs.count + deviceNamesAndGUIDs.outputNamesAndGUIDs.count;
-
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-    if( deviceCount > 0 )
-    {
-        deviceNamesAndGUIDs.winDsHostApi = winDsHostApi;
-        FindDevicePnpInterfaces( &deviceNamesAndGUIDs );
-    }
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-    if( deviceCount > 0 )
-    {
-        /* allocate array for pointers to PaDeviceInfo structs */
-        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
-                winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );
-        if( !(*hostApi)->deviceInfos )
-        {
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-        /* allocate all PaDeviceInfo structs in a contiguous block */
-        deviceInfoArray = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory(
-                winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount );
-        if( !deviceInfoArray )
-        {
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-        for( i=0; i < deviceCount; ++i )
-        {
-            PaDeviceInfo *deviceInfo = &deviceInfoArray[i].inheritedDeviceInfo;
-            deviceInfo->structVersion = 2;
-            deviceInfo->hostApi = hostApiIndex;
-            deviceInfo->name = 0;
-            (*hostApi)->deviceInfos[i] = deviceInfo;
-        }
-
-        for( i=0; i < deviceNamesAndGUIDs.inputNamesAndGUIDs.count; ++i )
-        {
-            result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi,
-                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].name,
-                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].lpGUID,
-                    deviceNamesAndGUIDs.inputNamesAndGUIDs.items[i].pnpInterface );
-            if( result != paNoError )
-                goto error;
-        }
-
-        for( i=0; i < deviceNamesAndGUIDs.outputNamesAndGUIDs.count; ++i )
-        {
-            result = AddOutputDeviceInfoFromDirectSound( winDsHostApi,
-                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].name,
-                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].lpGUID,
-                    deviceNamesAndGUIDs.outputNamesAndGUIDs.items[i].pnpInterface );
-            if( result != paNoError )
-                goto error;
-        }
-    }    
-
-    result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );
-    if( result != paNoError )
-        goto error;
-
-    result = TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );
-    if( result != paNoError )
-        goto error;
-
-    
-    (*hostApi)->Terminate = Terminate;
-    (*hostApi)->OpenStream = OpenStream;
-    (*hostApi)->IsFormatSupported = IsFormatSupported;
-
-    PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream,
-                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
-                                      GetStreamTime, GetStreamCpuLoad,
-                                      PaUtil_DummyRead, PaUtil_DummyWrite,
-                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
-
-    PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream,
-                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
-                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
-                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
-
-    return result;
-
-error:
-    if( winDsHostApi )
-    {
-        if( winDsHostApi->allocations )
-        {
-            PaUtil_FreeAllAllocations( winDsHostApi->allocations );
-            PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );
-        }
-                
-        PaUtil_FreeMemory( winDsHostApi );
-    }
-
-    TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.inputNamesAndGUIDs );
-    TerminateDSDeviceNameAndGUIDVector( &deviceNamesAndGUIDs.outputNamesAndGUIDs );
-
-    if( comWasInitialized )
-        CoUninitialize();
-
-    return result;
-}
-
-
-/***********************************************************************************/
-static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
-{
-    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
-    char comWasInitialized = winDsHostApi->comWasInitialized;
-
-    /*
-        IMPLEMENT ME:
-            - clean up any resources not handled by the allocation group
-    */
-
-    if( winDsHostApi->allocations )
-    {
-        PaUtil_FreeAllAllocations( winDsHostApi->allocations );
-        PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );
-    }
-
-    PaUtil_FreeMemory( winDsHostApi );
-
-    PaWinDs_TerminateDSoundEntryPoints();
-
-    if( comWasInitialized )
-        CoUninitialize();
-}
-
-
-/* Set minimal latency based on whether NT or Win95.
- * NT has higher latency.
- */
-static int PaWinDS_GetMinSystemLatency( void )
-{
-    int minLatencyMsec;
-    /* Set minimal latency based on whether NT or other OS.
-     * NT has higher latency.
-     */
-    OSVERSIONINFO osvi;
-	osvi.dwOSVersionInfoSize = sizeof( osvi );
-	GetVersionEx( &osvi );
-    DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId ));
-    DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion ));
-    DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion ));
-    /* Check for NT */
-	if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
-	{
-		minLatencyMsec = PA_WIN_NT_LATENCY;
-	}
-	else if(osvi.dwMajorVersion >= 5)
-	{
-		minLatencyMsec = PA_WIN_WDM_LATENCY;
-	}
-	else
-	{
-		minLatencyMsec = PA_WIN_9X_LATENCY;
-	}
-    return minLatencyMsec;
-}
-
-static PaError ValidateWinDirectSoundSpecificStreamInfo(
-        const PaStreamParameters *streamParameters,
-        const PaWinDirectSoundStreamInfo *streamInfo )
-{
-	if( streamInfo )
-	{
-	    if( streamInfo->size != sizeof( PaWinDirectSoundStreamInfo )
-	            || streamInfo->version != 1 )
-	    {
-	        return paIncompatibleHostApiSpecificStreamInfo;
-	    }
-	}
-
-	return paNoError;
-}
-
-/***********************************************************************************/
-static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
-                                  const PaStreamParameters *inputParameters,
-                                  const PaStreamParameters *outputParameters,
-                                  double sampleRate )
-{
-    PaError result;
-    PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;
-    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
-    int inputChannelCount, outputChannelCount;
-    PaSampleFormat inputSampleFormat, outputSampleFormat;
-    PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;
-
-    if( inputParameters )
-    {
-        inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];
-        inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;
-
-        inputChannelCount = inputParameters->channelCount;
-        inputSampleFormat = inputParameters->sampleFormat;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-
-        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that input device can support inputChannelCount */
-        if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown
-                && inputChannelCount > inputDeviceInfo->maxInputChannels )
-            return paInvalidChannelCount;
-
-        /* validate inputStreamInfo */
-        inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
-		result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );
-		if( result != paNoError ) return result;
-    }
-    else
-    {
-        inputChannelCount = 0;
-    }
-
-    if( outputParameters )
-    {
-        outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];
-        outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;
-
-        outputChannelCount = outputParameters->channelCount;
-        outputSampleFormat = outputParameters->sampleFormat;
-        
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-
-        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that output device can support inputChannelCount */
-        if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown
-                && outputChannelCount > outputDeviceInfo->maxOutputChannels )
-            return paInvalidChannelCount;
-
-        /* validate outputStreamInfo */
-        outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
-		result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );
-		if( result != paNoError ) return result;
-    }
-    else
-    {
-        outputChannelCount = 0;
-    }
-    
-    /*
-        IMPLEMENT ME:
-
-            - if a full duplex stream is requested, check that the combination
-                of input and output parameters is supported if necessary
-
-            - check that the device supports sampleRate
-
-        Because the buffer adapter handles conversion between all standard
-        sample formats, the following checks are only required if paCustomFormat
-        is implemented, or under some other unusual conditions.
-
-            - check that input device can support inputSampleFormat, or that
-                we have the capability to convert from outputSampleFormat to
-                a native format
-
-            - check that output device can support outputSampleFormat, or that
-                we have the capability to convert from outputSampleFormat to
-                a native format
-    */
-
-    return paFormatIsSupported;
-}
-
-
-/*************************************************************************
-** Determine minimum number of buffers required for this host based
-** on minimum latency. Latency can be optionally set by user by setting
-** an environment variable. For example, to set latency to 200 msec, put:
-**
-**    set PA_MIN_LATENCY_MSEC=200
-**
-** in the AUTOEXEC.BAT file and reboot.
-** If the environment variable is not set, then the latency will be determined
-** based on the OS. Windows NT has higher latency than Win95.
-*/
-#define PA_LATENCY_ENV_NAME  ("PA_MIN_LATENCY_MSEC")
-#define PA_ENV_BUF_SIZE  (32)
-
-static int PaWinDs_GetMinLatencyFrames( double sampleRate )
-{
-    char      envbuf[PA_ENV_BUF_SIZE];
-    DWORD     hresult;
-    int       minLatencyMsec = 0;
-
-    /* Let user determine minimal latency by setting environment variable. */
-    hresult = GetEnvironmentVariable( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE );
-    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) )
-    {
-        minLatencyMsec = atoi( envbuf );
-    }
-    else
-    {
-        minLatencyMsec = PaWinDS_GetMinSystemLatency();
-#if PA_USE_HIGH_LATENCY
-        PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec ));
-#endif
-
-    }
-
-    return (int) (minLatencyMsec * sampleRate * SECONDS_PER_MSEC);
-}
-
-
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-static HRESULT InitFullDuplexInputOutputBuffers( PaWinDsStream *stream,
-                                       PaWinDsDeviceInfo *inputDevice,
-                                       PaSampleFormat hostInputSampleFormat,
-                                       WORD inputChannelCount, 
-                                       int bytesPerInputBuffer,
-                                       PaWinWaveFormatChannelMask inputChannelMask,
-                                       PaWinDsDeviceInfo *outputDevice,
-                                       PaSampleFormat hostOutputSampleFormat,
-                                       WORD outputChannelCount, 
-                                       int bytesPerOutputBuffer,
-                                       PaWinWaveFormatChannelMask outputChannelMask,
-                                       unsigned long nFrameRate
-                                        )
-{
-    HRESULT hr;
-    DSCBUFFERDESC  captureDesc;
-    PaWinWaveFormat captureWaveFormat;
-    DSBUFFERDESC   secondaryRenderDesc;
-    PaWinWaveFormat renderWaveFormat;
-    LPDIRECTSOUNDBUFFER8 pRenderBuffer8;
-    LPDIRECTSOUNDCAPTUREBUFFER8 pCaptureBuffer8;
-
-    // capture buffer description
-
-    // only try wave format extensible. assume it's available on all ds 8 systems
-    PaWin_InitializeWaveFormatExtensible( &captureWaveFormat, inputChannelCount, 
-                hostInputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostInputSampleFormat ),
-                nFrameRate, inputChannelMask );
-
-    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
-    captureDesc.dwSize = sizeof(DSCBUFFERDESC);
-    captureDesc.dwFlags = 0;
-    captureDesc.dwBufferBytes = bytesPerInputBuffer;
-    captureDesc.lpwfxFormat = (WAVEFORMATEX*)&captureWaveFormat;
-
-    // render buffer description
-
-    PaWin_InitializeWaveFormatExtensible( &renderWaveFormat, outputChannelCount, 
-                hostOutputSampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( hostOutputSampleFormat ),
-                nFrameRate, outputChannelMask );
-
-    ZeroMemory(&secondaryRenderDesc, sizeof(DSBUFFERDESC));
-    secondaryRenderDesc.dwSize = sizeof(DSBUFFERDESC);
-    secondaryRenderDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
-    secondaryRenderDesc.dwBufferBytes = bytesPerOutputBuffer;
-    secondaryRenderDesc.lpwfxFormat = (WAVEFORMATEX*)&renderWaveFormat;
-
-    /* note that we don't create a primary buffer here at all */
-
-    hr = paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8( 
-            inputDevice->lpGUID, outputDevice->lpGUID,
-            &captureDesc, &secondaryRenderDesc,
-            GetDesktopWindow(), /* see InitOutputBuffer() for a discussion of whether this is a good idea */
-            DSSCL_EXCLUSIVE,
-            &stream->pDirectSoundFullDuplex8,
-            &pCaptureBuffer8,
-            &pRenderBuffer8,
-            NULL /* pUnkOuter must be NULL */ 
-        );
-
-    if( hr == DS_OK )
-    {
-        PA_DEBUG(("DirectSoundFullDuplexCreate succeeded!\n"));
-
-        /* retrieve the pre ds 8 buffer interfaces which are used by the rest of the code */
-
-        hr = IUnknown_QueryInterface( pCaptureBuffer8, &IID_IDirectSoundCaptureBuffer, (LPVOID *)&stream->pDirectSoundInputBuffer );
-        
-        if( hr == DS_OK )
-            hr = IUnknown_QueryInterface( pRenderBuffer8, &IID_IDirectSoundBuffer, (LPVOID *)&stream->pDirectSoundOutputBuffer );
-
-        /* release the ds 8 interfaces, we don't need them */
-        IUnknown_Release( pCaptureBuffer8 );
-        IUnknown_Release( pRenderBuffer8 );
-
-        if( !stream->pDirectSoundInputBuffer || !stream->pDirectSoundOutputBuffer ){
-            /* couldn't get pre ds 8 interfaces for some reason. clean up. */
-            if( stream->pDirectSoundInputBuffer )
-            {
-                IUnknown_Release( stream->pDirectSoundInputBuffer );
-                stream->pDirectSoundInputBuffer = NULL;
-            }
-
-            if( stream->pDirectSoundOutputBuffer )
-            {
-                IUnknown_Release( stream->pDirectSoundOutputBuffer );
-                stream->pDirectSoundOutputBuffer = NULL;
-            }
-            
-            IUnknown_Release( stream->pDirectSoundFullDuplex8 );
-            stream->pDirectSoundFullDuplex8 = NULL;
-        }
-    }
-    else
-    {
-        PA_DEBUG(("DirectSoundFullDuplexCreate failed. hr=%d\n", hr));
-    }
-
-    return hr;
-}
-#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
-
-
-static HRESULT InitInputBuffer( PaWinDsStream *stream, PaWinDsDeviceInfo *device, PaSampleFormat sampleFormat, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer, PaWinWaveFormatChannelMask channelMask )
-{
-    DSCBUFFERDESC  captureDesc;
-    PaWinWaveFormat waveFormat;
-    HRESULT        result;
-    
-    if( (result = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( 
-            device->lpGUID, &stream->pDirectSoundCapture, NULL) ) != DS_OK ){
-         ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));
-         return result;
-    }
-
-    // Setup the secondary buffer description
-    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));
-    captureDesc.dwSize = sizeof(DSCBUFFERDESC);
-    captureDesc.dwFlags = 0;
-    captureDesc.dwBufferBytes = bytesPerBuffer;
-    captureDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat;
-    
-    // Create the capture buffer
-
-    // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX
-    PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, 
-                sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),
-                nFrameRate, channelMask );
-
-    if( IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
-                  &captureDesc, &stream->pDirectSoundInputBuffer, NULL) != DS_OK )
-    {
-        PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, 
-                PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );
-
-        if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,
-                    &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result;
-    }
-
-    stream->readOffset = 0;  // reset last read position to start of buffer
-    return DS_OK;
-}
-
-
-static HRESULT InitOutputBuffer( PaWinDsStream *stream, PaWinDsDeviceInfo *device, PaSampleFormat sampleFormat, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer, PaWinWaveFormatChannelMask channelMask )
-{
-    HRESULT        result;
-    HWND           hWnd;
-    HRESULT        hr;
-    PaWinWaveFormat waveFormat;
-    DSBUFFERDESC   primaryDesc;
-    DSBUFFERDESC   secondaryDesc;
-    
-    if( (hr = paWinDsDSoundEntryPoints.DirectSoundCreate( 
-                device->lpGUID, &stream->pDirectSound, NULL )) != DS_OK ){
-        ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));
-        return hr;
-    }
-
-    // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the
-    // applications's window. Also if that window is closed before the Buffer is closed
-    // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.)
-    // So we will use GetDesktopWindow() which was suggested by Miller Puckette.
-    // hWnd = GetForegroundWindow();
-    //
-    //  FIXME: The example code I have on the net creates a hidden window that
-    //      is managed by our code - I think we should do that - one hidden
-    //      window for the whole of Pa_DS
-    //
-    hWnd = GetDesktopWindow();
-
-    // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz.
-    // exclusive also prevents unexpected sounds from other apps during a performance.
-    if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound,
-              hWnd, DSSCL_EXCLUSIVE)) != DS_OK)
-    {
-        return hr;
-    }
-
-    // -----------------------------------------------------------------------
-    // Create primary buffer and set format just so we can specify our custom format.
-    // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz.
-    // Setup the primary buffer description
-    ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC));
-    primaryDesc.dwSize        = sizeof(DSBUFFERDESC);
-    primaryDesc.dwFlags       = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth
-    primaryDesc.dwBufferBytes = 0;
-    primaryDesc.lpwfxFormat   = NULL;
-    // Create the buffer
-    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
-                  &primaryDesc, &stream->pDirectSoundPrimaryBuffer, NULL)) != DS_OK)
-        goto error;
-
-    // Set the primary buffer's format
-
-    // first try WAVEFORMATEXTENSIBLE. if this fails, fall back to WAVEFORMATEX
-    PaWin_InitializeWaveFormatExtensible( &waveFormat, nChannels, 
-                sampleFormat, PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ),
-                nFrameRate, channelMask );
-
-    if( IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat) != DS_OK )
-    {
-        PaWin_InitializeWaveFormatEx( &waveFormat, nChannels, sampleFormat, 
-                PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat ), nFrameRate );
-
-        if((result = IDirectSoundBuffer_SetFormat( stream->pDirectSoundPrimaryBuffer, (WAVEFORMATEX*)&waveFormat)) != DS_OK)
-            goto error;
-    }
-
-    // ----------------------------------------------------------------------
-    // Setup the secondary buffer description
-    ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC));
-    secondaryDesc.dwSize = sizeof(DSBUFFERDESC);
-    secondaryDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;
-    secondaryDesc.dwBufferBytes = bytesPerBuffer;
-    secondaryDesc.lpwfxFormat = (WAVEFORMATEX*)&waveFormat; /* waveFormat contains whatever format was negotiated for the primary buffer above */
-    // Create the secondary buffer
-    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,
-                  &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK)
-      goto error;
-    
-    return DS_OK;
-
-error:
-
-    if( stream->pDirectSoundPrimaryBuffer )
-    {
-        IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
-        stream->pDirectSoundPrimaryBuffer = NULL;
-    }
-
-    return result;
-}
-
-/***********************************************************************************/
-/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
-
-static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
-                           PaStream** s,
-                           const PaStreamParameters *inputParameters,
-                           const PaStreamParameters *outputParameters,
-                           double sampleRate,
-                           unsigned long framesPerBuffer,
-                           PaStreamFlags streamFlags,
-                           PaStreamCallback *streamCallback,
-                           void *userData )
-{
-    PaError result = paNoError;
-    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;
-    PaWinDsStream *stream = 0;
-    int bufferProcessorIsInitialized = 0;
-    int streamRepresentationIsInitialized = 0;
-    PaWinDsDeviceInfo *inputWinDsDeviceInfo, *outputWinDsDeviceInfo;
-    PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
-    int inputChannelCount, outputChannelCount;
-    PaSampleFormat inputSampleFormat, outputSampleFormat;
-    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
-    unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames;
-    PaWinDirectSoundStreamInfo *inputStreamInfo, *outputStreamInfo;
-    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;
-
-    if( inputParameters )
-    {
-        inputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ inputParameters->device ];
-        inputDeviceInfo = &inputWinDsDeviceInfo->inheritedDeviceInfo;
-
-        inputChannelCount = inputParameters->channelCount;
-        inputSampleFormat = inputParameters->sampleFormat;
-        suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate);
-
-        /* IDEA: the following 3 checks could be performed by default by pa_front
-            unless some flag indicated otherwise */
-            
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that input device can support inputChannelCount */
-        if( inputWinDsDeviceInfo->deviceInputChannelCountIsKnown
-                && inputChannelCount > inputDeviceInfo->maxInputChannels )
-            return paInvalidChannelCount;
-            
-        /* validate hostApiSpecificStreamInfo */
-        inputStreamInfo = (PaWinDirectSoundStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
-		result = ValidateWinDirectSoundSpecificStreamInfo( inputParameters, inputStreamInfo );
-		if( result != paNoError ) return result;
-
-        if( inputStreamInfo && inputStreamInfo->flags & paWinDirectSoundUseChannelMask )
-            inputChannelMask = inputStreamInfo->channelMask;
-        else
-            inputChannelMask = PaWin_DefaultChannelMask( inputChannelCount );
-    }
-    else
-    {
-        inputChannelCount = 0;
-		inputSampleFormat = 0;
-        suggestedInputLatencyFrames = 0;
-    }
-
-
-    if( outputParameters )
-    {
-        outputWinDsDeviceInfo = (PaWinDsDeviceInfo*) hostApi->deviceInfos[ outputParameters->device ];
-        outputDeviceInfo = &outputWinDsDeviceInfo->inheritedDeviceInfo;
-
-        outputChannelCount = outputParameters->channelCount;
-        outputSampleFormat = outputParameters->sampleFormat;
-        suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate);
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that output device can support outputChannelCount */
-        if( outputWinDsDeviceInfo->deviceOutputChannelCountIsKnown
-                && outputChannelCount > outputDeviceInfo->maxOutputChannels )
-            return paInvalidChannelCount;
-
-        /* validate hostApiSpecificStreamInfo */
-        outputStreamInfo = (PaWinDirectSoundStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
-		result = ValidateWinDirectSoundSpecificStreamInfo( outputParameters, outputStreamInfo );
-		if( result != paNoError ) return result;   
-
-        if( outputStreamInfo && outputStreamInfo->flags & paWinDirectSoundUseChannelMask )
-            outputChannelMask = outputStreamInfo->channelMask;
-        else
-            outputChannelMask = PaWin_DefaultChannelMask( outputChannelCount );
-    }
-    else
-    {
-        outputChannelCount = 0;
-		outputSampleFormat = 0;
-        suggestedOutputLatencyFrames = 0;
-    }
-
-
-    /*
-        IMPLEMENT ME:
-
-        ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() )
-
-            - check that input device can support inputSampleFormat, or that
-                we have the capability to convert from outputSampleFormat to
-                a native format
-
-            - check that output device can support outputSampleFormat, or that
-                we have the capability to convert from outputSampleFormat to
-                a native format
-
-            - if a full duplex stream is requested, check that the combination
-                of input and output parameters is supported
-
-            - check that the device supports sampleRate
-
-            - alter sampleRate to a close allowable rate if possible / necessary
-
-            - validate suggestedInputLatency and suggestedOutputLatency parameters,
-                use default values where necessary
-    */
-
-
-    /* validate platform specific flags */
-    if( (streamFlags & paPlatformSpecificFlags) != 0 )
-        return paInvalidFlag; /* unexpected platform specific flag */
-
-
-    stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) );
-    if( !stream )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */
-
-    if( streamCallback )
-    {
-        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
-                                               &winDsHostApi->callbackStreamInterface, streamCallback, userData );
-    }
-    else
-    {
-        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
-                                               &winDsHostApi->blockingStreamInterface, streamCallback, userData );
-    }
-    
-    streamRepresentationIsInitialized = 1;
-
-    stream->streamFlags = streamFlags;
-
-    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
-
-
-    if( inputParameters )
-    {
-        /* IMPLEMENT ME - establish which  host formats are available */
-        PaSampleFormat nativeInputFormats = paInt16;
-        //PaSampleFormat nativeFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32;
-
-        hostInputSampleFormat =
-            PaUtil_SelectClosestAvailableFormat( nativeInputFormats, inputParameters->sampleFormat );
-    }
-	else
-	{
-		hostInputSampleFormat = 0;
-	}
-
-    if( outputParameters )
-    {
-        /* IMPLEMENT ME - establish which  host formats are available */
-        PaSampleFormat nativeOutputFormats = paInt16;
-        //PaSampleFormat nativeOutputFormats = paUInt8 | paInt16 | paInt24 | paInt32 | paFloat32;
-
-        hostOutputSampleFormat =
-            PaUtil_SelectClosestAvailableFormat( nativeOutputFormats, outputParameters->sampleFormat );
-    }
-    else
-	{
-		hostOutputSampleFormat = 0;
-	}
-
-    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
-                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,
-                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
-                    sampleRate, streamFlags, framesPerBuffer,
-                    framesPerBuffer, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */
-                /* This next mode is required because DS can split the host buffer when it wraps around. */
-                    paUtilVariableHostBufferSizePartialUsageAllowed,
-                    streamCallback, userData );
-    if( result != paNoError )
-        goto error;
-
-    bufferProcessorIsInitialized = 1;
-
-    stream->streamRepresentation.streamInfo.inputLatency =
-            PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor);   /* FIXME: not initialised anywhere else */
-    stream->streamRepresentation.streamInfo.outputLatency =
-            PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor);    /* FIXME: not initialised anywhere else */
-    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
-
-    
-/* DirectSound specific initialization */ 
-    {
-        HRESULT          hr;
-        int              bytesPerDirectSoundInputBuffer, bytesPerDirectSoundOutputBuffer;
-        int              userLatencyFrames;
-        int              minLatencyFrames;
-        unsigned long    integerSampleRate = (unsigned long) (sampleRate + 0.5);
-    
-        stream->timerID = 0;
-
-        stream->processingCompleted = CreateEvent( NULL, /* bManualReset = */ TRUE, /* bInitialState = */ FALSE, NULL );
-        if( stream->processingCompleted == NULL )
-        {
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-    /* Get system minimum latency. */
-        minLatencyFrames = PaWinDs_GetMinLatencyFrames( sampleRate );
-
-    /* Let user override latency by passing latency parameter. */
-        userLatencyFrames = (suggestedInputLatencyFrames > suggestedOutputLatencyFrames)
-                    ? suggestedInputLatencyFrames
-                    : suggestedOutputLatencyFrames;
-        if( userLatencyFrames > 0 ) minLatencyFrames = userLatencyFrames;
-
-    /* Calculate stream->framesPerDSBuffer depending on framesPerBuffer */
-        if( framesPerBuffer == paFramesPerBufferUnspecified )
-        {
-        /* App support variable framesPerBuffer */
-            stream->framesPerDSBuffer = minLatencyFrames;
-
-            stream->streamRepresentation.streamInfo.outputLatency = (double)(minLatencyFrames - 1) / sampleRate;
-        }
-        else
-        {
-        /* Round up to number of buffers needed to guarantee that latency. */
-            int numUserBuffers = (minLatencyFrames + framesPerBuffer - 1) / framesPerBuffer;
-            if( numUserBuffers < 1 ) numUserBuffers = 1;
-            numUserBuffers += 1; /* So we have latency worth of buffers ahead of current buffer. */
-            stream->framesPerDSBuffer = framesPerBuffer * numUserBuffers;
-
-            stream->streamRepresentation.streamInfo.outputLatency = (double)(framesPerBuffer * (numUserBuffers-1)) / sampleRate;
-        }
-
-        {
-            /** @todo REVIEW: this calculation seems incorrect to me - rossb. */
-            int msecLatency = (int) ((stream->framesPerDSBuffer * MSEC_PER_SECOND) / sampleRate);
-            PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", stream->framesPerDSBuffer, msecLatency ));
-        }
-
-        /* set up i/o parameters */
-
-        /* ------------------ OUTPUT */
-        if( outputParameters )
-        {
-            LARGE_INTEGER  counterFrequency;
-
-            /*
-            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ];
-            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device));
-            */
-            
-            int bytesPerSample = Pa_GetSampleSize(hostOutputSampleFormat);
-            bytesPerDirectSoundOutputBuffer = stream->framesPerDSBuffer * outputParameters->channelCount * bytesPerSample;
-            if( bytesPerDirectSoundOutputBuffer < DSBSIZE_MIN )
-            {
-                result = paBufferTooSmall;
-                goto error;
-            }
-            else if( bytesPerDirectSoundOutputBuffer > DSBSIZE_MAX )
-            {
-                result = paBufferTooBig;
-                goto error;
-            }
-
-            /* Calculate value used in latency calculation to avoid real-time divides. */
-            stream->secondsPerHostByte = 1.0 /
-                (stream->bufferProcessor.bytesPerHostOutputSample *
-                outputChannelCount * sampleRate);
-
-            stream->outputBufferSizeBytes = bytesPerDirectSoundOutputBuffer;
-            stream->outputIsRunning = FALSE;
-            stream->outputUnderflowCount = 0;
-            stream->bytesPerOutputFrame = outputParameters->channelCount * bytesPerSample;
-
-            /* perfCounterTicksPerBuffer is used by QueryOutputSpace for overflow detection */
-            if( QueryPerformanceFrequency( &counterFrequency ) )
-            {
-                stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * stream->framesPerDSBuffer) / integerSampleRate;
-            }
-            else
-            {
-                stream->perfCounterTicksPerBuffer.QuadPart = 0;
-            }
-        }
-
-        /* ------------------ INPUT */
-        if( inputParameters )
-        {
-            /*
-            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ];
-            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device));
-            */
-            
-            int bytesPerSample = Pa_GetSampleSize(hostInputSampleFormat);
-            bytesPerDirectSoundInputBuffer = stream->framesPerDSBuffer * inputParameters->channelCount * bytesPerSample;
-            if( bytesPerDirectSoundInputBuffer < DSBSIZE_MIN )
-            {
-                result = paBufferTooSmall;
-                goto error;
-            }
-            else if( bytesPerDirectSoundInputBuffer > DSBSIZE_MAX )
-            {
-                result = paBufferTooBig;
-                goto error;
-            }
-
-            stream->bytesPerInputFrame = inputParameters->channelCount * bytesPerSample;
-
-            stream->inputSize = bytesPerDirectSoundInputBuffer;
-        }
-
-        /* open/create the DirectSound buffers */
-
-        /* interface ptrs should be zeroed when stream is zeroed. */
-        assert( stream->pDirectSoundCapture == NULL );
-        assert( stream->pDirectSoundInputBuffer == NULL );
-        assert( stream->pDirectSound == NULL );
-        assert( stream->pDirectSoundPrimaryBuffer == NULL );
-        assert( stream->pDirectSoundOutputBuffer == NULL );
-        
-
-        if( inputParameters && outputParameters )
-        {
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-            /* try to use the full-duplex DX8 API to create the buffers.
-                if that fails we fall back to the half-duplex API below */
-
-            hr = InitFullDuplexInputOutputBuffers( stream,
-                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],
-                                       hostInputSampleFormat,
-                                       (WORD)inputParameters->channelCount, bytesPerDirectSoundInputBuffer,
-                                       inputChannelMask,
-                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],
-                                       hostOutputSampleFormat,
-                                       (WORD)outputParameters->channelCount, bytesPerDirectSoundOutputBuffer,
-                                       outputChannelMask,
-                                       integerSampleRate
-                                        );
-            DBUG(("InitFullDuplexInputOutputBuffers() returns %x\n", hr));
-            /* ignore any error returned by InitFullDuplexInputOutputBuffers. 
-                we retry opening the buffers below */
-#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
-        }
-
-        /*  create half duplex buffers. also used for full-duplex streams which didn't 
-            succeed when using the full duplex API. that could happen because
-            DX8 or greater isnt installed, the i/o devices aren't the same 
-            physical device. etc.
-        */
-
-        if( outputParameters && !stream->pDirectSoundOutputBuffer )
-        {
-            hr = InitOutputBuffer( stream,
-                                       (PaWinDsDeviceInfo*)hostApi->deviceInfos[outputParameters->device],
-                                       hostOutputSampleFormat,
-                                       integerSampleRate,
-                                       (WORD)outputParameters->channelCount, bytesPerDirectSoundOutputBuffer,
-                                       outputChannelMask );
-            DBUG(("InitOutputBuffer() returns %x\n", hr));
-            if( hr != DS_OK )
-            {
-                result = paUnanticipatedHostError;
-                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
-                goto error;
-            }
-        }
-
-        if( inputParameters && !stream->pDirectSoundInputBuffer )
-        {
-            hr = InitInputBuffer( stream,
-                                      (PaWinDsDeviceInfo*)hostApi->deviceInfos[inputParameters->device],
-                                      hostInputSampleFormat,
-                                      integerSampleRate,
-                                      (WORD)inputParameters->channelCount, bytesPerDirectSoundInputBuffer,
-                                      inputChannelMask );
-            DBUG(("InitInputBuffer() returns %x\n", hr));
-            if( hr != DS_OK )
-            {
-                ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));
-                result = paUnanticipatedHostError;
-                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
-                goto error;
-            }
-        }
-    }
-
-    *s = (PaStream*)stream;
-
-    return result;
-
-error:
-    if( stream )
-    {
-        if( stream->processingCompleted != NULL )
-            CloseHandle( stream->processingCompleted );
-
-        if( stream->pDirectSoundOutputBuffer )
-        {
-            IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
-            IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
-            stream->pDirectSoundOutputBuffer = NULL;
-        }
-
-        if( stream->pDirectSoundPrimaryBuffer )
-        {
-            IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
-            stream->pDirectSoundPrimaryBuffer = NULL;
-        }
-
-        if( stream->pDirectSoundInputBuffer )
-        {
-            IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
-            IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
-            stream->pDirectSoundInputBuffer = NULL;
-        }
-
-        if( stream->pDirectSoundCapture )
-        {
-            IDirectSoundCapture_Release( stream->pDirectSoundCapture );
-            stream->pDirectSoundCapture = NULL;
-        }
-
-        if( stream->pDirectSound )
-        {
-            IDirectSound_Release( stream->pDirectSound );
-            stream->pDirectSound = NULL;
-        }
-
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-        if( stream->pDirectSoundFullDuplex8 )
-        {
-            IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );
-            stream->pDirectSoundFullDuplex8 = NULL;
-        }
-#endif
-        if( bufferProcessorIsInitialized )
-            PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
-
-        if( streamRepresentationIsInitialized )
-            PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
-
-        PaUtil_FreeMemory( stream );
-    }
-
-    return result;
-}
-
-
-/************************************************************************************
- * Determine how much space can be safely written to in DS buffer.
- * Detect underflows and overflows.
- * Does not allow writing into safety gap maintained by DirectSound.
- */
-static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty )
-{
-    HRESULT hr;
-    DWORD   playCursor;
-    DWORD   writeCursor;
-    long    numBytesEmpty;
-    long    playWriteGap;
-    // Query to see how much room is in buffer.
-    hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
-            &playCursor, &writeCursor );
-    if( hr != DS_OK )
-    {
-        return hr;
-    }
-
-    // Determine size of gap between playIndex and WriteIndex that we cannot write into.
-    playWriteGap = writeCursor - playCursor;
-    if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap
-
-    /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */
-    /* Attempt to detect playCursor wrap-around and correct it. */
-    if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) )
-    {
-        /* How much time has elapsed since last check. */
-        LARGE_INTEGER   currentTime;
-        LARGE_INTEGER   elapsedTime;
-        long            bytesPlayed;
-        long            bytesExpected;
-        long            buffersWrapped;
-
-        QueryPerformanceCounter( &currentTime );
-        elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart;
-        stream->previousPlayTime = currentTime;
-
-        /* How many bytes does DirectSound say have been played. */
-        bytesPlayed = playCursor - stream->previousPlayCursor;
-        if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap
-        stream->previousPlayCursor = playCursor;
-
-        /* Calculate how many bytes we would have expected to been played by now. */
-        bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart);
-        buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes;
-        if( buffersWrapped > 0 )
-        {
-            playCursor += (buffersWrapped * stream->outputBufferSizeBytes);
-            bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes);
-        }
-    }
-    numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes;
-    if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset
-
-    /* Have we underflowed? */
-    if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) )
-    {
-        if( stream->outputIsRunning )
-        {
-            stream->outputUnderflowCount += 1;
-        }
-
-        /*
-            From MSDN:
-                The write cursor indicates the position at which it is safe  
-            to write new data to the buffer. The write cursor always leads the
-            play cursor, typically by about 15 milliseconds' worth of audio
-            data.
-                It is always safe to change data that is behind the position 
-            indicated by the lpdwCurrentPlayCursor parameter.
-        */
-
-        stream->outputBufferWriteOffsetBytes = writeCursor;
-        numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap;
-    }
-    *bytesEmpty = numBytesEmpty;
-    return hr;
-}
-
-/***********************************************************************************/
-static int TimeSlice( PaWinDsStream *stream )
-{
-    long              numFrames = 0;
-    long              bytesEmpty = 0;
-    long              bytesFilled = 0;
-    long              bytesToXfer = 0;
-    long              framesToXfer = 0;
-    long              numInFramesReady = 0;
-    long              numOutFramesReady = 0;
-    long              bytesProcessed;
-    HRESULT           hresult;
-    double            outputLatency = 0;
-    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */
-    
-/* Input */
-    LPBYTE            lpInBuf1 = NULL;
-    LPBYTE            lpInBuf2 = NULL;
-    DWORD             dwInSize1 = 0;
-    DWORD             dwInSize2 = 0;
-/* Output */
-    LPBYTE            lpOutBuf1 = NULL;
-    LPBYTE            lpOutBuf2 = NULL;
-    DWORD             dwOutSize1 = 0;
-    DWORD             dwOutSize2 = 0;
-
-    /* How much input data is available? */
-    if( stream->bufferProcessor.inputChannelCount > 0 )
-    {
-        HRESULT hr;
-        DWORD capturePos;
-        DWORD readPos;
-        long  filled = 0;
-        // Query to see how much data is in buffer.
-        // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly
-        // so let's pass a pointer just to be safe.
-        hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos );
-        if( hr == DS_OK )
-        {
-            filled = readPos - stream->readOffset;
-            if( filled < 0 ) filled += stream->inputSize; // unwrap offset
-            bytesFilled = filled;
-        }
-            // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails?
-
-        framesToXfer = numInFramesReady = bytesFilled / stream->bytesPerInputFrame; 
-        outputLatency = ((double)bytesFilled) * stream->secondsPerHostByte;  // FIXME: this doesn't look right. we're calculating output latency in input branch. also secondsPerHostByte is only initialized for the output stream
-
-        /** @todo Check for overflow */
-    }
-
-    /* How much output room is available? */
-    if( stream->bufferProcessor.outputChannelCount > 0 )
-    {
-        UINT previousUnderflowCount = stream->outputUnderflowCount;
-        QueryOutputSpace( stream, &bytesEmpty );
-        framesToXfer = numOutFramesReady = bytesEmpty / stream->bytesPerOutputFrame;
-
-        /* Check for underflow */
-        if( stream->outputUnderflowCount != previousUnderflowCount )
-            stream->callbackFlags |= paOutputUnderflow;
-    }
-
-    if( (numInFramesReady > 0) && (numOutFramesReady > 0) )
-    {
-        framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady;
-    }
-
-    if( framesToXfer > 0 )
-    {
-
-        PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
-
-    /* The outputBufferDacTime parameter should indicates the time at which
-        the first sample of the output buffer is heard at the DACs. */
-        timeInfo.currentTime = PaUtil_GetTime();
-        timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency; // FIXME: QueryOutputSpace gets the playback position, we could use that (?)
-
-
-        PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags );
-        stream->callbackFlags = 0;
-        
-    /* Input */
-        if( stream->bufferProcessor.inputChannelCount > 0 )
-        {
-            bytesToXfer = framesToXfer * stream->bytesPerInputFrame;
-            hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer,
-                stream->readOffset, bytesToXfer,
-                (void **) &lpInBuf1, &dwInSize1,
-                (void **) &lpInBuf2, &dwInSize2, 0);
-            if (hresult != DS_OK)
-            {
-                ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult));
-                /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */
-                PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */
-                stream->callbackResult = paComplete;
-                goto error2;
-            }
-
-            numFrames = dwInSize1 / stream->bytesPerInputFrame;
-            PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames );
-            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 );
-        /* Is input split into two regions. */
-            if( dwInSize2 > 0 )
-            {
-                numFrames = dwInSize2 / stream->bytesPerInputFrame;
-                PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames );
-                PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 );
-            }
-        }
-
-    /* Output */
-        if( stream->bufferProcessor.outputChannelCount > 0 )
-        {
-            bytesToXfer = framesToXfer * stream->bytesPerOutputFrame;
-            hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer,
-                stream->outputBufferWriteOffsetBytes, bytesToXfer,
-                (void **) &lpOutBuf1, &dwOutSize1,
-                (void **) &lpOutBuf2, &dwOutSize2, 0);
-            if (hresult != DS_OK)
-            {
-                ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult));
-                /* PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult ); */
-                PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); /* flush the buffer processor */
-                stream->callbackResult = paComplete;
-                goto error1;
-            }
-
-            numFrames = dwOutSize1 / stream->bytesPerOutputFrame;
-            PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames );
-            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 );
-
-        /* Is output split into two regions. */
-            if( dwOutSize2 > 0 )
-            {
-                numFrames = dwOutSize2 / stream->bytesPerOutputFrame;
-                PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames );
-                PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 );
-            }
-        }
-
-        numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &stream->callbackResult );
-        stream->framesWritten += numFrames;
-        
-        if( stream->bufferProcessor.outputChannelCount > 0 )
-        {
-        /* FIXME: an underflow could happen here */
-
-        /* Update our buffer offset and unlock sound buffer */
-            bytesProcessed = numFrames * stream->bytesPerOutputFrame;
-            stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes;
-            IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2);
-        }
-
-error1:
-        if( stream->bufferProcessor.inputChannelCount > 0 )
-        {
-        /* FIXME: an overflow could happen here */
-
-        /* Update our buffer offset and unlock sound buffer */
-            bytesProcessed = numFrames * stream->bytesPerInputFrame;
-            stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputSize;
-            IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2);
-        }
-error2:
-
-        PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames );        
-    }
-
-    if( stream->callbackResult == paComplete && !PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
-    {
-        /* don't return completed until the buffer processor has been drained */
-        return paContinue;
-    }
-    else
-    {
-        return stream->callbackResult;
-    }
-}
-/*******************************************************************/
-
-static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream )
-{
-    HRESULT hr;
-    LPBYTE lpbuf1 = NULL;
-    LPBYTE lpbuf2 = NULL;
-    DWORD dwsize1 = 0;
-    DWORD dwsize2 = 0;
-    long  bytesEmpty;
-    hr = QueryOutputSpace( stream, &bytesEmpty );
-    if (hr != DS_OK) return hr;
-    if( bytesEmpty == 0 ) return DS_OK;
-    // Lock free space in the DS
-    hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes,
-                                    bytesEmpty, (void **) &lpbuf1, &dwsize1,
-                                    (void **) &lpbuf2, &dwsize2, 0);
-    if (hr == DS_OK)
-    {
-        // Copy the buffer into the DS
-        ZeroMemory(lpbuf1, dwsize1);
-        if(lpbuf2 != NULL)
-        {
-            ZeroMemory(lpbuf2, dwsize2);
-        }
-        // Update our buffer offset and unlock sound buffer
-        stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes;
-        IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2);
-
-        stream->finalZeroBytesWritten += dwsize1 + dwsize2;
-    }
-    return hr;
-}
-
-
-static void CALLBACK TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2)
-{
-    PaWinDsStream *stream;
-    int isFinished = 0;
-
-    /* suppress unused variable warnings */
-    (void) uID;
-    (void) uMsg;
-    (void) dw1;
-    (void) dw2;
-    
-    stream = (PaWinDsStream *) dwUser;
-    if( stream == NULL ) return;
-
-    if( stream->isActive )
-    {
-        if( stream->abortProcessing )
-        {
-            isFinished = 1;
-        }
-        else if( stream->stopProcessing )
-        {
-            if( stream->bufferProcessor.outputChannelCount > 0 )
-            {
-                ZeroAvailableOutputSpace( stream );
-                if( stream->finalZeroBytesWritten >= stream->outputBufferSizeBytes )
-                {
-                    /* once we've flushed the whole output buffer with zeros we know all data has been played */
-                    isFinished = 1;
-                }
-            }
-            else
-            {
-                isFinished = 1;
-            }
-        }
-        else
-        {
-            int callbackResult = TimeSlice( stream );
-            if( callbackResult != paContinue )
-            {
-                /* FIXME implement handling of paComplete and paAbort if possible 
-                   At the moment this should behave as if paComplete was called and 
-                   flush the buffer.
-                */
-
-                stream->stopProcessing = 1;
-            }
-        }
-
-        if( isFinished )
-        {
-            if( stream->streamRepresentation.streamFinishedCallback != 0 )
-                stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
-
-            stream->isActive = 0; /* don't set this until the stream really is inactive */
-            SetEvent( stream->processingCompleted );
-        }
-    }
-}
-
-/***********************************************************************************
-    When CloseStream() is called, the multi-api layer ensures that
-    the stream has already been stopped or aborted.
-*/
-static PaError CloseStream( PaStream* s )
-{
-    PaError result = paNoError;
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    CloseHandle( stream->processingCompleted );
-
-    // Cleanup the sound buffers
-    if( stream->pDirectSoundOutputBuffer )
-    {
-        IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
-        IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );
-        stream->pDirectSoundOutputBuffer = NULL;
-    }
-
-    if( stream->pDirectSoundPrimaryBuffer )
-    {
-        IDirectSoundBuffer_Release( stream->pDirectSoundPrimaryBuffer );
-        stream->pDirectSoundPrimaryBuffer = NULL;
-    }
-
-    if( stream->pDirectSoundInputBuffer )
-    {
-        IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
-        IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );
-        stream->pDirectSoundInputBuffer = NULL;
-    }
-
-    if( stream->pDirectSoundCapture )
-    {
-        IDirectSoundCapture_Release( stream->pDirectSoundCapture );
-        stream->pDirectSoundCapture = NULL;
-    }
-
-    if( stream->pDirectSound )
-    {
-        IDirectSound_Release( stream->pDirectSound );
-        stream->pDirectSound = NULL;
-    }
-
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-    if( stream->pDirectSoundFullDuplex8 )
-    {
-        IDirectSoundFullDuplex_Release( stream->pDirectSoundFullDuplex8 );
-        stream->pDirectSoundFullDuplex8 = NULL;
-    }
-#endif
-
-    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
-    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
-    PaUtil_FreeMemory( stream );
-
-    return result;
-}
-
-/***********************************************************************************/
-static HRESULT ClearOutputBuffer( PaWinDsStream *stream )
-{
-    PaError          result = paNoError;
-    unsigned char*   pDSBuffData;
-    DWORD            dwDataLen;
-    HRESULT          hr;
-
-    hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 );
-    DBUG(("PaHost_ClearOutputBuffer: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr));
-    if( hr != DS_OK )
-        return hr;
-
-    // Lock the DS buffer
-    if ((hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData,
-                                           &dwDataLen, NULL, 0, 0)) != DS_OK )
-        return hr;
-
-    // Zero the DS buffer
-    ZeroMemory(pDSBuffData, dwDataLen);
-    // Unlock the DS buffer
-    if ((hr = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK)
-        return hr;
-    
-    // Let DSound set the starting write position because if we set it to zero, it looks like the
-    // buffer is full to begin with. This causes a long pause before sound starts when using large buffers.
-    if ((hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,
-            &stream->previousPlayCursor, &stream->outputBufferWriteOffsetBytes )) != DS_OK)
-        return hr;
-
-    /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */
-
-    return DS_OK;
-}
-
-static PaError StartStream( PaStream *s )
-{
-    PaError          result = paNoError;
-    PaWinDsStream   *stream = (PaWinDsStream*)s;
-    HRESULT          hr;
-        
-    stream->callbackResult = paContinue;
-    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
-    
-    ResetEvent( stream->processingCompleted );
-
-    if( stream->bufferProcessor.inputChannelCount > 0 )
-    {
-        // Start the buffer capture
-        if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary
-        {
-            hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING );
-        }
-
-        DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr));
-        if( hr != DS_OK )
-        {
-            result = paUnanticipatedHostError;
-            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
-            goto error;
-        }
-    }
-
-    stream->framesWritten = 0;
-    stream->callbackFlags = 0;
-
-    stream->abortProcessing = 0;
-    stream->stopProcessing = 0;
-    stream->isActive = 1;
-
-    if( stream->bufferProcessor.outputChannelCount > 0 )
-    {
-        QueryPerformanceCounter( &stream->previousPlayTime );
-        stream->finalZeroBytesWritten = 0;
-
-        hr = ClearOutputBuffer( stream );
-        if( hr != DS_OK )
-        {
-            result = paUnanticipatedHostError;
-            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
-            goto error;
-        }
-
-        if( stream->streamRepresentation.streamCallback && (stream->streamFlags & paPrimeOutputBuffersUsingStreamCallback) )
-        {
-            stream->callbackFlags = paPrimingOutput;
-
-            TimeSlice( stream );
-            /* we ignore the return value from TimeSlice here and start the stream as usual.
-                The first timer callback will detect if the callback has completed. */
-
-            stream->callbackFlags = 0;
-        }
-
-        // Start the buffer playback in a loop.
-        if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here
-        {
-            hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING );
-            DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr));
-            if( hr != DS_OK )
-            {
-                result = paUnanticipatedHostError;
-                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
-                goto error;
-            }
-            stream->outputIsRunning = TRUE;
-        }
-    }
-
-    if( stream->streamRepresentation.streamCallback )
-    {
-        /* Create timer that will wake us up so we can fill the DSound buffer. */
-        int resolution;
-        int framesPerWakeup = stream->framesPerDSBuffer / 4;
-        int msecPerWakeup = MSEC_PER_SECOND * framesPerWakeup / (int) stream->streamRepresentation.streamInfo.sampleRate;
-        if( msecPerWakeup < 10 ) msecPerWakeup = 10;
-        else if( msecPerWakeup > 100 ) msecPerWakeup = 100;
-        resolution = msecPerWakeup/4;
-        stream->timerID = timeSetEvent( msecPerWakeup, resolution, (LPTIMECALLBACK) TimerCallback,
-                                             (DWORD_PTR) stream, TIME_PERIODIC | TIME_KILL_SYNCHRONOUS );
-    
-        if( stream->timerID == 0 )
-        {
-            stream->isActive = 0;
-            result = paUnanticipatedHostError;
-            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );
-            goto error;
-        }
-    }
-
-    stream->isStarted = TRUE;
-
-error:
-    return result;
-}
-
-
-/***********************************************************************************/
-static PaError StopStream( PaStream *s )
-{
-    PaError result = paNoError;
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-    HRESULT          hr;
-    int timeoutMsec;
-
-    if( stream->streamRepresentation.streamCallback )
-    {
-        stream->stopProcessing = 1;
-
-        /* Set timeout at 4 times maximum time we might wait. */
-        timeoutMsec = (int) (4 * MSEC_PER_SECOND * (stream->framesPerDSBuffer / stream->streamRepresentation.streamInfo.sampleRate));
-
-        WaitForSingleObject( stream->processingCompleted, timeoutMsec );
-    }
-
-    if( stream->timerID != 0 )
-    {
-        timeKillEvent(stream->timerID);  /* Stop callback timer. */
-        stream->timerID = 0;
-    }
-
-
-    if( stream->bufferProcessor.outputChannelCount > 0 )
-    {
-        // Stop the buffer playback
-        if( stream->pDirectSoundOutputBuffer != NULL )
-        {
-            stream->outputIsRunning = FALSE;
-            // FIXME: what happens if IDirectSoundBuffer_Stop returns an error?
-            hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );
-
-            if( stream->pDirectSoundPrimaryBuffer )
-                IDirectSoundBuffer_Stop( stream->pDirectSoundPrimaryBuffer ); /* FIXME we never started the primary buffer so I'm not sure we need to stop it */
-        }
-    }
-
-    if( stream->bufferProcessor.inputChannelCount > 0 )
-    {
-        // Stop the buffer capture
-        if( stream->pDirectSoundInputBuffer != NULL )
-        {
-            // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error?
-            hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );
-        }
-    }
-
-    stream->isStarted = FALSE;
-
-    return result;
-}
-
-
-/***********************************************************************************/
-static PaError AbortStream( PaStream *s )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    stream->abortProcessing = 1;
-    return StopStream( s );
-}
-
-
-/***********************************************************************************/
-static PaError IsStreamStopped( PaStream *s )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    return !stream->isStarted;
-}
-
-
-/***********************************************************************************/
-static PaError IsStreamActive( PaStream *s )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    return stream->isActive;
-}
-
-/***********************************************************************************/
-static PaTime GetStreamTime( PaStream *s )
-{
-    /* suppress unused variable warnings */
-    (void) s;
-
-    return PaUtil_GetTime();
-}
-
-
-/***********************************************************************************/
-static double GetStreamCpuLoad( PaStream* s )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
-}
-
-
-/***********************************************************************************
-    As separate stream interfaces are used for blocking and callback
-    streams, the following functions can be guaranteed to only be called
-    for blocking streams.
-*/
-
-static PaError ReadStream( PaStream* s,
-                           void *buffer,
-                           unsigned long frames )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    /* suppress unused variable warnings */
-    (void) buffer;
-    (void) frames;
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-
-    return paNoError;
-}
-
-
-/***********************************************************************************/
-static PaError WriteStream( PaStream* s,
-                            const void *buffer,
-                            unsigned long frames )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    /* suppress unused variable warnings */
-    (void) buffer;
-    (void) frames;
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-
-    return paNoError;
-}
-
-
-/***********************************************************************************/
-static signed long GetStreamReadAvailable( PaStream* s )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    /* suppress unused variable warnings */
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-
-    return 0;
-}
-
-
-/***********************************************************************************/
-static signed long GetStreamWriteAvailable( PaStream* s )
-{
-    PaWinDsStream *stream = (PaWinDsStream*)s;
-
-    /* suppress unused variable warnings */
-    (void) stream;
-    
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-
-    return 0;
-}
-
-
-
diff --git a/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c b/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c
deleted file mode 100644
index c4e3c4eca..000000000
--- a/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.c
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Interface for dynamically loading directsound and providing a dummy
- * implementation if it isn't present.
- *
- * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)
- *
- * For PortAudio Portable Real-Time Audio Library
- * For more information see: http://www.portaudio.com
- * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/**
- @file
- @ingroup hostapi_src
-*/
-
-#include "pa_win_ds_dynlink.h"
-#include "pa_debugprint.h"
-
-PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 };
-
-
-static HRESULT WINAPI DummyDllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
-{
-    (void)rclsid; /* unused parameter */
-    (void)riid; /* unused parameter */
-    (void)ppv; /* unused parameter */
-    return CLASS_E_CLASSNOTAVAILABLE;
-}
-
-static HRESULT WINAPI DummyDirectSoundCreate(LPGUID lpcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter)
-{
-    (void)lpcGuidDevice; /* unused parameter */
-    (void)ppDS; /* unused parameter */
-    (void)pUnkOuter; /* unused parameter */
-    return E_NOTIMPL;
-}
-
-static HRESULT WINAPI DummyDirectSoundEnumerateW(LPDSENUMCALLBACKW lpDSEnumCallback, LPVOID lpContext)
-{
-    (void)lpDSEnumCallback; /* unused parameter */
-    (void)lpContext; /* unused parameter */
-    return E_NOTIMPL;
-}
-
-static HRESULT WINAPI DummyDirectSoundEnumerateA(LPDSENUMCALLBACKA lpDSEnumCallback, LPVOID lpContext)
-{
-    (void)lpDSEnumCallback; /* unused parameter */
-    (void)lpContext; /* unused parameter */
-    return E_NOTIMPL;
-}
-
-static HRESULT WINAPI DummyDirectSoundCaptureCreate(LPGUID lpcGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter)
-{
-    (void)lpcGUID; /* unused parameter */
-    (void)lplpDSC; /* unused parameter */
-    (void)pUnkOuter; /* unused parameter */
-    return E_NOTIMPL;
-}
-
-static HRESULT WINAPI DummyDirectSoundCaptureEnumerateW(LPDSENUMCALLBACKW lpDSCEnumCallback, LPVOID lpContext)
-{
-    (void)lpDSCEnumCallback; /* unused parameter */
-    (void)lpContext; /* unused parameter */
-    return E_NOTIMPL;
-}
-
-static HRESULT WINAPI DummyDirectSoundCaptureEnumerateA(LPDSENUMCALLBACKA lpDSCEnumCallback, LPVOID lpContext)
-{
-    (void)lpDSCEnumCallback; /* unused parameter */
-    (void)lpContext; /* unused parameter */
-    return E_NOTIMPL;
-}
-
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-static HRESULT WINAPI DummyDirectSoundFullDuplexCreate8(
-         LPCGUID pcGuidCaptureDevice,
-         LPCGUID pcGuidRenderDevice,
-         LPCDSCBUFFERDESC pcDSCBufferDesc,
-         LPCDSBUFFERDESC pcDSBufferDesc,
-         HWND hWnd,
-         DWORD dwLevel,
-         LPDIRECTSOUNDFULLDUPLEX * ppDSFD,
-         LPDIRECTSOUNDCAPTUREBUFFER8 * ppDSCBuffer8,
-         LPDIRECTSOUNDBUFFER8 * ppDSBuffer8,
-         LPUNKNOWN pUnkOuter)
-{
-    (void)pcGuidCaptureDevice; /* unused parameter */
-    (void)pcGuidRenderDevice; /* unused parameter */
-    (void)pcDSCBufferDesc; /* unused parameter */
-    (void)pcDSBufferDesc; /* unused parameter */
-    (void)hWnd; /* unused parameter */
-    (void)dwLevel; /* unused parameter */
-    (void)ppDSFD; /* unused parameter */
-    (void)ppDSCBuffer8; /* unused parameter */
-    (void)ppDSBuffer8; /* unused parameter */
-    (void)pUnkOuter; /* unused parameter */
-
-    return E_NOTIMPL;
-}
-#endif /* PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE */
-
-void PaWinDs_InitializeDSoundEntryPoints(void)
-{
-    paWinDsDSoundEntryPoints.hInstance_ = LoadLibraryA("dsound.dll");
-    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )
-    {
-        paWinDsDSoundEntryPoints.DllGetClassObject =
-                (HRESULT (WINAPI *)(REFCLSID, REFIID , LPVOID *))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DllGetClassObject" );
-        if( paWinDsDSoundEntryPoints.DllGetClassObject == NULL )
-            paWinDsDSoundEntryPoints.DllGetClassObject = DummyDllGetClassObject;
-
-        paWinDsDSoundEntryPoints.DirectSoundCreate =
-                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCreate" );
-        if( paWinDsDSoundEntryPoints.DirectSoundCreate == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;
-
-        paWinDsDSoundEntryPoints.DirectSoundEnumerateW =
-                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateW" );
-        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateW == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;
-
-        paWinDsDSoundEntryPoints.DirectSoundEnumerateA =
-                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateA" );
-        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateA == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;
-
-        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate =
-                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureCreate" );
-        if( paWinDsDSoundEntryPoints.DirectSoundCaptureCreate == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;
-
-        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW =
-                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateW" );
-        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;
-
-        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA =
-                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateA" );
-        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;
-
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-        paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 =
-                (HRESULT (WINAPI *)(LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,
-                                    HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *, 
-                                    LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN))
-                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundFullDuplexCreate" );
-        if( paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 == NULL )
-            paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;
-#endif
-    }
-    else
-    {
-        DWORD errorCode = GetLastError(); // 126 (0x7E) == ERROR_MOD_NOT_FOUND
-        PA_DEBUG(("Couldn't load dsound.dll error code: %d \n",errorCode));
-
-        /* initialize with dummy entry points to make live easy when ds isn't present */
-        paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;
-        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;
-        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;
-        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;
-        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;
-        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-        paWinDsDSoundEntryPoints.DirectSoundFullDuplexCreate8 = DummyDirectSoundFullDuplexCreate8;
-#endif
-    }
-}
-
-
-void PaWinDs_TerminateDSoundEntryPoints(void)
-{
-    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )
-    {
-        /* ensure that we crash reliably if the entry points arent initialised */
-        paWinDsDSoundEntryPoints.DirectSoundCreate = 0;
-        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = 0;
-        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = 0;
-        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = 0;
-        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = 0;
-        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = 0;
-
-        FreeLibrary( paWinDsDSoundEntryPoints.hInstance_ );
-        paWinDsDSoundEntryPoints.hInstance_ = NULL;
-    }
-}
\ No newline at end of file
diff --git a/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h b/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h
deleted file mode 100644
index fd6d8feda..000000000
--- a/portaudio/src/hostapi/dsound/pa_win_ds_dynlink.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Interface for dynamically loading directsound and providing a dummy
- * implementation if it isn't present.
- *
- * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)
- *
- * For PortAudio Portable Real-Time Audio Library
- * For more information see: http://www.portaudio.com
- * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/**
- @file
- @ingroup hostapi_src
-*/
-
-#ifndef INCLUDED_PA_DSOUND_DYNLINK_H
-#define INCLUDED_PA_DSOUND_DYNLINK_H
-
-/* on Borland compilers, WIN32 doesn't seem to be defined by default, which
-    breaks dsound.h. Adding the define here fixes the problem. - rossb. */
-#ifdef __BORLANDC__
-#if !defined(WIN32)
-#define WIN32
-#endif
-#endif
-
-/*
-  Use the earliest version of DX required, no need to polute the namespace
-*/
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-#define DIRECTSOUND_VERSION 0x0800
-#else
-#define DIRECTSOUND_VERSION 0x0300
-#endif
-#include <dsound.h>
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-
-typedef struct
-{
-    HINSTANCE hInstance_;
-    
-    HRESULT (WINAPI *DllGetClassObject)(REFCLSID , REFIID , LPVOID *);
-
-    HRESULT (WINAPI *DirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
-    HRESULT (WINAPI *DirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
-    HRESULT (WINAPI *DirectSoundEnumerateA)(LPDSENUMCALLBACKA, LPVOID);
-
-    HRESULT (WINAPI *DirectSoundCaptureCreate)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN);
-    HRESULT (WINAPI *DirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID);
-    HRESULT (WINAPI *DirectSoundCaptureEnumerateA)(LPDSENUMCALLBACKA, LPVOID);
-
-#ifdef PAWIN_USE_DIRECTSOUNDFULLDUPLEXCREATE
-    HRESULT (WINAPI *DirectSoundFullDuplexCreate8)(
-                LPCGUID, LPCGUID, LPCDSCBUFFERDESC, LPCDSBUFFERDESC,
-                HWND, DWORD, LPDIRECTSOUNDFULLDUPLEX *, LPDIRECTSOUNDCAPTUREBUFFER8 *, 
-                LPDIRECTSOUNDBUFFER8 *, LPUNKNOWN );
-#endif
-}PaWinDsDSoundEntryPoints;
-
-extern PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints;
-
-void PaWinDs_InitializeDSoundEntryPoints(void);
-void PaWinDs_TerminateDSoundEntryPoints(void);
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* INCLUDED_PA_DSOUND_DYNLINK_H */
diff --git a/portaudio/src/hostapi/jack/pa_jack.c b/portaudio/src/hostapi/jack/pa_jack.c
index 2c2396fe9..6b6c2120e 100644
--- a/portaudio/src/hostapi/jack/pa_jack.c
+++ b/portaudio/src/hostapi/jack/pa_jack.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_jack.c 1530 2010-07-29 06:29:41Z dmitrykos $
+ * $Id: pa_jack.c 1238 2007-07-15 16:58:50Z aknudsen $
  * PortAudio Portable Real-Time Audio Library
  * Latest Version at: http://www.portaudio.com
  * JACK Implementation by Joshua Haberman
@@ -254,7 +254,7 @@ static PaError BlockingInitFIFO( PaUtilRingBuffer *rbuf, long numFrames, long by
     char *buffer = (char *) malloc( numBytes );
     if( buffer == NULL ) return paInsufficientMemory;
     memset( buffer, 0, numBytes );
-    return (PaError) PaUtil_InitializeRingBuffer( rbuf, 1, numBytes, buffer );
+    return (PaError) PaUtil_InitializeRingBuffer( rbuf, numBytes, buffer );
 }
 
 /* Free buffer. */
@@ -717,19 +717,14 @@ PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi,
     ASSERT_CALL( pthread_cond_init( &jackHostApi->cond, NULL ), 0 );
 
     /* Try to become a client of the JACK server.  If we cannot do
-     * this, then this API cannot be used.
-     *
-     * Without the JackNoStartServer option, the jackd server is started
-     * automatically which we do not want.
-     */
+     * this, then this API cannot be used. */
 
-    jackHostApi->jack_client = jack_client_open( clientName_, JackNoStartServer, &jackStatus );
+    jackHostApi->jack_client = jack_client_open( clientName_, 0, &jackStatus );
     if( !jackHostApi->jack_client )
     {
         /* the V19 development docs say that if an implementation
          * detects that it cannot be used, it should return a NULL
          * interface and paNoError */
-        PA_DEBUG(( "%s: Couldn't connect to JACK, status: %d\n", __FUNCTION__, jackStatus ));
         result = paNoError;
         goto error;
     }
@@ -742,6 +737,7 @@ PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi,
     (*hostApi)->info.name = "JACK Audio Connection Kit";
 
     /* Build a device list by querying the JACK server */
+
     ENSURE_PA( BuildDeviceList( jackHostApi ) );
 
     /* Register functions */
@@ -1000,7 +996,7 @@ static PaError WaitCondition( PaJackHostApiRepresentation *hostApi )
     PaTime pt = PaUtil_GetTime();
     struct timespec ts;
 
-    ts.tv_sec = (time_t) floor( pt + 10 * 60 /* 10 minutes */ );
+    ts.tv_sec = (time_t) floor( pt + 1 );
     ts.tv_nsec = (long) ((pt - floor( pt )) * 1000000000);
     /* XXX: Best enclose in loop, in case of spurious wakeups? */
     err = pthread_cond_timedwait( &hostApi->cond, &hostApi->mtx, &ts );
@@ -1177,7 +1173,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
             minimum_buffer_frames = jackHostApi->jack_buffer_size * 3;
 
         /* setup blocking API data structures (FIXME: can fail) */
-        BlockingBegin( stream, minimum_buffer_frames );
+	BlockingBegin( stream, minimum_buffer_frames );
 
         /* install our own callback for the blocking API */
         streamCallback = BlockingCallback;
@@ -1276,10 +1272,10 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
                   &stream->bufferProcessor,
                   inputChannelCount,
                   inputSampleFormat,
-                  paFloat32 | paNonInterleaved, /* hostInputSampleFormat */
+                  paFloat32,            /* hostInputSampleFormat */
                   outputChannelCount,
                   outputSampleFormat,
-                  paFloat32 | paNonInterleaved, /* hostOutputSampleFormat */
+                  paFloat32,            /* hostOutputSampleFormat */
                   jackSr,
                   streamFlags,
                   framesPerBuffer,
@@ -1752,8 +1748,7 @@ PaError PaJack_GetClientName(const char** clientName)
 {
     PaError result = paNoError;
     PaJackHostApiRepresentation* jackHostApi = NULL;
-    PaJackHostApiRepresentation** ref = &jackHostApi;
-    ENSURE_PA( PaUtil_GetHostApiRepresentation( (PaUtilHostApiRepresentation**)ref, paJACK ) );
+    ENSURE_PA( PaUtil_GetHostApiRepresentation( (PaUtilHostApiRepresentation**)&jackHostApi, paJACK ) );
     *clientName = jack_get_client_name( jackHostApi->jack_client );
 
 error:
diff --git a/portaudio/src/hostapi/oss/pa_unix_oss.c b/portaudio/src/hostapi/oss/pa_unix_oss.c
index 9bc972bf8..516f5a459 100644
--- a/portaudio/src/hostapi/oss/pa_unix_oss.c
+++ b/portaudio/src/hostapi/oss/pa_unix_oss.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_unix_oss.c 1509 2010-06-06 17:36:33Z dmitrykos $
+ * $Id: pa_unix_oss.c 1238 2007-07-15 16:58:50Z aknudsen $
  * PortAudio Portable Real-Time Audio Library
  * Latest Version at: http://www.portaudio.com
  * OSS implementation by:
@@ -65,11 +65,7 @@
 
 #ifdef HAVE_SYS_SOUNDCARD_H
 # include <sys/soundcard.h>
-# ifdef __NetBSD__
-#  define DEVICE_NAME_BASE           "/dev/audio"
-# else
-#  define DEVICE_NAME_BASE           "/dev/dsp"
-# endif
+# define DEVICE_NAME_BASE            "/dev/dsp"
 #elif defined(HAVE_LINUX_SOUNDCARD_H)
 # include <linux/soundcard.h>
 # define DEVICE_NAME_BASE            "/dev/dsp"
@@ -101,7 +97,7 @@ static pthread_t mainThread_;
             /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
             if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
             { \
-                PaUtil_SetLastHostErrorInfo( paOSS, sysErr_, strerror( errno ) ); \
+                PaUtil_SetLastHostErrorInfo( paALSA, sysErr_, strerror( errno ) ); \
             } \
             \
             PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
@@ -185,7 +181,7 @@ typedef struct PaOssStream
     double sampleRate;
 
     int callbackMode;
-    volatile int callbackStop, callbackAbort;
+    int callbackStop, callbackAbort;
 
     PaOssStreamComponent *capture, *playback;
     unsigned long pollTimeout;
@@ -336,11 +332,7 @@ static PaError QueryDirection( const char *deviceName, StreamMode mode, double *
         }
         else
         {
-            /* Ignore ENOENT, which means we've tried a non-existent device */
-            if( errno != ENOENT )
-            {
-                PA_DEBUG(( "%s: Can't access device %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
-            }
+            PA_DEBUG(( "%s: Can't access device: %s\n", __FUNCTION__, strerror( errno ) ));
         }
 
         return paDeviceUnavailable;
@@ -409,7 +401,11 @@ static PaError QueryDirection( const char *deviceName, StreamMode mode, double *
     if( *defaultSampleRate < 0 )
     {
         sr = 44100;
-        ENSURE_( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ), paUnanticipatedHostError );
+        if( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ) < 0 )
+        {
+            result = paUnanticipatedHostError;
+            goto error;
+        }
 
         *defaultSampleRate = sr;
     }
@@ -512,20 +508,27 @@ static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )
     /* Find devices by calling QueryDevice on each
      * potential device names.  When we find a valid one,
      * add it to a linked list.
-     * A: Set an arbitrary of 100 devices, should probably be a smarter way. */
+     * A: Can there only be 10 devices? */
 
-    for( i = 0; i < 100; i++ )
+    for( i = 0; i < 10; i++ )
     {
        char deviceName[32];
        PaDeviceInfo *deviceInfo;
        int testResult;
+       struct stat stbuf;
 
        if( i == 0 )
           snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);
        else
           snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);
 
-       /* PA_DEBUG(("%s: trying device %s\n", __FUNCTION__, deviceName )); */
+       /* PA_DEBUG(("PaOSS BuildDeviceList: trying device %s\n", deviceName )); */
+       if( stat( deviceName, &stbuf ) < 0 )
+       {
+           if( ENOENT != errno )
+               PA_DEBUG(( "%s: Error stat'ing %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
+           continue;
+       }
        if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )
        {
            if( testResult != paDeviceUnavailable )
@@ -782,15 +785,11 @@ error:
     return result;
 }
 
-/** Open input and output devices.
- *
- * @param idev: Returned input device file descriptor.
- * @param odev: Returned output device file descriptor.
- */
 static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )
 {
     PaError result = paNoError;
     int flags = O_NONBLOCK, duplex = 0;
+    int enableBits = 0;
     *idev = *odev = -1;
 
     if( idevName && odevName )
@@ -810,6 +809,10 @@ static PaError OpenDevices( const char *idevName, const char *odevName, int *ide
     {
         ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );
         PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */
+
+        /* Initially disable */
+        enableBits = ~PCM_ENABLE_INPUT;
+        ENSURE_( ioctl( *idev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
     }
     if( odevName )
     {
@@ -817,6 +820,10 @@ static PaError OpenDevices( const char *idevName, const char *odevName, int *ide
         {
             ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );
             PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */
+
+            /* Initially disable */
+            enableBits = ~PCM_ENABLE_OUTPUT;
+            ENSURE_( ioctl( *odev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
         }
         else
         {
@@ -969,10 +976,8 @@ static int CalcHigherLogTwo( int n )
     return log2;
 }
 
-/** Configure stream component device parameters.
- */
-static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long
-        framesPerBuffer, StreamMode streamMode, PaOssStreamComponent *master )
+static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long framesPerBuffer,
+        StreamMode streamMode, PaOssStreamComponent *master )
 {
     PaError result = paNoError;
     int temp, nativeFormat;
@@ -1184,7 +1189,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;
     int bpInitialized = 0;
     double inLatency = 0., outLatency = 0.;
-    int i = 0;
 
     /* validate platform specific flags */
     if( (streamFlags & paPlatformSpecificFlags) != 0 )
@@ -1221,14 +1225,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
         }
     }
 
-    /* Round framesPerBuffer to the next power-of-two to make OSS happy. */
-    if( framesPerBuffer != paFramesPerBufferUnspecified )
-    {
-        framesPerBuffer &= INT_MAX;
-        for (i = 1; framesPerBuffer > i; i <<= 1) ;
-        framesPerBuffer = i;
-    }
-
     /* allocate and do basic initialization of the stream structure */
     PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );
     PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );
@@ -1317,17 +1313,7 @@ static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *fr
 
     while( pollPlayback || pollCapture )
     {
-#ifdef PTHREAD_CANCELED
         pthread_testcancel();
-#else
-        /* avoid indefinite waiting on thread not supporting cancelation */
-        if( stream->callbackStop || stream->callbackAbort )
-        {
-            PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
-            (*frames) = 0;
-            return paNoError;
-        }
-#endif
 
         /* select may modify the timeout parameter */
         selectTimeval.tv_usec = timeout;
@@ -1351,17 +1337,8 @@ static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *fr
             ENSURE_( -1, paUnanticipatedHostError );
         }
         */
-#ifdef PTHREAD_CANCELED
         pthread_testcancel();
-#else
-        /* avoid indefinite waiting on thread not supporting cancelation */
-        if( stream->callbackStop || stream->callbackAbort )
-        {
-            PA_DEBUG(( "Cancelling PaOssStream_WaitForFrames\n" ));
-            (*frames) = 0;
-            return paNoError;
-        }
-#endif
+
         if( pollCapture )
         {
             if( FD_ISSET( captureFd, &readFds ) )
@@ -1451,12 +1428,6 @@ static PaError PaOssStream_Prepare( PaOssStream *stream )
     if( stream->triggered )
         return result;
 
-    /* The OSS reference instructs us to clear direction bits before setting them.*/
-    if( stream->playback )
-        ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
-    if( stream->capture )
-        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
-
     if( stream->playback )
     {
         size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );
@@ -1507,29 +1478,17 @@ static PaError PaOssStream_Stop( PaOssStream *stream, int abort )
     PaError result = paNoError;
 
     /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.
-     * Also disable capture/playback till the stream is started again.
-     */
-    int captureErr = 0, playbackErr = 0;
+     * Also disable capture/playback till the stream is started again */
     if( stream->capture )
     {
-        if( (captureErr = ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 )) < 0 )
-        {
-            PA_DEBUG(( "%s: Failed to stop capture device, error: %d\n", __FUNCTION__, captureErr ));
-        }
+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );
     }
     if( stream->playback && !stream->sharedDevice )
     {
-        if( (playbackErr = ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 )) < 0 )
-        {
-            PA_DEBUG(( "%s: Failed to stop playback device, error: %d\n", __FUNCTION__, playbackErr ));
-        }
-    }
-
-    if( captureErr || playbackErr )
-    {
-        result = paUnanticipatedHostError;
+        ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );
     }
 
+error:
     return result;
 }
 
@@ -1622,15 +1581,8 @@ static void *PaOSS_AudioThreadProc( void *userData )
 
     while( 1 )
     {
-#ifdef PTHREAD_CANCELED
         pthread_testcancel();
-#else
-        if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancelation */
-        {
-            PA_DEBUG(( "Aborting callback thread\n" ));
-            break;
-        }
-#endif
+
         if( stream->callbackStop && callbackResult == paContinue )
         {
             PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
@@ -1657,21 +1609,8 @@ static void *PaOSS_AudioThreadProc( void *userData )
         {
             unsigned long frames = framesAvail;
 
-#ifdef PTHREAD_CANCELED
             pthread_testcancel();
-#else
-            if( stream->callbackStop )
-            {
-                PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
-                callbackResult = paComplete;
-            }
 
-            if( stream->callbackAbort ) /* avoid indefinite waiting on thread not supporting cancelation */
-            {
-                PA_DEBUG(( "Aborting callback thread\n" ));
-                break;
-            }
-#endif
             PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
 
             /* Read data */
@@ -1913,7 +1852,6 @@ static PaError ReadStream( PaStream* s,
                            void *buffer,
                            unsigned long frames )
 {
-    PaError result = paNoError;
     PaOssStream *stream = (PaOssStream*)s;
     int bytesRequested, bytesRead;
     unsigned long framesRequested;
@@ -1934,28 +1872,21 @@ static PaError ReadStream( PaStream* s,
         framesRequested = PA_MIN( frames, stream->capture->hostFrames );
 
 	bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );
-	ENSURE_( (bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested )),
-                 paUnanticipatedHostError );
+	bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested );
 	if ( bytesRequested != bytesRead )
-	{
-	    PA_DEBUG(( "Requested %d bytes, read %d\n", bytesRequested, bytesRead ));
 	    return paUnanticipatedHostError;
-	}
 
 	PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );
 	PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );
         PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );
 	frames -= framesRequested;
     }
-
-error:
-    return result;
+    return paNoError;
 }
 
 
 static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )
 {
-    PaError result = paNoError;
     PaOssStream *stream = (PaOssStream*)s;
     int bytesRequested, bytesWritten;
     unsigned long framesConverted;
@@ -1981,50 +1912,35 @@ static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frame
 	frames -= framesConverted;
 
 	bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );
-	ENSURE_( (bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested )),
-                 paUnanticipatedHostError );
+	bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested );
 
 	if ( bytesRequested != bytesWritten )
-	{
-	    PA_DEBUG(( "Requested %d bytes, wrote %d\n", bytesRequested, bytesWritten ));
 	    return paUnanticipatedHostError;
-	}
     }
-
-error:
-    return result;
+    return paNoError;
 }
 
 
 static signed long GetStreamReadAvailable( PaStream* s )
 {
-    PaError result = paNoError;
     PaOssStream *stream = (PaOssStream*)s;
     audio_buf_info info;
 
-    ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ), paUnanticipatedHostError );
+    if( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ) < 0 )
+        return paUnanticipatedHostError;
     return info.fragments * stream->capture->hostFrames;
-
-error:
-    return result;
 }
 
 
 /* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */
 static signed long GetStreamWriteAvailable( PaStream* s )
 {
-    PaError result = paNoError;
     PaOssStream *stream = (PaOssStream*)s;
     int delay = 0;
-#ifdef SNDCTL_DSP_GETODELAY
-    ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ), paUnanticipatedHostError );
-#endif
-    return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );
 
-/* Conditionally compile this to avoid warning about unused label */
-#ifdef SNDCTL_DSP_GETODELAY
-error:
-    return result;
-#endif
+    if( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ) < 0 )
+        return paUnanticipatedHostError;
+
+    return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );
 }
 
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/AudioSessionTypes.h b/portaudio/src/hostapi/wasapi/mingw-include/AudioSessionTypes.h
deleted file mode 100644
index 100111a09..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/AudioSessionTypes.h
+++ /dev/null
@@ -1,94 +0,0 @@
-//
-// AudioSessionTypes.h -- Copyright Microsoft Corporation, All Rights Reserved.
-//
-// Description: Type definitions used by the audio session manager RPC/COM interfaces
-//
-#pragma once
-
-#ifndef __AUDIOSESSIONTYPES__
-#define __AUDIOSESSIONTYPES__
-
-#if defined(__midl)
-#define MIDL_SIZE_IS(x) [size_is(x)]
-#define MIDL_STRING [string]
-#define MIDL_ANYSIZE_ARRAY
-#else   // !defined(__midl)
-#define MIDL_SIZE_IS(x)
-#define MIDL_STRING
-#define MIDL_ANYSIZE_ARRAY ANYSIZE_ARRAY
-#endif  // defined(__midl)
-
-//-------------------------------------------------------------------------
-// Description: AudioClient share mode
-//                                   
-//     AUDCLNT_SHAREMODE_SHARED -    The device will be opened in shared mode and use the 
-//                                   WAS format.
-//     AUDCLNT_SHAREMODE_EXCLUSIVE - The device will be opened in exclusive mode and use the 
-//                                   application specified format.
-//
-typedef enum _AUDCLNT_SHAREMODE
-{ 
-    AUDCLNT_SHAREMODE_SHARED, 
-    AUDCLNT_SHAREMODE_EXCLUSIVE 
-} AUDCLNT_SHAREMODE;
-
-//-------------------------------------------------------------------------
-// Description: AudioClient stream flags
-// 
-// Can be a combination of AUDCLNT_STREAMFLAGS and AUDCLNT_SYSFXFLAGS:
-// 
-// AUDCLNT_STREAMFLAGS (this group of flags uses the high word, w/exception of high-bit which is reserved, 0x7FFF0000):
-//                                  
-//     AUDCLNT_STREAMFLAGS_CROSSPROCESS - Audio policy control for this stream will be shared with 
-//                                        with other process sessions that use the same audio session 
-//                                        GUID.
-//     AUDCLNT_STREAMFLAGS_LOOPBACK -     Initializes a renderer endpoint for a loopback audio application. 
-//                                        In this mode, a capture stream will be opened on the specified 
-//                                        renderer endpoint. Shared mode and a renderer endpoint is required.
-//                                        Otherwise the IAudioClient::Initialize call will fail. If the 
-//                                        initialize is successful, a capture stream will be available 
-//                                        from the IAudioClient object.
-//
-//     AUDCLNT_STREAMFLAGS_EVENTCALLBACK - An exclusive mode client will supply an event handle that will be
-//                                         signaled when an IRP completes (or a waveRT buffer completes) telling
-//                                         it to fill the next buffer
-//
-//     AUDCLNT_STREAMFLAGS_NOPERSIST -    Session state will not be persisted
-//
-// AUDCLNT_SYSFXFLAGS (these flags use low word 0x0000FFFF):
-//
-//     none defined currently
-//
-#define AUDCLNT_STREAMFLAGS_CROSSPROCESS  0x00010000
-#define AUDCLNT_STREAMFLAGS_LOOPBACK      0x00020000
-#define AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000
-#define AUDCLNT_STREAMFLAGS_NOPERSIST     0x00080000
-
-//-------------------------------------------------------------------------
-// Description: Device share mode - sharing mode for the audio device.
-//
-//      DeviceShared - The device can be shared with other processes.
-//      DeviceExclusive - The device will only be used by this process.
-//
-typedef enum _DeviceShareMode
-{ 
-    DeviceShared, 
-    DeviceExclusive 
-} DeviceShareMode;
-
-
-//-------------------------------------------------------------------------
-// Description: AudioSession State.
-//
-//      AudioSessionStateInactive - The session has no active audio streams.
-//      AudioSessionStateActive - The session has active audio streams.
-//      AudioSessionStateExpired - The session is dormant.
-typedef enum _AudioSessionState
-{
-    AudioSessionStateInactive = 0,
-    AudioSessionStateActive = 1,
-    AudioSessionStateExpired = 2
-} AudioSessionState;
-
-#endif
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/FunctionDiscoveryKeys_devpkey.h b/portaudio/src/hostapi/wasapi/mingw-include/FunctionDiscoveryKeys_devpkey.h
deleted file mode 100644
index f015eaec3..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/FunctionDiscoveryKeys_devpkey.h
+++ /dev/null
@@ -1,186 +0,0 @@
-
-/*++
-
-Copyright (c) Microsoft Corporation.  All rights reserved.
-
-Module Name:
-
-    devpkey.h
-
-Abstract:
-
-    Defines property keys for the Plug and Play Device Property API.
-
-Author:
-
-    Jim Cavalaris (jamesca) 10-14-2003
-
-Environment:
-
-    User-mode only.
-
-Revision History:
-
-    14-October-2003     jamesca
-
-        Creation and initial implementation.
-
-    20-June-2006        dougb
-
-        Copied Jim's version replaced "DEFINE_DEVPROPKEY(DEVPKEY_" with "DEFINE_PROPERTYKEY(PKEY_"
-    
---*/
-
-//#include <devpropdef.h>
-
-//
-// _NAME
-//
-
-DEFINE_PROPERTYKEY(PKEY_NAME,                          0xb725f130, 0x47ef, 0x101a, 0xa5, 0xf1, 0x02, 0x60, 0x8c, 0x9e, 0xeb, 0xac, 10);    // DEVPROP_TYPE_STRING
-
-//
-// Device properties
-// These PKEYs correspond to the old setupapi SPDRP_XXX properties
-//
-DEFINE_PROPERTYKEY(PKEY_Device_DeviceDesc,             0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 2);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_HardwareIds,            0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 3);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_CompatibleIds,          0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 4);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_Service,                0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 6);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_Class,                  0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 9);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_ClassGuid,              0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 10);    // DEVPROP_TYPE_GUID
-DEFINE_PROPERTYKEY(PKEY_Device_Driver,                 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 11);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_ConfigFlags,            0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 12);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_Manufacturer,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 13);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_LocationInfo,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 15);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_PDOName,                0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 16);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_Capabilities,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 17);    // DEVPROP_TYPE_UNINT32
-DEFINE_PROPERTYKEY(PKEY_Device_UINumber,               0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 18);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_UpperFilters,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 19);    // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_LowerFilters,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 20);    // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_BusTypeGuid,            0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 21);    // DEVPROP_TYPE_GUID
-DEFINE_PROPERTYKEY(PKEY_Device_LegacyBusType,          0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 22);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_BusNumber,              0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 23);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_EnumeratorName,         0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 24);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_Security,               0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 25);    // DEVPROP_TYPE_SECURITY_DESCRIPTOR
-DEFINE_PROPERTYKEY(PKEY_Device_SecuritySDS,            0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 26);    // DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DevType,                0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 27);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_Exclusive,              0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 28);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_Characteristics,        0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 29);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_Address,                0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 30);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_UINumberDescFormat,     0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 31);    // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_PowerData,              0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 32);    // DEVPROP_TYPE_BINARY
-DEFINE_PROPERTYKEY(PKEY_Device_RemovalPolicy,          0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 33);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_RemovalPolicyDefault,   0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 34);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_RemovalPolicyOverride,  0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 35);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_InstallState,           0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 36);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_LocationPaths,          0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 37);    // DEVPROP_TYPE_STRING_LIST
-
-//
-// Device properties
-// These PKEYs correspond to a device's status and problem code
-//
-DEFINE_PROPERTYKEY(PKEY_Device_DevNodeStatus,          0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 2);     // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_ProblemCode,            0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 3);     // DEVPROP_TYPE_UINT32
-
-//
-// Device properties
-// These PKEYs correspond to device relations
-//
-DEFINE_PROPERTYKEY(PKEY_Device_EjectionRelations,      0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 4);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_RemovalRelations,       0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 5);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_PowerRelations,         0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 6);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_BusRelations,           0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 7);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_Parent,                 0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 8);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_Children,               0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 9);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_Siblings,               0x4340a6c5, 0x93fa, 0x4706, 0x97, 0x2c, 0x7b, 0x64, 0x80, 0x08, 0xa5, 0xa7, 10);    // DEVPROP_TYPE_STRING_LIST
-
-//
-// Other Device properties
-//
-DEFINE_PROPERTYKEY(PKEY_Device_Reported,               0x80497100, 0x8c73, 0x48b9, 0xaa, 0xd9, 0xce, 0x38, 0x7e, 0x19, 0xc5, 0x6e, 2);     // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_Device_Legacy,                 0x80497100, 0x8c73, 0x48b9, 0xaa, 0xd9, 0xce, 0x38, 0x7e, 0x19, 0xc5, 0x6e, 3);     // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_Device_InstanceId,             0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 256);   // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Numa_Proximity_Domain,         0x540b947e, 0x8b40, 0x45bc, 0xa8, 0xa2, 0x6a, 0x0b, 0x89, 0x4c, 0xbd, 0xa2, 1);     // DEVPROP_TYPE_UINT32
-
-//
-// Device driver properties
-//
-DEFINE_PROPERTYKEY(PKEY_Device_DriverDate,             0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 2);      // DEVPROP_TYPE_FILETIME
-DEFINE_PROPERTYKEY(PKEY_Device_DriverVersion,          0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 3);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverDesc,             0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 4);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverInfPath,          0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 5);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverInfSection,       0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 6);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverInfSectionExt,    0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 7);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_MatchingDeviceId,       0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 8);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverProvider,         0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 9);      // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverPropPageProvider, 0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 10);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverCoInstallers,     0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 11);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_Device_ResourcePickerTags,     0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 12);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_ResourcePickerExceptions, 0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 13); // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_Device_DriverRank,             0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 14);     // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_DriverLogoLevel,        0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 15);     // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_Device_NoConnectSound,         0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 17);     // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_Device_GenericDriverInstalled, 0xa8b865dd, 0x2e3d, 0x4094, 0xad, 0x97, 0xe5, 0x93, 0xa7, 0xc, 0x75, 0xd6, 18);     // DEVPROP_TYPE_BOOLEAN
-
-
-//
-// Device properties that were set by the driver package that was installed
-// on the device.
-//
-DEFINE_PROPERTYKEY(PKEY_DrvPkg_Model,                  0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32, 2);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DrvPkg_VendorWebSite,          0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32, 3);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DrvPkg_DetailedDescription,    0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32, 4);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DrvPkg_DocumentationLink,      0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32, 5);     // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DrvPkg_Icon,                   0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32, 6);     // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_DrvPkg_BrandingIcon,           0xcf73bb51, 0x3abf, 0x44a2, 0x85, 0xe0, 0x9a, 0x3d, 0xc7, 0xa1, 0x21, 0x32, 7);     // DEVPROP_TYPE_STRING_LIST
-
-//
-// Device setup class properties
-// These PKEYs correspond to the old setupapi SPCRP_XXX properties
-//
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_UpperFilters,      0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 19);    // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_LowerFilters,      0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 20);    // DEVPROP_TYPE_STRING_LIST
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_Security,          0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 25);    // DEVPROP_TYPE_SECURITY_DESCRIPTOR
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_SecuritySDS,       0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 26);    // DEVPROP_TYPE_SECURITY_DESCRIPTOR_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_DevType,           0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 27);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_Exclusive,         0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 28);    // DEVPROP_TYPE_UINT32
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_Characteristics,   0x4321918b, 0xf69e, 0x470d, 0xa5, 0xde, 0x4d, 0x88, 0xc7, 0x5a, 0xd2, 0x4b, 29);    // DEVPROP_TYPE_UINT32
-
-//
-// Device setup class properties
-// These PKEYs correspond to registry values under the device class GUID key
-//
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_Name,              0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 2);  // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_ClassName,         0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 3);  // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_Icon,              0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 4);  // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_ClassInstaller,    0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 5);  // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_PropPageProvider,  0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 6);  // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_NoInstallClass,    0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 7);  // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_NoDisplayClass,    0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 8);  // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_SilentInstall,     0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 9);  // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_NoUseClass,        0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 10); // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_DefaultService,    0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 11); // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_IconPath,          0x259abffc, 0x50a7, 0x47ce, 0xaf, 0x8, 0x68, 0xc9, 0xa7, 0xd7, 0x33, 0x66, 12); // DEVPROP_TYPE_STRING_LIST
-
-//
-// Other Device setup class properties
-//
-DEFINE_PROPERTYKEY(PKEY_DeviceClass_ClassCoInstallers, 0x713d1703, 0xa2e2, 0x49f5, 0x92, 0x14, 0x56, 0x47, 0x2e, 0xf3, 0xda, 0x5c, 2); // DEVPROP_TYPE_STRING_LIST
-
-//
-// Device interface properties
-//
-DEFINE_PROPERTYKEY(PKEY_DeviceInterface_FriendlyName,  0x026e516e, 0xb814, 0x414b, 0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22, 2); // DEVPROP_TYPE_STRING
-DEFINE_PROPERTYKEY(PKEY_DeviceInterface_Enabled,       0x026e516e, 0xb814, 0x414b, 0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22, 3); // DEVPROP_TYPE_BOOLEAN
-DEFINE_PROPERTYKEY(PKEY_DeviceInterface_ClassGuid,     0x026e516e, 0xb814, 0x414b, 0x83, 0xcd, 0x85, 0x6d, 0x6f, 0xef, 0x48, 0x22, 4); // DEVPROP_TYPE_GUID
-
-//
-// Device interface class properties
-//
-DEFINE_PROPERTYKEY(PKEY_DeviceInterfaceClass_DefaultInterface,  0x14c83a99, 0x0b3f, 0x44b7, 0xbe, 0x4c, 0xa1, 0x78, 0xd3, 0x99, 0x05, 0x64, 2); // DEVPROP_TYPE_STRING
-
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/audioclient.h b/portaudio/src/hostapi/wasapi/mingw-include/audioclient.h
deleted file mode 100644
index 3328c9d6b..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/audioclient.h
+++ /dev/null
@@ -1,1177 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for audioclient.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 500
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __audioclient_h__
-#define __audioclient_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-#ifndef __IAudioClient_FWD_DEFINED__
-#define __IAudioClient_FWD_DEFINED__
-typedef interface IAudioClient IAudioClient;
-#endif 	/* __IAudioClient_FWD_DEFINED__ */
-
-
-#ifndef __IAudioRenderClient_FWD_DEFINED__
-#define __IAudioRenderClient_FWD_DEFINED__
-typedef interface IAudioRenderClient IAudioRenderClient;
-#endif 	/* __IAudioRenderClient_FWD_DEFINED__ */
-
-
-#ifndef __IAudioCaptureClient_FWD_DEFINED__
-#define __IAudioCaptureClient_FWD_DEFINED__
-typedef interface IAudioCaptureClient IAudioCaptureClient;
-#endif 	/* __IAudioCaptureClient_FWD_DEFINED__ */
-
-
-#ifndef __IAudioClock_FWD_DEFINED__
-#define __IAudioClock_FWD_DEFINED__
-typedef interface IAudioClock IAudioClock;
-#endif 	/* __IAudioClock_FWD_DEFINED__ */
-
-
-#ifndef __ISimpleAudioVolume_FWD_DEFINED__
-#define __ISimpleAudioVolume_FWD_DEFINED__
-typedef interface ISimpleAudioVolume ISimpleAudioVolume;
-#endif 	/* __ISimpleAudioVolume_FWD_DEFINED__ */
-
-
-#ifndef __IAudioStreamVolume_FWD_DEFINED__
-#define __IAudioStreamVolume_FWD_DEFINED__
-typedef interface IAudioStreamVolume IAudioStreamVolume;
-#endif 	/* __IAudioStreamVolume_FWD_DEFINED__ */
-
-
-#ifndef __IChannelAudioVolume_FWD_DEFINED__
-#define __IChannelAudioVolume_FWD_DEFINED__
-typedef interface IChannelAudioVolume IChannelAudioVolume;
-#endif 	/* __IChannelAudioVolume_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "wtypes.h"
-#include "unknwn.h"
-#include "AudioSessionTypes.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_audioclient_0000_0000 */
-/* [local] */ 
-
-#if 0
-typedef /* [hidden][restricted] */ struct WAVEFORMATEX
-    {
-    WORD wFormatTag;
-    WORD nChannels;
-    DWORD nSamplesPerSec;
-    DWORD nAvgBytesPerSec;
-    WORD nBlockAlign;
-    WORD wBitsPerSample;
-    WORD cbSize;
-    } 	WAVEFORMATEX;
-
-#else
-#include <mmreg.h>
-#endif
-#if 0
-typedef /* [hidden][restricted] */ LONGLONG REFERENCE_TIME;
-
-#else
-#define _IKsControl_
-#include <ks.h>
-#include <ksmedia.h>
-#endif
-
-enum _AUDCLNT_BUFFERFLAGS
-    {	AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY	= 0x1,
-	AUDCLNT_BUFFERFLAGS_SILENT	= 0x2,
-	AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR	= 0x4
-    } ;
-
-
-extern RPC_IF_HANDLE __MIDL_itf_audioclient_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_audioclient_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IAudioClient_INTERFACE_DEFINED__
-#define __IAudioClient_INTERFACE_DEFINED__
-
-/* interface IAudioClient */
-/* [local][unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IAudioClient;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2")
-    IAudioClient : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Initialize( 
-            /* [in] */ 
-            __in  AUDCLNT_SHAREMODE ShareMode,
-            /* [in] */ 
-            __in  DWORD StreamFlags,
-            /* [in] */ 
-            __in  REFERENCE_TIME hnsBufferDuration,
-            /* [in] */ 
-            __in  REFERENCE_TIME hnsPeriodicity,
-            /* [in] */ 
-            __in  const WAVEFORMATEX *pFormat,
-            /* [in] */ 
-            __in_opt  LPCGUID AudioSessionGuid) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetBufferSize( 
-            /* [out] */ 
-            __out  UINT32 *pNumBufferFrames) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetStreamLatency( 
-            /* [out] */ 
-            __out  REFERENCE_TIME *phnsLatency) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetCurrentPadding( 
-            /* [out] */ 
-            __out  UINT32 *pNumPaddingFrames) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE IsFormatSupported( 
-            /* [in] */ 
-            __in  AUDCLNT_SHAREMODE ShareMode,
-            /* [in] */ 
-            __in  const WAVEFORMATEX *pFormat,
-            /* [unique][out] */ 
-            __out_opt  WAVEFORMATEX **ppClosestMatch) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetMixFormat( 
-            /* [out] */ 
-            __out  WAVEFORMATEX **ppDeviceFormat) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetDevicePeriod( 
-            /* [out] */ 
-            __out_opt  REFERENCE_TIME *phnsDefaultDevicePeriod,
-            /* [out] */ 
-            __out_opt  REFERENCE_TIME *phnsMinimumDevicePeriod) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Start( void) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Stop( void) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetEventHandle( 
-            /* [in] */ HANDLE eventHandle) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetService( 
-            /* [in] */ 
-            __in  REFIID riid,
-            /* [iid_is][out] */ 
-            __out  void **ppv) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioClientVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioClient * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioClient * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioClient * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Initialize )( 
-            IAudioClient * This,
-            /* [in] */ 
-            __in  AUDCLNT_SHAREMODE ShareMode,
-            /* [in] */ 
-            __in  DWORD StreamFlags,
-            /* [in] */ 
-            __in  REFERENCE_TIME hnsBufferDuration,
-            /* [in] */ 
-            __in  REFERENCE_TIME hnsPeriodicity,
-            /* [in] */ 
-            __in  const WAVEFORMATEX *pFormat,
-            /* [in] */ 
-            __in_opt  LPCGUID AudioSessionGuid);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetBufferSize )( 
-            IAudioClient * This,
-            /* [out] */ 
-            __out  UINT32 *pNumBufferFrames);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetStreamLatency )( 
-            IAudioClient * This,
-            /* [out] */ 
-            __out  REFERENCE_TIME *phnsLatency);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCurrentPadding )( 
-            IAudioClient * This,
-            /* [out] */ 
-            __out  UINT32 *pNumPaddingFrames);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsFormatSupported )( 
-            IAudioClient * This,
-            /* [in] */ 
-            __in  AUDCLNT_SHAREMODE ShareMode,
-            /* [in] */ 
-            __in  const WAVEFORMATEX *pFormat,
-            /* [unique][out] */ 
-            __out_opt  WAVEFORMATEX **ppClosestMatch);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetMixFormat )( 
-            IAudioClient * This,
-            /* [out] */ 
-            __out  WAVEFORMATEX **ppDeviceFormat);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDevicePeriod )( 
-            IAudioClient * This,
-            /* [out] */ 
-            __out_opt  REFERENCE_TIME *phnsDefaultDevicePeriod,
-            /* [out] */ 
-            __out_opt  REFERENCE_TIME *phnsMinimumDevicePeriod);
-        
-        HRESULT ( STDMETHODCALLTYPE *Start )( 
-            IAudioClient * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Stop )( 
-            IAudioClient * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Reset )( 
-            IAudioClient * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetEventHandle )( 
-            IAudioClient * This,
-            /* [in] */ HANDLE eventHandle);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetService )( 
-            IAudioClient * This,
-            /* [in] */ 
-            __in  REFIID riid,
-            /* [iid_is][out] */ 
-            __out  void **ppv);
-        
-        END_INTERFACE
-    } IAudioClientVtbl;
-
-    interface IAudioClient
-    {
-        CONST_VTBL struct IAudioClientVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioClient_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioClient_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioClient_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioClient_Initialize(This,ShareMode,StreamFlags,hnsBufferDuration,hnsPeriodicity,pFormat,AudioSessionGuid)	\
-    ( (This)->lpVtbl -> Initialize(This,ShareMode,StreamFlags,hnsBufferDuration,hnsPeriodicity,pFormat,AudioSessionGuid) ) 
-
-#define IAudioClient_GetBufferSize(This,pNumBufferFrames)	\
-    ( (This)->lpVtbl -> GetBufferSize(This,pNumBufferFrames) ) 
-
-#define IAudioClient_GetStreamLatency(This,phnsLatency)	\
-    ( (This)->lpVtbl -> GetStreamLatency(This,phnsLatency) ) 
-
-#define IAudioClient_GetCurrentPadding(This,pNumPaddingFrames)	\
-    ( (This)->lpVtbl -> GetCurrentPadding(This,pNumPaddingFrames) ) 
-
-#define IAudioClient_IsFormatSupported(This,ShareMode,pFormat,ppClosestMatch)	\
-    ( (This)->lpVtbl -> IsFormatSupported(This,ShareMode,pFormat,ppClosestMatch) ) 
-
-#define IAudioClient_GetMixFormat(This,ppDeviceFormat)	\
-    ( (This)->lpVtbl -> GetMixFormat(This,ppDeviceFormat) ) 
-
-#define IAudioClient_GetDevicePeriod(This,phnsDefaultDevicePeriod,phnsMinimumDevicePeriod)	\
-    ( (This)->lpVtbl -> GetDevicePeriod(This,phnsDefaultDevicePeriod,phnsMinimumDevicePeriod) ) 
-
-#define IAudioClient_Start(This)	\
-    ( (This)->lpVtbl -> Start(This) ) 
-
-#define IAudioClient_Stop(This)	\
-    ( (This)->lpVtbl -> Stop(This) ) 
-
-#define IAudioClient_Reset(This)	\
-    ( (This)->lpVtbl -> Reset(This) ) 
-
-#define IAudioClient_SetEventHandle(This,eventHandle)	\
-    ( (This)->lpVtbl -> SetEventHandle(This,eventHandle) ) 
-
-#define IAudioClient_GetService(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetService(This,riid,ppv) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioClient_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioRenderClient_INTERFACE_DEFINED__
-#define __IAudioRenderClient_INTERFACE_DEFINED__
-
-/* interface IAudioRenderClient */
-/* [local][unique][helpstring][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IAudioRenderClient;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("F294ACFC-3146-4483-A7BF-ADDCA7C260E2")
-    IAudioRenderClient : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetBuffer( 
-            /* [in] */ 
-            __in  UINT32 NumFramesRequested,
-            /* [out] */ 
-            __out  BYTE **ppData) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer( 
-            /* [in] */ 
-            __in  UINT32 NumFramesWritten,
-            /* [in] */ 
-            __in  DWORD dwFlags) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioRenderClientVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioRenderClient * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioRenderClient * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioRenderClient * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetBuffer )( 
-            IAudioRenderClient * This,
-            /* [in] */ 
-            __in  UINT32 NumFramesRequested,
-            /* [out] */ 
-            __out  BYTE **ppData);
-        
-        HRESULT ( STDMETHODCALLTYPE *ReleaseBuffer )( 
-            IAudioRenderClient * This,
-            /* [in] */ 
-            __in  UINT32 NumFramesWritten,
-            /* [in] */ 
-            __in  DWORD dwFlags);
-        
-        END_INTERFACE
-    } IAudioRenderClientVtbl;
-
-    interface IAudioRenderClient
-    {
-        CONST_VTBL struct IAudioRenderClientVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioRenderClient_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioRenderClient_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioRenderClient_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioRenderClient_GetBuffer(This,NumFramesRequested,ppData)	\
-    ( (This)->lpVtbl -> GetBuffer(This,NumFramesRequested,ppData) ) 
-
-#define IAudioRenderClient_ReleaseBuffer(This,NumFramesWritten,dwFlags)	\
-    ( (This)->lpVtbl -> ReleaseBuffer(This,NumFramesWritten,dwFlags) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioRenderClient_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioCaptureClient_INTERFACE_DEFINED__
-#define __IAudioCaptureClient_INTERFACE_DEFINED__
-
-/* interface IAudioCaptureClient */
-/* [local][unique][helpstring][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IAudioCaptureClient;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("C8ADBD64-E71E-48a0-A4DE-185C395CD317")
-    IAudioCaptureClient : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetBuffer( 
-            /* [out] */ 
-            __out  BYTE **ppData,
-            /* [out] */ 
-            __out  UINT32 *pNumFramesToRead,
-            /* [out] */ 
-            __out  DWORD *pdwFlags,
-            /* [unique][out] */ 
-            __out_opt  UINT64 *pu64DevicePosition,
-            /* [unique][out] */ 
-            __out_opt  UINT64 *pu64QPCPosition) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE ReleaseBuffer( 
-            /* [in] */ 
-            __in  UINT32 NumFramesRead) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetNextPacketSize( 
-            /* [out] */ 
-            __out  UINT32 *pNumFramesInNextPacket) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioCaptureClientVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioCaptureClient * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioCaptureClient * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioCaptureClient * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetBuffer )( 
-            IAudioCaptureClient * This,
-            /* [out] */ 
-            __out  BYTE **ppData,
-            /* [out] */ 
-            __out  UINT32 *pNumFramesToRead,
-            /* [out] */ 
-            __out  DWORD *pdwFlags,
-            /* [unique][out] */ 
-            __out_opt  UINT64 *pu64DevicePosition,
-            /* [unique][out] */ 
-            __out_opt  UINT64 *pu64QPCPosition);
-        
-        HRESULT ( STDMETHODCALLTYPE *ReleaseBuffer )( 
-            IAudioCaptureClient * This,
-            /* [in] */ 
-            __in  UINT32 NumFramesRead);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetNextPacketSize )( 
-            IAudioCaptureClient * This,
-            /* [out] */ 
-            __out  UINT32 *pNumFramesInNextPacket);
-        
-        END_INTERFACE
-    } IAudioCaptureClientVtbl;
-
-    interface IAudioCaptureClient
-    {
-        CONST_VTBL struct IAudioCaptureClientVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioCaptureClient_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioCaptureClient_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioCaptureClient_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioCaptureClient_GetBuffer(This,ppData,pNumFramesToRead,pdwFlags,pu64DevicePosition,pu64QPCPosition)	\
-    ( (This)->lpVtbl -> GetBuffer(This,ppData,pNumFramesToRead,pdwFlags,pu64DevicePosition,pu64QPCPosition) ) 
-
-#define IAudioCaptureClient_ReleaseBuffer(This,NumFramesRead)	\
-    ( (This)->lpVtbl -> ReleaseBuffer(This,NumFramesRead) ) 
-
-#define IAudioCaptureClient_GetNextPacketSize(This,pNumFramesInNextPacket)	\
-    ( (This)->lpVtbl -> GetNextPacketSize(This,pNumFramesInNextPacket) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioCaptureClient_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_audioclient_0000_0003 */
-/* [local] */ 
-
-#define AUDIOCLOCK_CHARACTERISTIC_FIXED_FREQ  0x00000001
-
-
-extern RPC_IF_HANDLE __MIDL_itf_audioclient_0000_0003_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_audioclient_0000_0003_v0_0_s_ifspec;
-
-#ifndef __IAudioClock_INTERFACE_DEFINED__
-#define __IAudioClock_INTERFACE_DEFINED__
-
-/* interface IAudioClock */
-/* [local][unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IAudioClock;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("CD63314F-3FBA-4a1b-812C-EF96358728E7")
-    IAudioClock : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetFrequency( 
-            /* [out] */ 
-            __out  UINT64 *pu64Frequency) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPosition( 
-            /* [out] */ 
-            __out  UINT64 *pu64Position,
-            /* [unique][out] */ 
-            __out_opt  UINT64 *pu64QPCPosition) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetCharacteristics( 
-            /* [out] */ 
-            __out  DWORD *pdwCharacteristics) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioClockVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioClock * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioClock * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioClock * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetFrequency )( 
-            IAudioClock * This,
-            /* [out] */ 
-            __out  UINT64 *pu64Frequency);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPosition )( 
-            IAudioClock * This,
-            /* [out] */ 
-            __out  UINT64 *pu64Position,
-            /* [unique][out] */ 
-            __out_opt  UINT64 *pu64QPCPosition);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCharacteristics )( 
-            IAudioClock * This,
-            /* [out] */ 
-            __out  DWORD *pdwCharacteristics);
-        
-        END_INTERFACE
-    } IAudioClockVtbl;
-
-    interface IAudioClock
-    {
-        CONST_VTBL struct IAudioClockVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioClock_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioClock_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioClock_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioClock_GetFrequency(This,pu64Frequency)	\
-    ( (This)->lpVtbl -> GetFrequency(This,pu64Frequency) ) 
-
-#define IAudioClock_GetPosition(This,pu64Position,pu64QPCPosition)	\
-    ( (This)->lpVtbl -> GetPosition(This,pu64Position,pu64QPCPosition) ) 
-
-#define IAudioClock_GetCharacteristics(This,pdwCharacteristics)	\
-    ( (This)->lpVtbl -> GetCharacteristics(This,pdwCharacteristics) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioClock_INTERFACE_DEFINED__ */
-
-
-#ifndef __ISimpleAudioVolume_INTERFACE_DEFINED__
-#define __ISimpleAudioVolume_INTERFACE_DEFINED__
-
-/* interface ISimpleAudioVolume */
-/* [local][unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_ISimpleAudioVolume;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("87CE5498-68D6-44E5-9215-6DA47EF883D8")
-    ISimpleAudioVolume : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE SetMasterVolume( 
-            /* [in] */ 
-            __in  float fLevel,
-            /* [unique][in] */ LPCGUID EventContext) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetMasterVolume( 
-            /* [out] */ 
-            __out  float *pfLevel) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetMute( 
-            /* [in] */ 
-            __in  const BOOL bMute,
-            /* [unique][in] */ LPCGUID EventContext) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetMute( 
-            /* [out] */ 
-            __out  BOOL *pbMute) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct ISimpleAudioVolumeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ISimpleAudioVolume * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ISimpleAudioVolume * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ISimpleAudioVolume * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetMasterVolume )( 
-            ISimpleAudioVolume * This,
-            /* [in] */ 
-            __in  float fLevel,
-            /* [unique][in] */ LPCGUID EventContext);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetMasterVolume )( 
-            ISimpleAudioVolume * This,
-            /* [out] */ 
-            __out  float *pfLevel);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetMute )( 
-            ISimpleAudioVolume * This,
-            /* [in] */ 
-            __in  const BOOL bMute,
-            /* [unique][in] */ LPCGUID EventContext);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetMute )( 
-            ISimpleAudioVolume * This,
-            /* [out] */ 
-            __out  BOOL *pbMute);
-        
-        END_INTERFACE
-    } ISimpleAudioVolumeVtbl;
-
-    interface ISimpleAudioVolume
-    {
-        CONST_VTBL struct ISimpleAudioVolumeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ISimpleAudioVolume_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ISimpleAudioVolume_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ISimpleAudioVolume_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define ISimpleAudioVolume_SetMasterVolume(This,fLevel,EventContext)	\
-    ( (This)->lpVtbl -> SetMasterVolume(This,fLevel,EventContext) ) 
-
-#define ISimpleAudioVolume_GetMasterVolume(This,pfLevel)	\
-    ( (This)->lpVtbl -> GetMasterVolume(This,pfLevel) ) 
-
-#define ISimpleAudioVolume_SetMute(This,bMute,EventContext)	\
-    ( (This)->lpVtbl -> SetMute(This,bMute,EventContext) ) 
-
-#define ISimpleAudioVolume_GetMute(This,pbMute)	\
-    ( (This)->lpVtbl -> GetMute(This,pbMute) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ISimpleAudioVolume_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioStreamVolume_INTERFACE_DEFINED__
-#define __IAudioStreamVolume_INTERFACE_DEFINED__
-
-/* interface IAudioStreamVolume */
-/* [local][unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IAudioStreamVolume;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("93014887-242D-4068-8A15-CF5E93B90FE3")
-    IAudioStreamVolume : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetChannelCount( 
-            /* [out] */ 
-            __out  UINT32 *pdwCount) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetChannelVolume( 
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [in] */ 
-            __in  const float fLevel) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetChannelVolume( 
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [out] */ 
-            __out  float *pfLevel) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetAllVolumes( 
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][in] */ 
-            __in_ecount(dwCount)  const float *pfVolumes) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAllVolumes( 
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][out] */ 
-            __out_ecount(dwCount)  float *pfVolumes) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioStreamVolumeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioStreamVolume * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioStreamVolume * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioStreamVolume * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioStreamVolume * This,
-            /* [out] */ 
-            __out  UINT32 *pdwCount);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetChannelVolume )( 
-            IAudioStreamVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [in] */ 
-            __in  const float fLevel);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetChannelVolume )( 
-            IAudioStreamVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [out] */ 
-            __out  float *pfLevel);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetAllVolumes )( 
-            IAudioStreamVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][in] */ 
-            __in_ecount(dwCount)  const float *pfVolumes);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAllVolumes )( 
-            IAudioStreamVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][out] */ 
-            __out_ecount(dwCount)  float *pfVolumes);
-        
-        END_INTERFACE
-    } IAudioStreamVolumeVtbl;
-
-    interface IAudioStreamVolume
-    {
-        CONST_VTBL struct IAudioStreamVolumeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioStreamVolume_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioStreamVolume_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioStreamVolume_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioStreamVolume_GetChannelCount(This,pdwCount)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pdwCount) ) 
-
-#define IAudioStreamVolume_SetChannelVolume(This,dwIndex,fLevel)	\
-    ( (This)->lpVtbl -> SetChannelVolume(This,dwIndex,fLevel) ) 
-
-#define IAudioStreamVolume_GetChannelVolume(This,dwIndex,pfLevel)	\
-    ( (This)->lpVtbl -> GetChannelVolume(This,dwIndex,pfLevel) ) 
-
-#define IAudioStreamVolume_SetAllVolumes(This,dwCount,pfVolumes)	\
-    ( (This)->lpVtbl -> SetAllVolumes(This,dwCount,pfVolumes) ) 
-
-#define IAudioStreamVolume_GetAllVolumes(This,dwCount,pfVolumes)	\
-    ( (This)->lpVtbl -> GetAllVolumes(This,dwCount,pfVolumes) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioStreamVolume_INTERFACE_DEFINED__ */
-
-
-#ifndef __IChannelAudioVolume_INTERFACE_DEFINED__
-#define __IChannelAudioVolume_INTERFACE_DEFINED__
-
-/* interface IChannelAudioVolume */
-/* [local][unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IChannelAudioVolume;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("1C158861-B533-4B30-B1CF-E853E51C59B8")
-    IChannelAudioVolume : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetChannelCount( 
-            /* [out] */ 
-            __out  UINT32 *pdwCount) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetChannelVolume( 
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [in] */ 
-            __in  const float fLevel,
-            /* [unique][in] */ LPCGUID EventContext) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetChannelVolume( 
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [out] */ 
-            __out  float *pfLevel) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetAllVolumes( 
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][in] */ 
-            __in_ecount(dwCount)  const float *pfVolumes,
-            /* [unique][in] */ LPCGUID EventContext) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAllVolumes( 
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][out] */ 
-            __out_ecount(dwCount)  float *pfVolumes) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IChannelAudioVolumeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IChannelAudioVolume * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IChannelAudioVolume * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IChannelAudioVolume * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IChannelAudioVolume * This,
-            /* [out] */ 
-            __out  UINT32 *pdwCount);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetChannelVolume )( 
-            IChannelAudioVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [in] */ 
-            __in  const float fLevel,
-            /* [unique][in] */ LPCGUID EventContext);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetChannelVolume )( 
-            IChannelAudioVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwIndex,
-            /* [out] */ 
-            __out  float *pfLevel);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetAllVolumes )( 
-            IChannelAudioVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][in] */ 
-            __in_ecount(dwCount)  const float *pfVolumes,
-            /* [unique][in] */ LPCGUID EventContext);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAllVolumes )( 
-            IChannelAudioVolume * This,
-            /* [in] */ 
-            __in  UINT32 dwCount,
-            /* [size_is][out] */ 
-            __out_ecount(dwCount)  float *pfVolumes);
-        
-        END_INTERFACE
-    } IChannelAudioVolumeVtbl;
-
-    interface IChannelAudioVolume
-    {
-        CONST_VTBL struct IChannelAudioVolumeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IChannelAudioVolume_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IChannelAudioVolume_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IChannelAudioVolume_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IChannelAudioVolume_GetChannelCount(This,pdwCount)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pdwCount) ) 
-
-#define IChannelAudioVolume_SetChannelVolume(This,dwIndex,fLevel,EventContext)	\
-    ( (This)->lpVtbl -> SetChannelVolume(This,dwIndex,fLevel,EventContext) ) 
-
-#define IChannelAudioVolume_GetChannelVolume(This,dwIndex,pfLevel)	\
-    ( (This)->lpVtbl -> GetChannelVolume(This,dwIndex,pfLevel) ) 
-
-#define IChannelAudioVolume_SetAllVolumes(This,dwCount,pfVolumes,EventContext)	\
-    ( (This)->lpVtbl -> SetAllVolumes(This,dwCount,pfVolumes,EventContext) ) 
-
-#define IChannelAudioVolume_GetAllVolumes(This,dwCount,pfVolumes)	\
-    ( (This)->lpVtbl -> GetAllVolumes(This,dwCount,pfVolumes) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IChannelAudioVolume_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_audioclient_0000_0007 */
-/* [local] */ 
-
-#define FACILITY_AUDCLNT 0x889
-#define AUDCLNT_ERR(n) MAKE_HRESULT(SEVERITY_ERROR, FACILITY_AUDCLNT, n)
-#define AUDCLNT_SUCCESS(n) MAKE_SCODE(SEVERITY_SUCCESS, FACILITY_AUDCLNT, n)
-#define AUDCLNT_E_NOT_INITIALIZED            AUDCLNT_ERR(0x001)
-#define AUDCLNT_E_ALREADY_INITIALIZED        AUDCLNT_ERR(0x002)
-#define AUDCLNT_E_WRONG_ENDPOINT_TYPE        AUDCLNT_ERR(0x003)
-#define AUDCLNT_E_DEVICE_INVALIDATED         AUDCLNT_ERR(0x004)
-#define AUDCLNT_E_NOT_STOPPED                AUDCLNT_ERR(0x005)
-#define AUDCLNT_E_BUFFER_TOO_LARGE           AUDCLNT_ERR(0x006)
-#define AUDCLNT_E_OUT_OF_ORDER               AUDCLNT_ERR(0x007)
-#define AUDCLNT_E_UNSUPPORTED_FORMAT         AUDCLNT_ERR(0x008)
-#define AUDCLNT_E_INVALID_SIZE               AUDCLNT_ERR(0x009)
-#define AUDCLNT_E_DEVICE_IN_USE              AUDCLNT_ERR(0x00a)
-#define AUDCLNT_E_BUFFER_OPERATION_PENDING   AUDCLNT_ERR(0x00b)
-#define AUDCLNT_E_THREAD_NOT_REGISTERED      AUDCLNT_ERR(0x00c)
-#define AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED AUDCLNT_ERR(0x00e)
-#define AUDCLNT_E_ENDPOINT_CREATE_FAILED     AUDCLNT_ERR(0x00f)
-#define AUDCLNT_E_SERVICE_NOT_RUNNING        AUDCLNT_ERR(0x010)
-#define AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED     AUDCLNT_ERR(0x011)
-#define AUDCLNT_E_EXCLUSIVE_MODE_ONLY          AUDCLNT_ERR(0x012)
-#define AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL AUDCLNT_ERR(0x013)
-#define AUDCLNT_E_EVENTHANDLE_NOT_SET          AUDCLNT_ERR(0x014)
-#define AUDCLNT_E_INCORRECT_BUFFER_SIZE        AUDCLNT_ERR(0x015)
-#define AUDCLNT_E_BUFFER_SIZE_ERROR            AUDCLNT_ERR(0x016)
-#define AUDCLNT_E_CPUUSAGE_EXCEEDED            AUDCLNT_ERR(0x017)
-#define AUDCLNT_S_BUFFER_EMPTY              AUDCLNT_SUCCESS(0x001)
-#define AUDCLNT_S_THREAD_ALREADY_REGISTERED AUDCLNT_SUCCESS(0x002)
-#define AUDCLNT_S_POSITION_STALLED		   AUDCLNT_SUCCESS(0x003)
-
-
-extern RPC_IF_HANDLE __MIDL_itf_audioclient_0000_0007_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_audioclient_0000_0007_v0_0_s_ifspec;
-
-/* Additional Prototypes for ALL interfaces */
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/devicetopology.h b/portaudio/src/hostapi/wasapi/mingw-include/devicetopology.h
deleted file mode 100644
index 1002ba0b5..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/devicetopology.h
+++ /dev/null
@@ -1,3275 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for devicetopology.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 500
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __devicetopology_h__
-#define __devicetopology_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-#ifndef __IKsControl_FWD_DEFINED__
-#define __IKsControl_FWD_DEFINED__
-typedef interface IKsControl IKsControl;
-#endif 	/* __IKsControl_FWD_DEFINED__ */
-
-
-#ifndef __IPerChannelDbLevel_FWD_DEFINED__
-#define __IPerChannelDbLevel_FWD_DEFINED__
-typedef interface IPerChannelDbLevel IPerChannelDbLevel;
-#endif 	/* __IPerChannelDbLevel_FWD_DEFINED__ */
-
-
-#ifndef __IAudioVolumeLevel_FWD_DEFINED__
-#define __IAudioVolumeLevel_FWD_DEFINED__
-typedef interface IAudioVolumeLevel IAudioVolumeLevel;
-#endif 	/* __IAudioVolumeLevel_FWD_DEFINED__ */
-
-
-#ifndef __IAudioChannelConfig_FWD_DEFINED__
-#define __IAudioChannelConfig_FWD_DEFINED__
-typedef interface IAudioChannelConfig IAudioChannelConfig;
-#endif 	/* __IAudioChannelConfig_FWD_DEFINED__ */
-
-
-#ifndef __IAudioLoudness_FWD_DEFINED__
-#define __IAudioLoudness_FWD_DEFINED__
-typedef interface IAudioLoudness IAudioLoudness;
-#endif 	/* __IAudioLoudness_FWD_DEFINED__ */
-
-
-#ifndef __IAudioInputSelector_FWD_DEFINED__
-#define __IAudioInputSelector_FWD_DEFINED__
-typedef interface IAudioInputSelector IAudioInputSelector;
-#endif 	/* __IAudioInputSelector_FWD_DEFINED__ */
-
-
-#ifndef __IAudioOutputSelector_FWD_DEFINED__
-#define __IAudioOutputSelector_FWD_DEFINED__
-typedef interface IAudioOutputSelector IAudioOutputSelector;
-#endif 	/* __IAudioOutputSelector_FWD_DEFINED__ */
-
-
-#ifndef __IAudioMute_FWD_DEFINED__
-#define __IAudioMute_FWD_DEFINED__
-typedef interface IAudioMute IAudioMute;
-#endif 	/* __IAudioMute_FWD_DEFINED__ */
-
-
-#ifndef __IAudioBass_FWD_DEFINED__
-#define __IAudioBass_FWD_DEFINED__
-typedef interface IAudioBass IAudioBass;
-#endif 	/* __IAudioBass_FWD_DEFINED__ */
-
-
-#ifndef __IAudioMidrange_FWD_DEFINED__
-#define __IAudioMidrange_FWD_DEFINED__
-typedef interface IAudioMidrange IAudioMidrange;
-#endif 	/* __IAudioMidrange_FWD_DEFINED__ */
-
-
-#ifndef __IAudioTreble_FWD_DEFINED__
-#define __IAudioTreble_FWD_DEFINED__
-typedef interface IAudioTreble IAudioTreble;
-#endif 	/* __IAudioTreble_FWD_DEFINED__ */
-
-
-#ifndef __IAudioAutoGainControl_FWD_DEFINED__
-#define __IAudioAutoGainControl_FWD_DEFINED__
-typedef interface IAudioAutoGainControl IAudioAutoGainControl;
-#endif 	/* __IAudioAutoGainControl_FWD_DEFINED__ */
-
-
-#ifndef __IAudioPeakMeter_FWD_DEFINED__
-#define __IAudioPeakMeter_FWD_DEFINED__
-typedef interface IAudioPeakMeter IAudioPeakMeter;
-#endif 	/* __IAudioPeakMeter_FWD_DEFINED__ */
-
-
-#ifndef __IDeviceSpecificProperty_FWD_DEFINED__
-#define __IDeviceSpecificProperty_FWD_DEFINED__
-typedef interface IDeviceSpecificProperty IDeviceSpecificProperty;
-#endif 	/* __IDeviceSpecificProperty_FWD_DEFINED__ */
-
-
-#ifndef __IKsFormatSupport_FWD_DEFINED__
-#define __IKsFormatSupport_FWD_DEFINED__
-typedef interface IKsFormatSupport IKsFormatSupport;
-#endif 	/* __IKsFormatSupport_FWD_DEFINED__ */
-
-
-#ifndef __IKsJackDescription_FWD_DEFINED__
-#define __IKsJackDescription_FWD_DEFINED__
-typedef interface IKsJackDescription IKsJackDescription;
-#endif 	/* __IKsJackDescription_FWD_DEFINED__ */
-
-
-#ifndef __IPartsList_FWD_DEFINED__
-#define __IPartsList_FWD_DEFINED__
-typedef interface IPartsList IPartsList;
-#endif 	/* __IPartsList_FWD_DEFINED__ */
-
-
-#ifndef __IPart_FWD_DEFINED__
-#define __IPart_FWD_DEFINED__
-typedef interface IPart IPart;
-#endif 	/* __IPart_FWD_DEFINED__ */
-
-
-#ifndef __IConnector_FWD_DEFINED__
-#define __IConnector_FWD_DEFINED__
-typedef interface IConnector IConnector;
-#endif 	/* __IConnector_FWD_DEFINED__ */
-
-
-#ifndef __ISubunit_FWD_DEFINED__
-#define __ISubunit_FWD_DEFINED__
-typedef interface ISubunit ISubunit;
-#endif 	/* __ISubunit_FWD_DEFINED__ */
-
-
-#ifndef __IControlInterface_FWD_DEFINED__
-#define __IControlInterface_FWD_DEFINED__
-typedef interface IControlInterface IControlInterface;
-#endif 	/* __IControlInterface_FWD_DEFINED__ */
-
-
-#ifndef __IControlChangeNotify_FWD_DEFINED__
-#define __IControlChangeNotify_FWD_DEFINED__
-typedef interface IControlChangeNotify IControlChangeNotify;
-#endif 	/* __IControlChangeNotify_FWD_DEFINED__ */
-
-
-#ifndef __IDeviceTopology_FWD_DEFINED__
-#define __IDeviceTopology_FWD_DEFINED__
-typedef interface IDeviceTopology IDeviceTopology;
-#endif 	/* __IDeviceTopology_FWD_DEFINED__ */
-
-
-#ifndef __DeviceTopology_FWD_DEFINED__
-#define __DeviceTopology_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class DeviceTopology DeviceTopology;
-#else
-typedef struct DeviceTopology DeviceTopology;
-#endif /* __cplusplus */
-
-#endif 	/* __DeviceTopology_FWD_DEFINED__ */
-
-
-#ifndef __IPartsList_FWD_DEFINED__
-#define __IPartsList_FWD_DEFINED__
-typedef interface IPartsList IPartsList;
-#endif 	/* __IPartsList_FWD_DEFINED__ */
-
-
-#ifndef __IPerChannelDbLevel_FWD_DEFINED__
-#define __IPerChannelDbLevel_FWD_DEFINED__
-typedef interface IPerChannelDbLevel IPerChannelDbLevel;
-#endif 	/* __IPerChannelDbLevel_FWD_DEFINED__ */
-
-
-#ifndef __IAudioVolumeLevel_FWD_DEFINED__
-#define __IAudioVolumeLevel_FWD_DEFINED__
-typedef interface IAudioVolumeLevel IAudioVolumeLevel;
-#endif 	/* __IAudioVolumeLevel_FWD_DEFINED__ */
-
-
-#ifndef __IAudioLoudness_FWD_DEFINED__
-#define __IAudioLoudness_FWD_DEFINED__
-typedef interface IAudioLoudness IAudioLoudness;
-#endif 	/* __IAudioLoudness_FWD_DEFINED__ */
-
-
-#ifndef __IAudioInputSelector_FWD_DEFINED__
-#define __IAudioInputSelector_FWD_DEFINED__
-typedef interface IAudioInputSelector IAudioInputSelector;
-#endif 	/* __IAudioInputSelector_FWD_DEFINED__ */
-
-
-#ifndef __IAudioMute_FWD_DEFINED__
-#define __IAudioMute_FWD_DEFINED__
-typedef interface IAudioMute IAudioMute;
-#endif 	/* __IAudioMute_FWD_DEFINED__ */
-
-
-#ifndef __IAudioBass_FWD_DEFINED__
-#define __IAudioBass_FWD_DEFINED__
-typedef interface IAudioBass IAudioBass;
-#endif 	/* __IAudioBass_FWD_DEFINED__ */
-
-
-#ifndef __IAudioMidrange_FWD_DEFINED__
-#define __IAudioMidrange_FWD_DEFINED__
-typedef interface IAudioMidrange IAudioMidrange;
-#endif 	/* __IAudioMidrange_FWD_DEFINED__ */
-
-
-#ifndef __IAudioTreble_FWD_DEFINED__
-#define __IAudioTreble_FWD_DEFINED__
-typedef interface IAudioTreble IAudioTreble;
-#endif 	/* __IAudioTreble_FWD_DEFINED__ */
-
-
-#ifndef __IAudioAutoGainControl_FWD_DEFINED__
-#define __IAudioAutoGainControl_FWD_DEFINED__
-typedef interface IAudioAutoGainControl IAudioAutoGainControl;
-#endif 	/* __IAudioAutoGainControl_FWD_DEFINED__ */
-
-
-#ifndef __IAudioOutputSelector_FWD_DEFINED__
-#define __IAudioOutputSelector_FWD_DEFINED__
-typedef interface IAudioOutputSelector IAudioOutputSelector;
-#endif 	/* __IAudioOutputSelector_FWD_DEFINED__ */
-
-
-#ifndef __IAudioPeakMeter_FWD_DEFINED__
-#define __IAudioPeakMeter_FWD_DEFINED__
-typedef interface IAudioPeakMeter IAudioPeakMeter;
-#endif 	/* __IAudioPeakMeter_FWD_DEFINED__ */
-
-
-#ifndef __IDeviceSpecificProperty_FWD_DEFINED__
-#define __IDeviceSpecificProperty_FWD_DEFINED__
-typedef interface IDeviceSpecificProperty IDeviceSpecificProperty;
-#endif 	/* __IDeviceSpecificProperty_FWD_DEFINED__ */
-
-
-#ifndef __IKsFormatSupport_FWD_DEFINED__
-#define __IKsFormatSupport_FWD_DEFINED__
-typedef interface IKsFormatSupport IKsFormatSupport;
-#endif 	/* __IKsFormatSupport_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "oaidl.h"
-#include "ocidl.h"
-#include "propidl.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_devicetopology_0000_0000 */
-/* [local] */ 
-
-#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
-//
-//   Flag for clients of IControlChangeNotify::OnNotify to allow those clients to identify hardware initiated notifications
-//
-#define DEVTOPO_HARDWARE_INITIATED_EVENTCONTEXT 'draH'
-/* E2C2E9DE-09B1-4B04-84E5-07931225EE04 */
-DEFINE_GUID(EVENTCONTEXT_VOLUMESLIDER, 0xE2C2E9DE,0x09B1,0x4B04,0x84, 0xE5, 0x07, 0x93, 0x12, 0x25, 0xEE, 0x04);
-#define _IKsControl_
-#include "ks.h"
-#include "ksmedia.h"
-#ifndef _KS_
-typedef /* [public] */ struct __MIDL___MIDL_itf_devicetopology_0000_0000_0001
-    {
-    ULONG FormatSize;
-    ULONG Flags;
-    ULONG SampleSize;
-    ULONG Reserved;
-    GUID MajorFormat;
-    GUID SubFormat;
-    GUID Specifier;
-    } 	KSDATAFORMAT;
-
-typedef struct __MIDL___MIDL_itf_devicetopology_0000_0000_0001 *PKSDATAFORMAT;
-
-typedef /* [public][public][public][public][public][public][public][public][public][public] */ struct __MIDL___MIDL_itf_devicetopology_0000_0000_0002
-    {
-    union 
-        {
-        struct 
-            {
-            GUID Set;
-            ULONG Id;
-            ULONG Flags;
-            } 	;
-        LONGLONG Alignment;
-        } 	;
-    } 	KSIDENTIFIER;
-
-typedef struct __MIDL___MIDL_itf_devicetopology_0000_0000_0002 *PKSIDENTIFIER;
-
-typedef /* [public][public][public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0005
-    {	ePcxChanMap_FL_FR	= 0,
-	ePcxChanMap_FC_LFE	= ( ePcxChanMap_FL_FR + 1 ) ,
-	ePcxChanMap_BL_BR	= ( ePcxChanMap_FC_LFE + 1 ) ,
-	ePcxChanMap_FLC_FRC	= ( ePcxChanMap_BL_BR + 1 ) ,
-	ePcxChanMap_SL_SR	= ( ePcxChanMap_FLC_FRC + 1 ) ,
-	ePcxChanMap_Unknown	= ( ePcxChanMap_SL_SR + 1 ) 
-    } 	EChannelMapping;
-
-typedef /* [public][public][public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0006
-    {	eConnTypeUnknown	= 0,
-	eConnTypeEighth	= ( eConnTypeUnknown + 1 ) ,
-	eConnTypeQuarter	= ( eConnTypeEighth + 1 ) ,
-	eConnTypeAtapiInternal	= ( eConnTypeQuarter + 1 ) ,
-	eConnTypeRCA	= ( eConnTypeAtapiInternal + 1 ) ,
-	eConnTypeOptical	= ( eConnTypeRCA + 1 ) ,
-	eConnTypeOtherDigital	= ( eConnTypeOptical + 1 ) ,
-	eConnTypeOtherAnalog	= ( eConnTypeOtherDigital + 1 ) ,
-	eConnTypeMultichannelAnalogDIN	= ( eConnTypeOtherAnalog + 1 ) ,
-	eConnTypeXlrProfessional	= ( eConnTypeMultichannelAnalogDIN + 1 ) ,
-	eConnTypeRJ11Modem	= ( eConnTypeXlrProfessional + 1 ) ,
-	eConnTypeCombination	= ( eConnTypeRJ11Modem + 1 ) 
-    } 	EPcxConnectionType;
-
-typedef /* [public][public][public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0007
-    {	eGeoLocRear	= 0x1,
-	eGeoLocFront	= ( eGeoLocRear + 1 ) ,
-	eGeoLocLeft	= ( eGeoLocFront + 1 ) ,
-	eGeoLocRight	= ( eGeoLocLeft + 1 ) ,
-	eGeoLocTop	= ( eGeoLocRight + 1 ) ,
-	eGeoLocBottom	= ( eGeoLocTop + 1 ) ,
-	eGeoLocRearOPanel	= ( eGeoLocBottom + 1 ) ,
-	eGeoLocRiser	= ( eGeoLocRearOPanel + 1 ) ,
-	eGeoLocInsideMobileLid	= ( eGeoLocRiser + 1 ) ,
-	eGeoLocDrivebay	= ( eGeoLocInsideMobileLid + 1 ) ,
-	eGeoLocHDMI	= ( eGeoLocDrivebay + 1 ) ,
-	eGeoLocOutsideMobileLid	= ( eGeoLocHDMI + 1 ) ,
-	eGeoLocATAPI	= ( eGeoLocOutsideMobileLid + 1 ) ,
-	eGeoLocReserved5	= ( eGeoLocATAPI + 1 ) ,
-	eGeoLocReserved6	= ( eGeoLocReserved5 + 1 ) 
-    } 	EPcxGeoLocation;
-
-typedef /* [public][public][public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0008
-    {	eGenLocPrimaryBox	= 0,
-	eGenLocInternal	= ( eGenLocPrimaryBox + 1 ) ,
-	eGenLocSeperate	= ( eGenLocInternal + 1 ) ,
-	eGenLocOther	= ( eGenLocSeperate + 1 ) 
-    } 	EPcxGenLocation;
-
-typedef /* [public][public][public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0009
-    {	ePortConnJack	= 0,
-	ePortConnIntegratedDevice	= ( ePortConnJack + 1 ) ,
-	ePortConnBothIntegratedAndJack	= ( ePortConnIntegratedDevice + 1 ) ,
-	ePortConnUnknown	= ( ePortConnBothIntegratedAndJack + 1 ) 
-    } 	EPxcPortConnection;
-
-typedef /* [public][public] */ struct __MIDL___MIDL_itf_devicetopology_0000_0000_0010
-    {
-    EChannelMapping ChannelMapping;
-    COLORREF Color;
-    EPcxConnectionType ConnectionType;
-    EPcxGeoLocation GeoLocation;
-    EPcxGenLocation GenLocation;
-    EPxcPortConnection PortConnection;
-    BOOL IsConnected;
-    } 	KSJACK_DESCRIPTION;
-
-typedef struct __MIDL___MIDL_itf_devicetopology_0000_0000_0010 *PKSJACK_DESCRIPTION;
-
-typedef KSIDENTIFIER KSPROPERTY;
-
-typedef KSIDENTIFIER *PKSPROPERTY;
-
-typedef KSIDENTIFIER KSMETHOD;
-
-typedef KSIDENTIFIER *PKSMETHOD;
-
-typedef KSIDENTIFIER KSEVENT;
-
-typedef KSIDENTIFIER *PKSEVENT;
-
-#endif
-
-
-
-
-
-
-
-
-typedef /* [public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0011
-    {	In	= 0,
-	Out	= ( In + 1 ) 
-    } 	DataFlow;
-
-typedef /* [public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0012
-    {	Connector	= 0,
-	Subunit	= ( Connector + 1 ) 
-    } 	PartType;
-
-#define PARTTYPE_FLAG_CONNECTOR 0x00010000
-#define PARTTYPE_FLAG_SUBUNIT   0x00020000
-#define PARTTYPE_MASK           0x00030000
-#define PARTID_MASK             0x0000ffff
-typedef /* [public][public] */ 
-enum __MIDL___MIDL_itf_devicetopology_0000_0000_0013
-    {	Unknown_Connector	= 0,
-	Physical_Internal	= ( Unknown_Connector + 1 ) ,
-	Physical_External	= ( Physical_Internal + 1 ) ,
-	Software_IO	= ( Physical_External + 1 ) ,
-	Software_Fixed	= ( Software_IO + 1 ) ,
-	Network	= ( Software_Fixed + 1 ) 
-    } 	ConnectorType;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_devicetopology_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_devicetopology_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IKsControl_INTERFACE_DEFINED__
-#define __IKsControl_INTERFACE_DEFINED__
-
-/* interface IKsControl */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IKsControl;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("28F54685-06FD-11D2-B27A-00A0C9223196")
-    IKsControl : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE KsProperty( 
-            /* [in] */ PKSPROPERTY Property,
-            /* [in] */ ULONG PropertyLength,
-            /* [out][in] */ void *PropertyData,
-            /* [in] */ ULONG DataLength,
-            /* [out] */ ULONG *BytesReturned) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE KsMethod( 
-            /* [in] */ PKSMETHOD Method,
-            /* [in] */ ULONG MethodLength,
-            /* [out][in] */ void *MethodData,
-            /* [in] */ ULONG DataLength,
-            /* [out] */ ULONG *BytesReturned) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE KsEvent( 
-            /* [in] */ PKSEVENT Event,
-            /* [in] */ ULONG EventLength,
-            /* [out][in] */ void *EventData,
-            /* [in] */ ULONG DataLength,
-            /* [out] */ ULONG *BytesReturned) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IKsControlVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IKsControl * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IKsControl * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IKsControl * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *KsProperty )( 
-            IKsControl * This,
-            /* [in] */ PKSPROPERTY Property,
-            /* [in] */ ULONG PropertyLength,
-            /* [out][in] */ void *PropertyData,
-            /* [in] */ ULONG DataLength,
-            /* [out] */ ULONG *BytesReturned);
-        
-        HRESULT ( STDMETHODCALLTYPE *KsMethod )( 
-            IKsControl * This,
-            /* [in] */ PKSMETHOD Method,
-            /* [in] */ ULONG MethodLength,
-            /* [out][in] */ void *MethodData,
-            /* [in] */ ULONG DataLength,
-            /* [out] */ ULONG *BytesReturned);
-        
-        HRESULT ( STDMETHODCALLTYPE *KsEvent )( 
-            IKsControl * This,
-            /* [in] */ PKSEVENT Event,
-            /* [in] */ ULONG EventLength,
-            /* [out][in] */ void *EventData,
-            /* [in] */ ULONG DataLength,
-            /* [out] */ ULONG *BytesReturned);
-        
-        END_INTERFACE
-    } IKsControlVtbl;
-
-    interface IKsControl
-    {
-        CONST_VTBL struct IKsControlVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IKsControl_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IKsControl_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IKsControl_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IKsControl_KsProperty(This,Property,PropertyLength,PropertyData,DataLength,BytesReturned)	\
-    ( (This)->lpVtbl -> KsProperty(This,Property,PropertyLength,PropertyData,DataLength,BytesReturned) ) 
-
-#define IKsControl_KsMethod(This,Method,MethodLength,MethodData,DataLength,BytesReturned)	\
-    ( (This)->lpVtbl -> KsMethod(This,Method,MethodLength,MethodData,DataLength,BytesReturned) ) 
-
-#define IKsControl_KsEvent(This,Event,EventLength,EventData,DataLength,BytesReturned)	\
-    ( (This)->lpVtbl -> KsEvent(This,Event,EventLength,EventData,DataLength,BytesReturned) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IKsControl_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPerChannelDbLevel_INTERFACE_DEFINED__
-#define __IPerChannelDbLevel_INTERFACE_DEFINED__
-
-/* interface IPerChannelDbLevel */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IPerChannelDbLevel;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("C2F8E001-F205-4BC9-99BC-C13B1E048CCB")
-    IPerChannelDbLevel : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetChannelCount( 
-            /* [out] */ 
-            __out  UINT *pcChannels) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLevelRange( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfMinLevelDB,
-            /* [out] */ 
-            __out  float *pfMaxLevelDB,
-            /* [out] */ 
-            __out  float *pfStepping) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLevel( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetLevel( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetLevelUniform( 
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetLevelAllChannels( 
-            /* [size_is][in] */ 
-            __in_ecount(cChannels)  float aLevelsDB[  ],
-            /* [in] */ 
-            __in  ULONG cChannels,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPerChannelDbLevelVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPerChannelDbLevel * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPerChannelDbLevel * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPerChannelDbLevel * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IPerChannelDbLevel * This,
-            /* [out] */ 
-            __out  UINT *pcChannels);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevelRange )( 
-            IPerChannelDbLevel * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfMinLevelDB,
-            /* [out] */ 
-            __out  float *pfMaxLevelDB,
-            /* [out] */ 
-            __out  float *pfStepping);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevel )( 
-            IPerChannelDbLevel * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevel )( 
-            IPerChannelDbLevel * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelUniform )( 
-            IPerChannelDbLevel * This,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelAllChannels )( 
-            IPerChannelDbLevel * This,
-            /* [size_is][in] */ 
-            __in_ecount(cChannels)  float aLevelsDB[  ],
-            /* [in] */ 
-            __in  ULONG cChannels,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IPerChannelDbLevelVtbl;
-
-    interface IPerChannelDbLevel
-    {
-        CONST_VTBL struct IPerChannelDbLevelVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPerChannelDbLevel_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPerChannelDbLevel_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPerChannelDbLevel_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPerChannelDbLevel_GetChannelCount(This,pcChannels)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pcChannels) ) 
-
-#define IPerChannelDbLevel_GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping)	\
-    ( (This)->lpVtbl -> GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping) ) 
-
-#define IPerChannelDbLevel_GetLevel(This,nChannel,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetLevel(This,nChannel,pfLevelDB) ) 
-
-#define IPerChannelDbLevel_SetLevel(This,nChannel,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevel(This,nChannel,fLevelDB,pguidEventContext) ) 
-
-#define IPerChannelDbLevel_SetLevelUniform(This,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelUniform(This,fLevelDB,pguidEventContext) ) 
-
-#define IPerChannelDbLevel_SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPerChannelDbLevel_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioVolumeLevel_INTERFACE_DEFINED__
-#define __IAudioVolumeLevel_INTERFACE_DEFINED__
-
-/* interface IAudioVolumeLevel */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioVolumeLevel;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("7FB7B48F-531D-44A2-BCB3-5AD5A134B3DC")
-    IAudioVolumeLevel : public IPerChannelDbLevel
-    {
-    public:
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioVolumeLevelVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioVolumeLevel * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioVolumeLevel * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioVolumeLevel * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioVolumeLevel * This,
-            /* [out] */ 
-            __out  UINT *pcChannels);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevelRange )( 
-            IAudioVolumeLevel * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfMinLevelDB,
-            /* [out] */ 
-            __out  float *pfMaxLevelDB,
-            /* [out] */ 
-            __out  float *pfStepping);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevel )( 
-            IAudioVolumeLevel * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevel )( 
-            IAudioVolumeLevel * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelUniform )( 
-            IAudioVolumeLevel * This,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelAllChannels )( 
-            IAudioVolumeLevel * This,
-            /* [size_is][in] */ 
-            __in_ecount(cChannels)  float aLevelsDB[  ],
-            /* [in] */ 
-            __in  ULONG cChannels,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioVolumeLevelVtbl;
-
-    interface IAudioVolumeLevel
-    {
-        CONST_VTBL struct IAudioVolumeLevelVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioVolumeLevel_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioVolumeLevel_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioVolumeLevel_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioVolumeLevel_GetChannelCount(This,pcChannels)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pcChannels) ) 
-
-#define IAudioVolumeLevel_GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping)	\
-    ( (This)->lpVtbl -> GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping) ) 
-
-#define IAudioVolumeLevel_GetLevel(This,nChannel,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetLevel(This,nChannel,pfLevelDB) ) 
-
-#define IAudioVolumeLevel_SetLevel(This,nChannel,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevel(This,nChannel,fLevelDB,pguidEventContext) ) 
-
-#define IAudioVolumeLevel_SetLevelUniform(This,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelUniform(This,fLevelDB,pguidEventContext) ) 
-
-#define IAudioVolumeLevel_SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext) ) 
-
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioVolumeLevel_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioChannelConfig_INTERFACE_DEFINED__
-#define __IAudioChannelConfig_INTERFACE_DEFINED__
-
-/* interface IAudioChannelConfig */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioChannelConfig;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("BB11C46F-EC28-493C-B88A-5DB88062CE98")
-    IAudioChannelConfig : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetChannelConfig( 
-            /* [in] */ DWORD dwConfig,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetChannelConfig( 
-            /* [retval][out] */ DWORD *pdwConfig) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioChannelConfigVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioChannelConfig * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioChannelConfig * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioChannelConfig * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetChannelConfig )( 
-            IAudioChannelConfig * This,
-            /* [in] */ DWORD dwConfig,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelConfig )( 
-            IAudioChannelConfig * This,
-            /* [retval][out] */ DWORD *pdwConfig);
-        
-        END_INTERFACE
-    } IAudioChannelConfigVtbl;
-
-    interface IAudioChannelConfig
-    {
-        CONST_VTBL struct IAudioChannelConfigVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioChannelConfig_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioChannelConfig_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioChannelConfig_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioChannelConfig_SetChannelConfig(This,dwConfig,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetChannelConfig(This,dwConfig,pguidEventContext) ) 
-
-#define IAudioChannelConfig_GetChannelConfig(This,pdwConfig)	\
-    ( (This)->lpVtbl -> GetChannelConfig(This,pdwConfig) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioChannelConfig_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioLoudness_INTERFACE_DEFINED__
-#define __IAudioLoudness_INTERFACE_DEFINED__
-
-/* interface IAudioLoudness */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioLoudness;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("7D8B1437-DD53-4350-9C1B-1EE2890BD938")
-    IAudioLoudness : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetEnabled( 
-            /* [out] */ 
-            __out  BOOL *pbEnabled) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetEnabled( 
-            /* [in] */ 
-            __in  BOOL bEnable,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioLoudnessVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioLoudness * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioLoudness * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioLoudness * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetEnabled )( 
-            IAudioLoudness * This,
-            /* [out] */ 
-            __out  BOOL *pbEnabled);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetEnabled )( 
-            IAudioLoudness * This,
-            /* [in] */ 
-            __in  BOOL bEnable,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioLoudnessVtbl;
-
-    interface IAudioLoudness
-    {
-        CONST_VTBL struct IAudioLoudnessVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioLoudness_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioLoudness_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioLoudness_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioLoudness_GetEnabled(This,pbEnabled)	\
-    ( (This)->lpVtbl -> GetEnabled(This,pbEnabled) ) 
-
-#define IAudioLoudness_SetEnabled(This,bEnable,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetEnabled(This,bEnable,pguidEventContext) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioLoudness_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioInputSelector_INTERFACE_DEFINED__
-#define __IAudioInputSelector_INTERFACE_DEFINED__
-
-/* interface IAudioInputSelector */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioInputSelector;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("4F03DC02-5E6E-4653-8F72-A030C123D598")
-    IAudioInputSelector : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSelection( 
-            /* [out] */ 
-            __out  UINT *pnIdSelected) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetSelection( 
-            /* [in] */ 
-            __in  UINT nIdSelect,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioInputSelectorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioInputSelector * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioInputSelector * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioInputSelector * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSelection )( 
-            IAudioInputSelector * This,
-            /* [out] */ 
-            __out  UINT *pnIdSelected);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetSelection )( 
-            IAudioInputSelector * This,
-            /* [in] */ 
-            __in  UINT nIdSelect,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioInputSelectorVtbl;
-
-    interface IAudioInputSelector
-    {
-        CONST_VTBL struct IAudioInputSelectorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioInputSelector_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioInputSelector_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioInputSelector_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioInputSelector_GetSelection(This,pnIdSelected)	\
-    ( (This)->lpVtbl -> GetSelection(This,pnIdSelected) ) 
-
-#define IAudioInputSelector_SetSelection(This,nIdSelect,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetSelection(This,nIdSelect,pguidEventContext) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioInputSelector_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioOutputSelector_INTERFACE_DEFINED__
-#define __IAudioOutputSelector_INTERFACE_DEFINED__
-
-/* interface IAudioOutputSelector */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioOutputSelector;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("BB515F69-94A7-429e-8B9C-271B3F11A3AB")
-    IAudioOutputSelector : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSelection( 
-            /* [out] */ 
-            __out  UINT *pnIdSelected) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetSelection( 
-            /* [in] */ 
-            __in  UINT nIdSelect,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioOutputSelectorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioOutputSelector * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioOutputSelector * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioOutputSelector * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSelection )( 
-            IAudioOutputSelector * This,
-            /* [out] */ 
-            __out  UINT *pnIdSelected);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetSelection )( 
-            IAudioOutputSelector * This,
-            /* [in] */ 
-            __in  UINT nIdSelect,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioOutputSelectorVtbl;
-
-    interface IAudioOutputSelector
-    {
-        CONST_VTBL struct IAudioOutputSelectorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioOutputSelector_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioOutputSelector_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioOutputSelector_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioOutputSelector_GetSelection(This,pnIdSelected)	\
-    ( (This)->lpVtbl -> GetSelection(This,pnIdSelected) ) 
-
-#define IAudioOutputSelector_SetSelection(This,nIdSelect,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetSelection(This,nIdSelect,pguidEventContext) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioOutputSelector_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioMute_INTERFACE_DEFINED__
-#define __IAudioMute_INTERFACE_DEFINED__
-
-/* interface IAudioMute */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioMute;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("DF45AEEA-B74A-4B6B-AFAD-2366B6AA012E")
-    IAudioMute : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetMute( 
-            /* [in] */ 
-            __in  BOOL bMuted,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetMute( 
-            /* [out] */ 
-            __out  BOOL *pbMuted) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioMuteVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioMute * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioMute * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioMute * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetMute )( 
-            IAudioMute * This,
-            /* [in] */ 
-            __in  BOOL bMuted,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetMute )( 
-            IAudioMute * This,
-            /* [out] */ 
-            __out  BOOL *pbMuted);
-        
-        END_INTERFACE
-    } IAudioMuteVtbl;
-
-    interface IAudioMute
-    {
-        CONST_VTBL struct IAudioMuteVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioMute_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioMute_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioMute_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioMute_SetMute(This,bMuted,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetMute(This,bMuted,pguidEventContext) ) 
-
-#define IAudioMute_GetMute(This,pbMuted)	\
-    ( (This)->lpVtbl -> GetMute(This,pbMuted) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioMute_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioBass_INTERFACE_DEFINED__
-#define __IAudioBass_INTERFACE_DEFINED__
-
-/* interface IAudioBass */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioBass;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("A2B1A1D9-4DB3-425D-A2B2-BD335CB3E2E5")
-    IAudioBass : public IPerChannelDbLevel
-    {
-    public:
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioBassVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioBass * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioBass * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioBass * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioBass * This,
-            /* [out] */ 
-            __out  UINT *pcChannels);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevelRange )( 
-            IAudioBass * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfMinLevelDB,
-            /* [out] */ 
-            __out  float *pfMaxLevelDB,
-            /* [out] */ 
-            __out  float *pfStepping);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevel )( 
-            IAudioBass * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevel )( 
-            IAudioBass * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelUniform )( 
-            IAudioBass * This,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelAllChannels )( 
-            IAudioBass * This,
-            /* [size_is][in] */ 
-            __in_ecount(cChannels)  float aLevelsDB[  ],
-            /* [in] */ 
-            __in  ULONG cChannels,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioBassVtbl;
-
-    interface IAudioBass
-    {
-        CONST_VTBL struct IAudioBassVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioBass_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioBass_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioBass_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioBass_GetChannelCount(This,pcChannels)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pcChannels) ) 
-
-#define IAudioBass_GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping)	\
-    ( (This)->lpVtbl -> GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping) ) 
-
-#define IAudioBass_GetLevel(This,nChannel,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetLevel(This,nChannel,pfLevelDB) ) 
-
-#define IAudioBass_SetLevel(This,nChannel,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevel(This,nChannel,fLevelDB,pguidEventContext) ) 
-
-#define IAudioBass_SetLevelUniform(This,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelUniform(This,fLevelDB,pguidEventContext) ) 
-
-#define IAudioBass_SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext) ) 
-
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioBass_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioMidrange_INTERFACE_DEFINED__
-#define __IAudioMidrange_INTERFACE_DEFINED__
-
-/* interface IAudioMidrange */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioMidrange;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("5E54B6D7-B44B-40D9-9A9E-E691D9CE6EDF")
-    IAudioMidrange : public IPerChannelDbLevel
-    {
-    public:
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioMidrangeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioMidrange * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioMidrange * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioMidrange * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioMidrange * This,
-            /* [out] */ 
-            __out  UINT *pcChannels);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevelRange )( 
-            IAudioMidrange * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfMinLevelDB,
-            /* [out] */ 
-            __out  float *pfMaxLevelDB,
-            /* [out] */ 
-            __out  float *pfStepping);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevel )( 
-            IAudioMidrange * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevel )( 
-            IAudioMidrange * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelUniform )( 
-            IAudioMidrange * This,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelAllChannels )( 
-            IAudioMidrange * This,
-            /* [size_is][in] */ 
-            __in_ecount(cChannels)  float aLevelsDB[  ],
-            /* [in] */ 
-            __in  ULONG cChannels,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioMidrangeVtbl;
-
-    interface IAudioMidrange
-    {
-        CONST_VTBL struct IAudioMidrangeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioMidrange_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioMidrange_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioMidrange_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioMidrange_GetChannelCount(This,pcChannels)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pcChannels) ) 
-
-#define IAudioMidrange_GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping)	\
-    ( (This)->lpVtbl -> GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping) ) 
-
-#define IAudioMidrange_GetLevel(This,nChannel,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetLevel(This,nChannel,pfLevelDB) ) 
-
-#define IAudioMidrange_SetLevel(This,nChannel,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevel(This,nChannel,fLevelDB,pguidEventContext) ) 
-
-#define IAudioMidrange_SetLevelUniform(This,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelUniform(This,fLevelDB,pguidEventContext) ) 
-
-#define IAudioMidrange_SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext) ) 
-
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioMidrange_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioTreble_INTERFACE_DEFINED__
-#define __IAudioTreble_INTERFACE_DEFINED__
-
-/* interface IAudioTreble */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioTreble;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("0A717812-694E-4907-B74B-BAFA5CFDCA7B")
-    IAudioTreble : public IPerChannelDbLevel
-    {
-    public:
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioTrebleVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioTreble * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioTreble * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioTreble * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioTreble * This,
-            /* [out] */ 
-            __out  UINT *pcChannels);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevelRange )( 
-            IAudioTreble * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfMinLevelDB,
-            /* [out] */ 
-            __out  float *pfMaxLevelDB,
-            /* [out] */ 
-            __out  float *pfStepping);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevel )( 
-            IAudioTreble * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevel )( 
-            IAudioTreble * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelUniform )( 
-            IAudioTreble * This,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLevelAllChannels )( 
-            IAudioTreble * This,
-            /* [size_is][in] */ 
-            __in_ecount(cChannels)  float aLevelsDB[  ],
-            /* [in] */ 
-            __in  ULONG cChannels,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioTrebleVtbl;
-
-    interface IAudioTreble
-    {
-        CONST_VTBL struct IAudioTrebleVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioTreble_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioTreble_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioTreble_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioTreble_GetChannelCount(This,pcChannels)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pcChannels) ) 
-
-#define IAudioTreble_GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping)	\
-    ( (This)->lpVtbl -> GetLevelRange(This,nChannel,pfMinLevelDB,pfMaxLevelDB,pfStepping) ) 
-
-#define IAudioTreble_GetLevel(This,nChannel,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetLevel(This,nChannel,pfLevelDB) ) 
-
-#define IAudioTreble_SetLevel(This,nChannel,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevel(This,nChannel,fLevelDB,pguidEventContext) ) 
-
-#define IAudioTreble_SetLevelUniform(This,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelUniform(This,fLevelDB,pguidEventContext) ) 
-
-#define IAudioTreble_SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetLevelAllChannels(This,aLevelsDB,cChannels,pguidEventContext) ) 
-
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioTreble_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioAutoGainControl_INTERFACE_DEFINED__
-#define __IAudioAutoGainControl_INTERFACE_DEFINED__
-
-/* interface IAudioAutoGainControl */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioAutoGainControl;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("85401FD4-6DE4-4b9d-9869-2D6753A82F3C")
-    IAudioAutoGainControl : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetEnabled( 
-            /* [out] */ 
-            __out  BOOL *pbEnabled) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetEnabled( 
-            /* [in] */ 
-            __in  BOOL bEnable,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioAutoGainControlVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioAutoGainControl * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioAutoGainControl * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioAutoGainControl * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetEnabled )( 
-            IAudioAutoGainControl * This,
-            /* [out] */ 
-            __out  BOOL *pbEnabled);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetEnabled )( 
-            IAudioAutoGainControl * This,
-            /* [in] */ 
-            __in  BOOL bEnable,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IAudioAutoGainControlVtbl;
-
-    interface IAudioAutoGainControl
-    {
-        CONST_VTBL struct IAudioAutoGainControlVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioAutoGainControl_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioAutoGainControl_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioAutoGainControl_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioAutoGainControl_GetEnabled(This,pbEnabled)	\
-    ( (This)->lpVtbl -> GetEnabled(This,pbEnabled) ) 
-
-#define IAudioAutoGainControl_SetEnabled(This,bEnable,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetEnabled(This,bEnable,pguidEventContext) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioAutoGainControl_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioPeakMeter_INTERFACE_DEFINED__
-#define __IAudioPeakMeter_INTERFACE_DEFINED__
-
-/* interface IAudioPeakMeter */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioPeakMeter;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("DD79923C-0599-45e0-B8B6-C8DF7DB6E796")
-    IAudioPeakMeter : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetChannelCount( 
-            /* [out] */ 
-            __out  UINT *pcChannels) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLevel( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevel) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioPeakMeterVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioPeakMeter * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioPeakMeter * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioPeakMeter * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioPeakMeter * This,
-            /* [out] */ 
-            __out  UINT *pcChannels);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLevel )( 
-            IAudioPeakMeter * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevel);
-        
-        END_INTERFACE
-    } IAudioPeakMeterVtbl;
-
-    interface IAudioPeakMeter
-    {
-        CONST_VTBL struct IAudioPeakMeterVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioPeakMeter_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioPeakMeter_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioPeakMeter_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioPeakMeter_GetChannelCount(This,pcChannels)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pcChannels) ) 
-
-#define IAudioPeakMeter_GetLevel(This,nChannel,pfLevel)	\
-    ( (This)->lpVtbl -> GetLevel(This,nChannel,pfLevel) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioPeakMeter_INTERFACE_DEFINED__ */
-
-
-#ifndef __IDeviceSpecificProperty_INTERFACE_DEFINED__
-#define __IDeviceSpecificProperty_INTERFACE_DEFINED__
-
-/* interface IDeviceSpecificProperty */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IDeviceSpecificProperty;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("3B22BCBF-2586-4af0-8583-205D391B807C")
-    IDeviceSpecificProperty : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetType( 
-            /* [out] */ 
-            __deref_out  VARTYPE *pVType) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetValue( 
-            /* [out] */ 
-            __out  void *pvValue,
-            /* [out][in] */ 
-            __inout  DWORD *pcbValue) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetValue( 
-            /* [in] */ 
-            __in  void *pvValue,
-            /* [in] */ DWORD cbValue,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Get4BRange( 
-            /* [out] */ 
-            __deref_out  LONG *plMin,
-            /* [out] */ 
-            __deref_out  LONG *plMax,
-            /* [out] */ 
-            __deref_out  LONG *plStepping) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IDeviceSpecificPropertyVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IDeviceSpecificProperty * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IDeviceSpecificProperty * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IDeviceSpecificProperty * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetType )( 
-            IDeviceSpecificProperty * This,
-            /* [out] */ 
-            __deref_out  VARTYPE *pVType);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetValue )( 
-            IDeviceSpecificProperty * This,
-            /* [out] */ 
-            __out  void *pvValue,
-            /* [out][in] */ 
-            __inout  DWORD *pcbValue);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetValue )( 
-            IDeviceSpecificProperty * This,
-            /* [in] */ 
-            __in  void *pvValue,
-            /* [in] */ DWORD cbValue,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Get4BRange )( 
-            IDeviceSpecificProperty * This,
-            /* [out] */ 
-            __deref_out  LONG *plMin,
-            /* [out] */ 
-            __deref_out  LONG *plMax,
-            /* [out] */ 
-            __deref_out  LONG *plStepping);
-        
-        END_INTERFACE
-    } IDeviceSpecificPropertyVtbl;
-
-    interface IDeviceSpecificProperty
-    {
-        CONST_VTBL struct IDeviceSpecificPropertyVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IDeviceSpecificProperty_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IDeviceSpecificProperty_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IDeviceSpecificProperty_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IDeviceSpecificProperty_GetType(This,pVType)	\
-    ( (This)->lpVtbl -> GetType(This,pVType) ) 
-
-#define IDeviceSpecificProperty_GetValue(This,pvValue,pcbValue)	\
-    ( (This)->lpVtbl -> GetValue(This,pvValue,pcbValue) ) 
-
-#define IDeviceSpecificProperty_SetValue(This,pvValue,cbValue,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetValue(This,pvValue,cbValue,pguidEventContext) ) 
-
-#define IDeviceSpecificProperty_Get4BRange(This,plMin,plMax,plStepping)	\
-    ( (This)->lpVtbl -> Get4BRange(This,plMin,plMax,plStepping) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IDeviceSpecificProperty_INTERFACE_DEFINED__ */
-
-
-#ifndef __IKsFormatSupport_INTERFACE_DEFINED__
-#define __IKsFormatSupport_INTERFACE_DEFINED__
-
-/* interface IKsFormatSupport */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IKsFormatSupport;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("3CB4A69D-BB6F-4D2B-95B7-452D2C155DB5")
-    IKsFormatSupport : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IsFormatSupported( 
-            /* [size_is][in] */ PKSDATAFORMAT pKsFormat,
-            /* [in] */ 
-            __in  DWORD cbFormat,
-            /* [out] */ 
-            __out  BOOL *pbSupported) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDevicePreferredFormat( 
-            /* [out] */ PKSDATAFORMAT *ppKsFormat) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IKsFormatSupportVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IKsFormatSupport * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IKsFormatSupport * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IKsFormatSupport * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *IsFormatSupported )( 
-            IKsFormatSupport * This,
-            /* [size_is][in] */ PKSDATAFORMAT pKsFormat,
-            /* [in] */ 
-            __in  DWORD cbFormat,
-            /* [out] */ 
-            __out  BOOL *pbSupported);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDevicePreferredFormat )( 
-            IKsFormatSupport * This,
-            /* [out] */ PKSDATAFORMAT *ppKsFormat);
-        
-        END_INTERFACE
-    } IKsFormatSupportVtbl;
-
-    interface IKsFormatSupport
-    {
-        CONST_VTBL struct IKsFormatSupportVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IKsFormatSupport_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IKsFormatSupport_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IKsFormatSupport_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IKsFormatSupport_IsFormatSupported(This,pKsFormat,cbFormat,pbSupported)	\
-    ( (This)->lpVtbl -> IsFormatSupported(This,pKsFormat,cbFormat,pbSupported) ) 
-
-#define IKsFormatSupport_GetDevicePreferredFormat(This,ppKsFormat)	\
-    ( (This)->lpVtbl -> GetDevicePreferredFormat(This,ppKsFormat) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IKsFormatSupport_INTERFACE_DEFINED__ */
-
-
-#ifndef __IKsJackDescription_INTERFACE_DEFINED__
-#define __IKsJackDescription_INTERFACE_DEFINED__
-
-/* interface IKsJackDescription */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IKsJackDescription;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("4509F757-2D46-4637-8E62-CE7DB944F57B")
-    IKsJackDescription : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetJackCount( 
-            /* [out] */ 
-            __out  UINT *pcJacks) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetJackDescription( 
-            /* [in] */ UINT nJack,
-            /* [out] */ 
-            __out  KSJACK_DESCRIPTION *pDescription) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IKsJackDescriptionVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IKsJackDescription * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IKsJackDescription * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IKsJackDescription * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetJackCount )( 
-            IKsJackDescription * This,
-            /* [out] */ 
-            __out  UINT *pcJacks);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetJackDescription )( 
-            IKsJackDescription * This,
-            /* [in] */ UINT nJack,
-            /* [out] */ 
-            __out  KSJACK_DESCRIPTION *pDescription);
-        
-        END_INTERFACE
-    } IKsJackDescriptionVtbl;
-
-    interface IKsJackDescription
-    {
-        CONST_VTBL struct IKsJackDescriptionVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IKsJackDescription_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IKsJackDescription_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IKsJackDescription_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IKsJackDescription_GetJackCount(This,pcJacks)	\
-    ( (This)->lpVtbl -> GetJackCount(This,pcJacks) ) 
-
-#define IKsJackDescription_GetJackDescription(This,nJack,pDescription)	\
-    ( (This)->lpVtbl -> GetJackDescription(This,nJack,pDescription) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IKsJackDescription_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPartsList_INTERFACE_DEFINED__
-#define __IPartsList_INTERFACE_DEFINED__
-
-/* interface IPartsList */
-/* [object][unique][helpstring][uuid][local] */ 
-
-
-EXTERN_C const IID IID_IPartsList;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("6DAA848C-5EB0-45CC-AEA5-998A2CDA1FFB")
-    IPartsList : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCount( 
-            /* [out] */ 
-            __out  UINT *pCount) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetPart( 
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __out  IPart **ppPart) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPartsListVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPartsList * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPartsList * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPartsList * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IPartsList * This,
-            /* [out] */ 
-            __out  UINT *pCount);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetPart )( 
-            IPartsList * This,
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __out  IPart **ppPart);
-        
-        END_INTERFACE
-    } IPartsListVtbl;
-
-    interface IPartsList
-    {
-        CONST_VTBL struct IPartsListVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPartsList_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPartsList_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPartsList_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPartsList_GetCount(This,pCount)	\
-    ( (This)->lpVtbl -> GetCount(This,pCount) ) 
-
-#define IPartsList_GetPart(This,nIndex,ppPart)	\
-    ( (This)->lpVtbl -> GetPart(This,nIndex,ppPart) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPartsList_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPart_INTERFACE_DEFINED__
-#define __IPart_INTERFACE_DEFINED__
-
-/* interface IPart */
-/* [object][unique][helpstring][uuid][local] */ 
-
-
-EXTERN_C const IID IID_IPart;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("AE2DE0E4-5BCA-4F2D-AA46-5D13F8FDB3A9")
-    IPart : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetName( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrName) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLocalId( 
-            /* [out] */ 
-            __out  UINT *pnId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetGlobalId( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrGlobalId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetPartType( 
-            /* [out] */ 
-            __out  PartType *pPartType) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSubType( 
-            /* [out] */ GUID *pSubType) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetControlInterfaceCount( 
-            /* [out] */ 
-            __out  UINT *pCount) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetControlInterface( 
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __out  IControlInterface **ppInterfaceDesc) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE EnumPartsIncoming( 
-            /* [out] */ 
-            __out  IPartsList **ppParts) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE EnumPartsOutgoing( 
-            /* [out] */ 
-            __out  IPartsList **ppParts) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetTopologyObject( 
-            /* [out] */ 
-            __out  IDeviceTopology **ppTopology) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Activate( 
-            /* [in] */ 
-            __in  DWORD dwClsContext,
-            /* [in] */ 
-            __in  REFIID refiid,
-            /* [iid_is][out] */ 
-            __out_opt  void **ppvObject) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RegisterControlChangeCallback( 
-            /* [in] */ 
-            __in  REFGUID riid,
-            /* [in] */ 
-            __in  IControlChangeNotify *pNotify) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE UnregisterControlChangeCallback( 
-            /* [in] */ 
-            __in  IControlChangeNotify *pNotify) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPartVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPart * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPart * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPart * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetName )( 
-            IPart * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrName);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLocalId )( 
-            IPart * This,
-            /* [out] */ 
-            __out  UINT *pnId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetGlobalId )( 
-            IPart * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrGlobalId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetPartType )( 
-            IPart * This,
-            /* [out] */ 
-            __out  PartType *pPartType);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSubType )( 
-            IPart * This,
-            /* [out] */ GUID *pSubType);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetControlInterfaceCount )( 
-            IPart * This,
-            /* [out] */ 
-            __out  UINT *pCount);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetControlInterface )( 
-            IPart * This,
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __out  IControlInterface **ppInterfaceDesc);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *EnumPartsIncoming )( 
-            IPart * This,
-            /* [out] */ 
-            __out  IPartsList **ppParts);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *EnumPartsOutgoing )( 
-            IPart * This,
-            /* [out] */ 
-            __out  IPartsList **ppParts);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetTopologyObject )( 
-            IPart * This,
-            /* [out] */ 
-            __out  IDeviceTopology **ppTopology);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Activate )( 
-            IPart * This,
-            /* [in] */ 
-            __in  DWORD dwClsContext,
-            /* [in] */ 
-            __in  REFIID refiid,
-            /* [iid_is][out] */ 
-            __out_opt  void **ppvObject);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RegisterControlChangeCallback )( 
-            IPart * This,
-            /* [in] */ 
-            __in  REFGUID riid,
-            /* [in] */ 
-            __in  IControlChangeNotify *pNotify);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *UnregisterControlChangeCallback )( 
-            IPart * This,
-            /* [in] */ 
-            __in  IControlChangeNotify *pNotify);
-        
-        END_INTERFACE
-    } IPartVtbl;
-
-    interface IPart
-    {
-        CONST_VTBL struct IPartVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPart_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPart_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPart_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPart_GetName(This,ppwstrName)	\
-    ( (This)->lpVtbl -> GetName(This,ppwstrName) ) 
-
-#define IPart_GetLocalId(This,pnId)	\
-    ( (This)->lpVtbl -> GetLocalId(This,pnId) ) 
-
-#define IPart_GetGlobalId(This,ppwstrGlobalId)	\
-    ( (This)->lpVtbl -> GetGlobalId(This,ppwstrGlobalId) ) 
-
-#define IPart_GetPartType(This,pPartType)	\
-    ( (This)->lpVtbl -> GetPartType(This,pPartType) ) 
-
-#define IPart_GetSubType(This,pSubType)	\
-    ( (This)->lpVtbl -> GetSubType(This,pSubType) ) 
-
-#define IPart_GetControlInterfaceCount(This,pCount)	\
-    ( (This)->lpVtbl -> GetControlInterfaceCount(This,pCount) ) 
-
-#define IPart_GetControlInterface(This,nIndex,ppInterfaceDesc)	\
-    ( (This)->lpVtbl -> GetControlInterface(This,nIndex,ppInterfaceDesc) ) 
-
-#define IPart_EnumPartsIncoming(This,ppParts)	\
-    ( (This)->lpVtbl -> EnumPartsIncoming(This,ppParts) ) 
-
-#define IPart_EnumPartsOutgoing(This,ppParts)	\
-    ( (This)->lpVtbl -> EnumPartsOutgoing(This,ppParts) ) 
-
-#define IPart_GetTopologyObject(This,ppTopology)	\
-    ( (This)->lpVtbl -> GetTopologyObject(This,ppTopology) ) 
-
-#define IPart_Activate(This,dwClsContext,refiid,ppvObject)	\
-    ( (This)->lpVtbl -> Activate(This,dwClsContext,refiid,ppvObject) ) 
-
-#define IPart_RegisterControlChangeCallback(This,riid,pNotify)	\
-    ( (This)->lpVtbl -> RegisterControlChangeCallback(This,riid,pNotify) ) 
-
-#define IPart_UnregisterControlChangeCallback(This,pNotify)	\
-    ( (This)->lpVtbl -> UnregisterControlChangeCallback(This,pNotify) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPart_INTERFACE_DEFINED__ */
-
-
-#ifndef __IConnector_INTERFACE_DEFINED__
-#define __IConnector_INTERFACE_DEFINED__
-
-/* interface IConnector */
-/* [object][unique][helpstring][uuid][local] */ 
-
-
-EXTERN_C const IID IID_IConnector;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("9c2c4058-23f5-41de-877a-df3af236a09e")
-    IConnector : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetType( 
-            /* [out] */ 
-            __out  ConnectorType *pType) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDataFlow( 
-            /* [out] */ 
-            __out  DataFlow *pFlow) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ConnectTo( 
-            /* [in] */ 
-            __in  IConnector *pConnectTo) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Disconnect( void) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IsConnected( 
-            /* [out] */ 
-            __out  BOOL *pbConnected) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetConnectedTo( 
-            /* [out] */ 
-            __out  IConnector **ppConTo) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetConnectorIdConnectedTo( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrConnectorId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDeviceIdConnectedTo( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrDeviceId) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IConnectorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IConnector * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IConnector * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IConnector * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetType )( 
-            IConnector * This,
-            /* [out] */ 
-            __out  ConnectorType *pType);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDataFlow )( 
-            IConnector * This,
-            /* [out] */ 
-            __out  DataFlow *pFlow);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ConnectTo )( 
-            IConnector * This,
-            /* [in] */ 
-            __in  IConnector *pConnectTo);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Disconnect )( 
-            IConnector * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *IsConnected )( 
-            IConnector * This,
-            /* [out] */ 
-            __out  BOOL *pbConnected);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetConnectedTo )( 
-            IConnector * This,
-            /* [out] */ 
-            __out  IConnector **ppConTo);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetConnectorIdConnectedTo )( 
-            IConnector * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrConnectorId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDeviceIdConnectedTo )( 
-            IConnector * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrDeviceId);
-        
-        END_INTERFACE
-    } IConnectorVtbl;
-
-    interface IConnector
-    {
-        CONST_VTBL struct IConnectorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IConnector_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IConnector_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IConnector_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IConnector_GetType(This,pType)	\
-    ( (This)->lpVtbl -> GetType(This,pType) ) 
-
-#define IConnector_GetDataFlow(This,pFlow)	\
-    ( (This)->lpVtbl -> GetDataFlow(This,pFlow) ) 
-
-#define IConnector_ConnectTo(This,pConnectTo)	\
-    ( (This)->lpVtbl -> ConnectTo(This,pConnectTo) ) 
-
-#define IConnector_Disconnect(This)	\
-    ( (This)->lpVtbl -> Disconnect(This) ) 
-
-#define IConnector_IsConnected(This,pbConnected)	\
-    ( (This)->lpVtbl -> IsConnected(This,pbConnected) ) 
-
-#define IConnector_GetConnectedTo(This,ppConTo)	\
-    ( (This)->lpVtbl -> GetConnectedTo(This,ppConTo) ) 
-
-#define IConnector_GetConnectorIdConnectedTo(This,ppwstrConnectorId)	\
-    ( (This)->lpVtbl -> GetConnectorIdConnectedTo(This,ppwstrConnectorId) ) 
-
-#define IConnector_GetDeviceIdConnectedTo(This,ppwstrDeviceId)	\
-    ( (This)->lpVtbl -> GetDeviceIdConnectedTo(This,ppwstrDeviceId) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IConnector_INTERFACE_DEFINED__ */
-
-
-#ifndef __ISubunit_INTERFACE_DEFINED__
-#define __ISubunit_INTERFACE_DEFINED__
-
-/* interface ISubunit */
-/* [object][unique][helpstring][uuid][local] */ 
-
-
-EXTERN_C const IID IID_ISubunit;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("82149A85-DBA6-4487-86BB-EA8F7FEFCC71")
-    ISubunit : public IUnknown
-    {
-    public:
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct ISubunitVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ISubunit * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ISubunit * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ISubunit * This);
-        
-        END_INTERFACE
-    } ISubunitVtbl;
-
-    interface ISubunit
-    {
-        CONST_VTBL struct ISubunitVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ISubunit_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ISubunit_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ISubunit_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ISubunit_INTERFACE_DEFINED__ */
-
-
-#ifndef __IControlInterface_INTERFACE_DEFINED__
-#define __IControlInterface_INTERFACE_DEFINED__
-
-/* interface IControlInterface */
-/* [object][unique][helpstring][uuid][local] */ 
-
-
-EXTERN_C const IID IID_IControlInterface;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("45d37c3f-5140-444a-ae24-400789f3cbf3")
-    IControlInterface : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetName( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrName) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetIID( 
-            /* [out] */ 
-            __out  GUID *pIID) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IControlInterfaceVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IControlInterface * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IControlInterface * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IControlInterface * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetName )( 
-            IControlInterface * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrName);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetIID )( 
-            IControlInterface * This,
-            /* [out] */ 
-            __out  GUID *pIID);
-        
-        END_INTERFACE
-    } IControlInterfaceVtbl;
-
-    interface IControlInterface
-    {
-        CONST_VTBL struct IControlInterfaceVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IControlInterface_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IControlInterface_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IControlInterface_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IControlInterface_GetName(This,ppwstrName)	\
-    ( (This)->lpVtbl -> GetName(This,ppwstrName) ) 
-
-#define IControlInterface_GetIID(This,pIID)	\
-    ( (This)->lpVtbl -> GetIID(This,pIID) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IControlInterface_INTERFACE_DEFINED__ */
-
-
-#ifndef __IControlChangeNotify_INTERFACE_DEFINED__
-#define __IControlChangeNotify_INTERFACE_DEFINED__
-
-/* interface IControlChangeNotify */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IControlChangeNotify;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("A09513ED-C709-4d21-BD7B-5F34C47F3947")
-    IControlChangeNotify : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnNotify( 
-            /* [in] */ 
-            __in  DWORD dwSenderProcessId,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IControlChangeNotifyVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IControlChangeNotify * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IControlChangeNotify * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IControlChangeNotify * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OnNotify )( 
-            IControlChangeNotify * This,
-            /* [in] */ 
-            __in  DWORD dwSenderProcessId,
-            /* [unique][in] */ 
-            __in_opt  LPCGUID pguidEventContext);
-        
-        END_INTERFACE
-    } IControlChangeNotifyVtbl;
-
-    interface IControlChangeNotify
-    {
-        CONST_VTBL struct IControlChangeNotifyVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IControlChangeNotify_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IControlChangeNotify_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IControlChangeNotify_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IControlChangeNotify_OnNotify(This,dwSenderProcessId,pguidEventContext)	\
-    ( (This)->lpVtbl -> OnNotify(This,dwSenderProcessId,pguidEventContext) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IControlChangeNotify_INTERFACE_DEFINED__ */
-
-
-#ifndef __IDeviceTopology_INTERFACE_DEFINED__
-#define __IDeviceTopology_INTERFACE_DEFINED__
-
-/* interface IDeviceTopology */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IDeviceTopology;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("2A07407E-6497-4A18-9787-32F79BD0D98F")
-    IDeviceTopology : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetConnectorCount( 
-            /* [out] */ 
-            __out  UINT *pCount) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetConnector( 
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __out  IConnector **ppConnector) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSubunitCount( 
-            /* [out] */ 
-            __out  UINT *pCount) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSubunit( 
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __deref_out  ISubunit **ppSubunit) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetPartById( 
-            /* [in] */ 
-            __in  UINT nId,
-            /* [out] */ 
-            __deref_out  IPart **ppPart) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDeviceId( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrDeviceId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSignalPath( 
-            /* [in] */ 
-            __in  IPart *pIPartFrom,
-            /* [in] */ 
-            __in  IPart *pIPartTo,
-            /* [in] */ 
-            __in  BOOL bRejectMixedPaths,
-            /* [out] */ 
-            __deref_out  IPartsList **ppParts) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IDeviceTopologyVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IDeviceTopology * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IDeviceTopology * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IDeviceTopology * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetConnectorCount )( 
-            IDeviceTopology * This,
-            /* [out] */ 
-            __out  UINT *pCount);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetConnector )( 
-            IDeviceTopology * This,
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __out  IConnector **ppConnector);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSubunitCount )( 
-            IDeviceTopology * This,
-            /* [out] */ 
-            __out  UINT *pCount);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSubunit )( 
-            IDeviceTopology * This,
-            /* [in] */ 
-            __in  UINT nIndex,
-            /* [out] */ 
-            __deref_out  ISubunit **ppSubunit);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetPartById )( 
-            IDeviceTopology * This,
-            /* [in] */ 
-            __in  UINT nId,
-            /* [out] */ 
-            __deref_out  IPart **ppPart);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDeviceId )( 
-            IDeviceTopology * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppwstrDeviceId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSignalPath )( 
-            IDeviceTopology * This,
-            /* [in] */ 
-            __in  IPart *pIPartFrom,
-            /* [in] */ 
-            __in  IPart *pIPartTo,
-            /* [in] */ 
-            __in  BOOL bRejectMixedPaths,
-            /* [out] */ 
-            __deref_out  IPartsList **ppParts);
-        
-        END_INTERFACE
-    } IDeviceTopologyVtbl;
-
-    interface IDeviceTopology
-    {
-        CONST_VTBL struct IDeviceTopologyVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IDeviceTopology_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IDeviceTopology_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IDeviceTopology_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IDeviceTopology_GetConnectorCount(This,pCount)	\
-    ( (This)->lpVtbl -> GetConnectorCount(This,pCount) ) 
-
-#define IDeviceTopology_GetConnector(This,nIndex,ppConnector)	\
-    ( (This)->lpVtbl -> GetConnector(This,nIndex,ppConnector) ) 
-
-#define IDeviceTopology_GetSubunitCount(This,pCount)	\
-    ( (This)->lpVtbl -> GetSubunitCount(This,pCount) ) 
-
-#define IDeviceTopology_GetSubunit(This,nIndex,ppSubunit)	\
-    ( (This)->lpVtbl -> GetSubunit(This,nIndex,ppSubunit) ) 
-
-#define IDeviceTopology_GetPartById(This,nId,ppPart)	\
-    ( (This)->lpVtbl -> GetPartById(This,nId,ppPart) ) 
-
-#define IDeviceTopology_GetDeviceId(This,ppwstrDeviceId)	\
-    ( (This)->lpVtbl -> GetDeviceId(This,ppwstrDeviceId) ) 
-
-#define IDeviceTopology_GetSignalPath(This,pIPartFrom,pIPartTo,bRejectMixedPaths,ppParts)	\
-    ( (This)->lpVtbl -> GetSignalPath(This,pIPartFrom,pIPartTo,bRejectMixedPaths,ppParts) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IDeviceTopology_INTERFACE_DEFINED__ */
-
-
-
-#ifndef __DevTopologyLib_LIBRARY_DEFINED__
-#define __DevTopologyLib_LIBRARY_DEFINED__
-
-/* library DevTopologyLib */
-/* [helpstring][version][uuid] */ 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-EXTERN_C const IID LIBID_DevTopologyLib;
-
-EXTERN_C const CLSID CLSID_DeviceTopology;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("1DF639D0-5EC1-47AA-9379-828DC1AA8C59")
-DeviceTopology;
-#endif
-#endif /* __DevTopologyLib_LIBRARY_DEFINED__ */
-
-/* Additional Prototypes for ALL interfaces */
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/endpointvolume.h b/portaudio/src/hostapi/wasapi/mingw-include/endpointvolume.h
deleted file mode 100644
index 095f18f7b..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/endpointvolume.h
+++ /dev/null
@@ -1,620 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for endpointvolume.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 500
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __endpointvolume_h__
-#define __endpointvolume_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-#ifndef __IAudioEndpointVolumeCallback_FWD_DEFINED__
-#define __IAudioEndpointVolumeCallback_FWD_DEFINED__
-typedef interface IAudioEndpointVolumeCallback IAudioEndpointVolumeCallback;
-#endif 	/* __IAudioEndpointVolumeCallback_FWD_DEFINED__ */
-
-
-#ifndef __IAudioEndpointVolume_FWD_DEFINED__
-#define __IAudioEndpointVolume_FWD_DEFINED__
-typedef interface IAudioEndpointVolume IAudioEndpointVolume;
-#endif 	/* __IAudioEndpointVolume_FWD_DEFINED__ */
-
-
-#ifndef __IAudioMeterInformation_FWD_DEFINED__
-#define __IAudioMeterInformation_FWD_DEFINED__
-typedef interface IAudioMeterInformation IAudioMeterInformation;
-#endif 	/* __IAudioMeterInformation_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "unknwn.h"
-#include "devicetopology.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_endpointvolume_0000_0000 */
-/* [local] */ 
-
-typedef struct AUDIO_VOLUME_NOTIFICATION_DATA
-    {
-    GUID guidEventContext;
-    BOOL bMuted;
-    float fMasterVolume;
-    UINT nChannels;
-    float afChannelVolumes[ 1 ];
-    } 	AUDIO_VOLUME_NOTIFICATION_DATA;
-
-typedef struct AUDIO_VOLUME_NOTIFICATION_DATA *PAUDIO_VOLUME_NOTIFICATION_DATA;
-
-#define   ENDPOINT_HARDWARE_SUPPORT_VOLUME    0x00000001
-#define   ENDPOINT_HARDWARE_SUPPORT_MUTE      0x00000002
-#define   ENDPOINT_HARDWARE_SUPPORT_METER     0x00000004
-
-
-extern RPC_IF_HANDLE __MIDL_itf_endpointvolume_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_endpointvolume_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IAudioEndpointVolumeCallback_INTERFACE_DEFINED__
-#define __IAudioEndpointVolumeCallback_INTERFACE_DEFINED__
-
-/* interface IAudioEndpointVolumeCallback */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioEndpointVolumeCallback;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("657804FA-D6AD-4496-8A60-352752AF4F89")
-    IAudioEndpointVolumeCallback : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE OnNotify( 
-            PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioEndpointVolumeCallbackVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioEndpointVolumeCallback * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioEndpointVolumeCallback * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioEndpointVolumeCallback * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *OnNotify )( 
-            IAudioEndpointVolumeCallback * This,
-            PAUDIO_VOLUME_NOTIFICATION_DATA pNotify);
-        
-        END_INTERFACE
-    } IAudioEndpointVolumeCallbackVtbl;
-
-    interface IAudioEndpointVolumeCallback
-    {
-        CONST_VTBL struct IAudioEndpointVolumeCallbackVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioEndpointVolumeCallback_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioEndpointVolumeCallback_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioEndpointVolumeCallback_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioEndpointVolumeCallback_OnNotify(This,pNotify)	\
-    ( (This)->lpVtbl -> OnNotify(This,pNotify) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioEndpointVolumeCallback_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioEndpointVolume_INTERFACE_DEFINED__
-#define __IAudioEndpointVolume_INTERFACE_DEFINED__
-
-/* interface IAudioEndpointVolume */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioEndpointVolume;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("5CDF2C82-841E-4546-9722-0CF74078229A")
-    IAudioEndpointVolume : public IUnknown
-    {
-    public:
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE RegisterControlChangeNotify( 
-            /* [in] */ 
-            __in  IAudioEndpointVolumeCallback *pNotify) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UnregisterControlChangeNotify( 
-            /* [in] */ 
-            __in  IAudioEndpointVolumeCallback *pNotify) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelCount( 
-            /* [out] */ 
-            __out  UINT *pnChannelCount) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetMasterVolumeLevel( 
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetMasterVolumeLevelScalar( 
-            /* [in] */ 
-            __in  float fLevel,
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMasterVolumeLevel( 
-            /* [out] */ 
-            __out  float *pfLevelDB) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMasterVolumeLevelScalar( 
-            /* [out] */ 
-            __out  float *pfLevel) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetChannelVolumeLevel( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            float fLevelDB,
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetChannelVolumeLevelScalar( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            float fLevel,
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelVolumeLevel( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelVolumeLevelScalar( 
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevel) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetMute( 
-            /* [in] */ 
-            __in  BOOL bMute,
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMute( 
-            /* [out] */ 
-            __out  BOOL *pbMute) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetVolumeStepInfo( 
-            /* [out] */ 
-            __out  UINT *pnStep,
-            /* [out] */ 
-            __out  UINT *pnStepCount) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE VolumeStepUp( 
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE VolumeStepDown( 
-            /* [unique][in] */ LPCGUID pguidEventContext) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE QueryHardwareSupport( 
-            /* [out] */ 
-            __out  DWORD *pdwHardwareSupportMask) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetVolumeRange( 
-            /* [out] */ 
-            __out  float *pflVolumeMindB,
-            /* [out] */ 
-            __out  float *pflVolumeMaxdB,
-            /* [out] */ 
-            __out  float *pflVolumeIncrementdB) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioEndpointVolumeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioEndpointVolume * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioEndpointVolume * This);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *RegisterControlChangeNotify )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  IAudioEndpointVolumeCallback *pNotify);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UnregisterControlChangeNotify )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  IAudioEndpointVolumeCallback *pNotify);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetChannelCount )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  UINT *pnChannelCount);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetMasterVolumeLevel )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  float fLevelDB,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetMasterVolumeLevelScalar )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  float fLevel,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetMasterVolumeLevel )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetMasterVolumeLevelScalar )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  float *pfLevel);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetChannelVolumeLevel )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            float fLevelDB,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetChannelVolumeLevelScalar )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            float fLevel,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetChannelVolumeLevel )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevelDB);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetChannelVolumeLevelScalar )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  UINT nChannel,
-            /* [out] */ 
-            __out  float *pfLevel);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetMute )( 
-            IAudioEndpointVolume * This,
-            /* [in] */ 
-            __in  BOOL bMute,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetMute )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  BOOL *pbMute);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetVolumeStepInfo )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  UINT *pnStep,
-            /* [out] */ 
-            __out  UINT *pnStepCount);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *VolumeStepUp )( 
-            IAudioEndpointVolume * This,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *VolumeStepDown )( 
-            IAudioEndpointVolume * This,
-            /* [unique][in] */ LPCGUID pguidEventContext);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *QueryHardwareSupport )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  DWORD *pdwHardwareSupportMask);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetVolumeRange )( 
-            IAudioEndpointVolume * This,
-            /* [out] */ 
-            __out  float *pflVolumeMindB,
-            /* [out] */ 
-            __out  float *pflVolumeMaxdB,
-            /* [out] */ 
-            __out  float *pflVolumeIncrementdB);
-        
-        END_INTERFACE
-    } IAudioEndpointVolumeVtbl;
-
-    interface IAudioEndpointVolume
-    {
-        CONST_VTBL struct IAudioEndpointVolumeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioEndpointVolume_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioEndpointVolume_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioEndpointVolume_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioEndpointVolume_RegisterControlChangeNotify(This,pNotify)	\
-    ( (This)->lpVtbl -> RegisterControlChangeNotify(This,pNotify) ) 
-
-#define IAudioEndpointVolume_UnregisterControlChangeNotify(This,pNotify)	\
-    ( (This)->lpVtbl -> UnregisterControlChangeNotify(This,pNotify) ) 
-
-#define IAudioEndpointVolume_GetChannelCount(This,pnChannelCount)	\
-    ( (This)->lpVtbl -> GetChannelCount(This,pnChannelCount) ) 
-
-#define IAudioEndpointVolume_SetMasterVolumeLevel(This,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetMasterVolumeLevel(This,fLevelDB,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_SetMasterVolumeLevelScalar(This,fLevel,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetMasterVolumeLevelScalar(This,fLevel,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_GetMasterVolumeLevel(This,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetMasterVolumeLevel(This,pfLevelDB) ) 
-
-#define IAudioEndpointVolume_GetMasterVolumeLevelScalar(This,pfLevel)	\
-    ( (This)->lpVtbl -> GetMasterVolumeLevelScalar(This,pfLevel) ) 
-
-#define IAudioEndpointVolume_SetChannelVolumeLevel(This,nChannel,fLevelDB,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetChannelVolumeLevel(This,nChannel,fLevelDB,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_SetChannelVolumeLevelScalar(This,nChannel,fLevel,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetChannelVolumeLevelScalar(This,nChannel,fLevel,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_GetChannelVolumeLevel(This,nChannel,pfLevelDB)	\
-    ( (This)->lpVtbl -> GetChannelVolumeLevel(This,nChannel,pfLevelDB) ) 
-
-#define IAudioEndpointVolume_GetChannelVolumeLevelScalar(This,nChannel,pfLevel)	\
-    ( (This)->lpVtbl -> GetChannelVolumeLevelScalar(This,nChannel,pfLevel) ) 
-
-#define IAudioEndpointVolume_SetMute(This,bMute,pguidEventContext)	\
-    ( (This)->lpVtbl -> SetMute(This,bMute,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_GetMute(This,pbMute)	\
-    ( (This)->lpVtbl -> GetMute(This,pbMute) ) 
-
-#define IAudioEndpointVolume_GetVolumeStepInfo(This,pnStep,pnStepCount)	\
-    ( (This)->lpVtbl -> GetVolumeStepInfo(This,pnStep,pnStepCount) ) 
-
-#define IAudioEndpointVolume_VolumeStepUp(This,pguidEventContext)	\
-    ( (This)->lpVtbl -> VolumeStepUp(This,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_VolumeStepDown(This,pguidEventContext)	\
-    ( (This)->lpVtbl -> VolumeStepDown(This,pguidEventContext) ) 
-
-#define IAudioEndpointVolume_QueryHardwareSupport(This,pdwHardwareSupportMask)	\
-    ( (This)->lpVtbl -> QueryHardwareSupport(This,pdwHardwareSupportMask) ) 
-
-#define IAudioEndpointVolume_GetVolumeRange(This,pflVolumeMindB,pflVolumeMaxdB,pflVolumeIncrementdB)	\
-    ( (This)->lpVtbl -> GetVolumeRange(This,pflVolumeMindB,pflVolumeMaxdB,pflVolumeIncrementdB) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioEndpointVolume_INTERFACE_DEFINED__ */
-
-
-#ifndef __IAudioMeterInformation_INTERFACE_DEFINED__
-#define __IAudioMeterInformation_INTERFACE_DEFINED__
-
-/* interface IAudioMeterInformation */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IAudioMeterInformation;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("C02216F6-8C67-4B5B-9D00-D008E73E0064")
-    IAudioMeterInformation : public IUnknown
-    {
-    public:
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetPeakValue( 
-            /* [out] */ float *pfPeak) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetMeteringChannelCount( 
-            /* [out] */ 
-            __out  UINT *pnChannelCount) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetChannelsPeakValues( 
-            /* [in] */ UINT32 u32ChannelCount,
-            /* [size_is][out] */ float *afPeakValues) = 0;
-        
-        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE QueryHardwareSupport( 
-            /* [out] */ 
-            __out  DWORD *pdwHardwareSupportMask) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IAudioMeterInformationVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IAudioMeterInformation * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IAudioMeterInformation * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IAudioMeterInformation * This);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetPeakValue )( 
-            IAudioMeterInformation * This,
-            /* [out] */ float *pfPeak);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetMeteringChannelCount )( 
-            IAudioMeterInformation * This,
-            /* [out] */ 
-            __out  UINT *pnChannelCount);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetChannelsPeakValues )( 
-            IAudioMeterInformation * This,
-            /* [in] */ UINT32 u32ChannelCount,
-            /* [size_is][out] */ float *afPeakValues);
-        
-        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *QueryHardwareSupport )( 
-            IAudioMeterInformation * This,
-            /* [out] */ 
-            __out  DWORD *pdwHardwareSupportMask);
-        
-        END_INTERFACE
-    } IAudioMeterInformationVtbl;
-
-    interface IAudioMeterInformation
-    {
-        CONST_VTBL struct IAudioMeterInformationVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IAudioMeterInformation_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IAudioMeterInformation_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IAudioMeterInformation_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IAudioMeterInformation_GetPeakValue(This,pfPeak)	\
-    ( (This)->lpVtbl -> GetPeakValue(This,pfPeak) ) 
-
-#define IAudioMeterInformation_GetMeteringChannelCount(This,pnChannelCount)	\
-    ( (This)->lpVtbl -> GetMeteringChannelCount(This,pnChannelCount) ) 
-
-#define IAudioMeterInformation_GetChannelsPeakValues(This,u32ChannelCount,afPeakValues)	\
-    ( (This)->lpVtbl -> GetChannelsPeakValues(This,u32ChannelCount,afPeakValues) ) 
-
-#define IAudioMeterInformation_QueryHardwareSupport(This,pdwHardwareSupportMask)	\
-    ( (This)->lpVtbl -> QueryHardwareSupport(This,pdwHardwareSupportMask) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IAudioMeterInformation_INTERFACE_DEFINED__ */
-
-
-/* Additional Prototypes for ALL interfaces */
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/functiondiscoverykeys.h b/portaudio/src/hostapi/wasapi/mingw-include/functiondiscoverykeys.h
deleted file mode 100644
index a298e4d0f..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/functiondiscoverykeys.h
+++ /dev/null
@@ -1,255 +0,0 @@
-#pragma once
-
-#if __GNUC__ >=3
-#pragma GCC system_header
-#endif
-
-#ifndef DEFINE_API_PKEY
-#include <propkey.h>
-#endif
-
-#include <FunctionDiscoveryKeys_devpkey.h>
-
-// FMTID_FD = {904b03a2-471d-423c-a584-f3483238a146}
-DEFINE_GUID(FMTID_FD, 0x904b03a2, 0x471d, 0x423c, 0xa5, 0x84, 0xf3, 0x48, 0x32, 0x38, 0xa1, 0x46);
-DEFINE_API_PKEY(PKEY_FD_Visibility, VisibilityFlags, 0x904b03a2, 0x471d, 0x423c, 0xa5, 0x84, 0xf3, 0x48, 0x32, 0x38, 0xa1, 0x46, 0x00000001); //    VT_UINT
-#define FD_Visibility_Default   0
-#define FD_Visibility_Hidden    1
-
-// FMTID_Device = {78C34FC8-104A-4aca-9EA4-524D52996E57}
-DEFINE_GUID(FMTID_Device, 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57);
-
-DEFINE_API_PKEY(PKEY_Device_NotPresent,     DeviceNotPresent   , 0x904b03a2, 0x471d, 0x423c, 0xa5, 0x84, 0xf3, 0x48, 0x32, 0x38, 0xa1, 0x46, 0x00000002); //    VT_UINT
-DEFINE_API_PKEY(PKEY_Device_QueueSize,      DeviceQueueSize    , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000024); //    VT_UI4
-DEFINE_API_PKEY(PKEY_Device_Status,         DeviceStatus       , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000025); //    VT_LPWSTR
-DEFINE_API_PKEY(PKEY_Device_Comment,        DeviceComment      , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000026); //    VT_LPWSTR
-DEFINE_API_PKEY(PKEY_Device_Model,          DeviceModel        , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000027); //    VT_LPWSTR
-
-//  Name:     System.Device.BIOSVersion -- PKEY_Device_BIOSVersion
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)  Legacy code may treat this as VT_BSTR.
-//  FormatID: EAEE7F1D-6A33-44D1-9441-5F46DEF23198, 9
-DEFINE_PROPERTYKEY(PKEY_Device_BIOSVersion, 0xEAEE7F1D, 0x6A33, 0x44D1, 0x94, 0x41, 0x5F, 0x46, 0xDE, 0xF2, 0x31, 0x98, 9);
-
-DEFINE_API_PKEY(PKEY_Write_Time,            WriteTime          , 0xf53b7e1c, 0x77e0, 0x4450, 0x8c, 0x5f, 0xa7, 0x6c, 0xc7, 0xfd, 0xe0, 0x58, 0x00000100); //    VT_FILETIME
-
-#ifdef FD_XP
-DEFINE_API_PKEY(PKEY_Device_InstanceId, DeviceInstanceId   , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000100); //    VT_LPWSTR
-#endif
-DEFINE_API_PKEY(PKEY_Device_Interface,  DeviceInterface    , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000101); //    VT_CLSID
-
-DEFINE_API_PKEY(PKEY_ExposedIIDs,           ExposedIIDs       , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00003002); //  VT_VECTOR | VT_CLSID
-DEFINE_API_PKEY(PKEY_ExposedCLSIDs,         ExposedCLSIDs     , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00003003); //  VT_VECTOR | VT_CLSID
-DEFINE_API_PKEY(PKEY_InstanceValidatorClsid,InstanceValidator , 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00003004); // VT_CLSID
-
-// FMTID_WSD = {92506491-FF95-4724-A05A-5B81885A7C92}
-DEFINE_GUID(FMTID_WSD, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92);
-
-DEFINE_API_PKEY(PKEY_WSD_AddressURI, WSD_AddressURI, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001000);   // VT_LPWSTR
-DEFINE_API_PKEY(PKEY_WSD_Types, WSD_Types, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001001); // VT_LPWSTR
-DEFINE_API_PKEY(PKEY_WSD_Scopes, WSD_Scopes, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001002);   // VT_LPWSTR
-DEFINE_API_PKEY(PKEY_WSD_MetadataVersion, WSD_MetadataVersion, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001003); //VT_UI8
-DEFINE_API_PKEY(PKEY_WSD_AppSeqInstanceID, WSD_AppSeqInstanceID, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001004);   // VT_UI8
-DEFINE_API_PKEY(PKEY_WSD_AppSeqSessionID, WSD_AppSeqSessionID, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001005); // VT_LPWSTR
-DEFINE_API_PKEY(PKEY_WSD_AppSeqMessageNumber, WSD_AppSeqMessageNumber, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00001006); // VT_UI8
-DEFINE_API_PKEY(PKEY_WSD_XAddrs, WSD_XAddrs, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00002000); // VT_LPWSTR or VT_VECTOR | VT_LPWSTR
-
-DEFINE_API_PKEY(PKEY_WSD_MetadataClean, WSD_MetadataClean, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00000001);   // VT_BOOL
-DEFINE_API_PKEY(PKEY_WSD_ServiceInfo, WSD_ServiceInfo, 0x92506491, 0xFF95, 0x4724, 0xA0, 0x5A, 0x5B, 0x81, 0x88, 0x5A, 0x7C, 0x92, 0x00000002);   // VT_VECTOR|VT_VARIANT (variants are VT_UNKNOWN)
-
-DEFINE_API_PKEY(PKEY_PUBSVCS_TYPE, PUBSVCS_TYPE, 0xF1B88AD3, 0x109C, 0x4FD2, 0xBA, 0x3F, 0x53, 0x5A, 0x76, 0x5F, 0x82, 0xF4, 0x00005001); // VT_LPWSTR
-DEFINE_API_PKEY(PKEY_PUBSVCS_SCOPE, PUBSVCS_SCOPE, 0x2AE2B567, 0xEECB, 0x4A3E, 0xB7, 0x53, 0x54, 0xC7, 0x25, 0x49, 0x43, 0x66, 0x00005002);   // VT_LPWSTR | VT_VECTOR
-DEFINE_API_PKEY(PKEY_PUBSVCS_METADATA, PUBSVCS_METADATA, 0x63C6D5B8, 0xF73A, 0x4ACA, 0x96, 0x7E, 0x0C, 0xC7, 0x87, 0xE0, 0xB5, 0x59, 0x00005003); // VT_LPWSTR
-DEFINE_API_PKEY(PKEY_PUBSVCS_METADATA_VERSION, PUBSVCS_METADATA_VERSION, 0xC0C96C15, 0x1823, 0x4E5B, 0x93, 0x48, 0xE8, 0x25, 0x19, 0x92, 0x3F, 0x04, 0x00005004); // VT_UI8
-DEFINE_API_PKEY(PKEY_PUBSVCS_NETWORK_PROFILES_ALLOWED, PUBSVCS_NETWORK_PROFILES_ALLOWED, 0x63C6D5B8, 0xF73A, 0x4ACA, 0x96, 0x7E, 0x0C, 0xC7, 0x87, 0xE0, 0xB5, 0x59, 0x00005005); // VT_VECTOR | VT_LPWSTR
-DEFINE_API_PKEY(PKEY_PUBSVCS_NETWORK_PROFILES_DENIED, PUBSVCS_NETWORK_PROFILES_DENIED, 0x63C6D5B8, 0xF73A, 0x4ACA, 0x96, 0x7E, 0x0C, 0xC7, 0x87, 0xE0, 0xB5, 0x59, 0x00005006); // VT_VECTOR | VT_LPWSTR
-DEFINE_API_PKEY(PKEY_PUBSVCS_NETWORK_PROFILES_DEFAULT, PUBSVCS_NETWORK_PROFILES_DEFAULT, 0x63C6D5B8, 0xF73A, 0x4ACA, 0x96, 0x7E, 0x0C, 0xC7, 0x87, 0xE0, 0xB5, 0x59, 0x00005007); // VT_BOOL
-
-// FMTID_PNPX = {656A3BB3-ECC0-43FD-8477-4AE0404A96CD}
-DEFINE_GUID(FMTID_PNPX, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD);
-        // from Discovery messages
-DEFINE_PROPERTYKEY(PKEY_PNPX_GlobalIdentity, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001000);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_Types, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001001);   // VT_LPWSTR | VT_VECTOR
-DEFINE_PROPERTYKEY(PKEY_PNPX_Scopes, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001002);   // VT_LPWSTR | VT_VECTOR
-DEFINE_PROPERTYKEY(PKEY_PNPX_XAddrs, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001003);   // VT_LPWSTR | VT_VECTOR
-DEFINE_PROPERTYKEY(PKEY_PNPX_MetadataVersion, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001004);   // VT_UI8
-DEFINE_PROPERTYKEY(PKEY_PNPX_ID, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001005);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_RootProxy, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001006);   // VT_BOOL
-
-        // for Directed Discovery
-DEFINE_PROPERTYKEY(PKEY_PNPX_RemoteAddress, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00001006);   // VT_LPWSTR
-
-        // from ThisModel metadata
-DEFINE_PROPERTYKEY(PKEY_PNPX_Manufacturer, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002000);   // VT_LPWSTR (localizable)
-DEFINE_PROPERTYKEY(PKEY_PNPX_ManufacturerUrl, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002001);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_ModelName, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002002);   // VT_LPWSTR (localizable)
-DEFINE_PROPERTYKEY(PKEY_PNPX_ModelNumber, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002003);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_ModelUrl, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002004);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_Upc, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002005);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_PresentationUrl, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00002006);   // VT_LPWSTR
-        // from ThisDevice metadata
-DEFINE_PROPERTYKEY(PKEY_PNPX_FriendlyName, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003000);   // VT_LPWSTR (localizable)
-DEFINE_PROPERTYKEY(PKEY_PNPX_FirmwareVersion, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003001);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_SerialNumber, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003002);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_DeviceCategory, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003004);   // VT_LPWSTR | VT_VECTOR
-        // DeviceCategory values
-#define PNPX_DEVICECATEGORY_COMPUTER                            L"Computers"
-#define PNPX_DEVICECATEGORY_INPUTDEVICE                         L"Input"
-#define PNPX_DEVICECATEGORY_PRINTER                             L"Printers"
-#define PNPX_DEVICECATEGORY_SCANNER                             L"Scanners"
-#define PNPX_DEVICECATEGORY_FAX                                 L"FAX"
-#define PNPX_DEVICECATEGORY_MFP                                 L"MFP"
-#define PNPX_DEVICECATEGORY_CAMERA                              L"Cameras"
-#define PNPX_DEVICECATEGORY_STORAGE                             L"Storage"
-#define PNPX_DEVICECATEGORY_NETWORK_INFRASTRUCTURE              L"NetworkInfrastructure"
-#define PNPX_DEVICECATEGORY_DISPLAYS                            L"Displays"
-#define PNPX_DEVICECATEGORY_MULTIMEDIA_DEVICE                   L"MediaDevices"
-#define PNPX_DEVICECATEGORY_GAMING_DEVICE                       L"Gaming"
-#define PNPX_DEVICECATEGORY_TELEPHONE                           L"Phones"
-#define PNPX_DEVICECATEGORY_HOME_AUTOMATION_SYSTEM              L"HomeAutomation"
-#define PNPX_DEVICECATEGORY_HOME_SECURITY_SYSTEM                L"HomeSecurity"
-#define PNPX_DEVICECATEGORY_OTHER                               L"Other"
-DEFINE_PROPERTYKEY(PKEY_PNPX_DeviceCategory_Desc, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003005);   // VT_LPWSTR | VT_VECTOR
-
-DEFINE_PROPERTYKEY(PKEY_PNPX_PhysicalAddress, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003006);   // VT_UI1 | VT_VECTOR
-DEFINE_PROPERTYKEY(PKEY_PNPX_NetworkInterfaceLuid, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003007);   // VT_UI8
-DEFINE_PROPERTYKEY(PKEY_PNPX_NetworkInterfaceGuid, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003008);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_IpAddress, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00003009);   // VT_LPWSTR | VT_VECTOR
-        // from Relationship metadata
-DEFINE_PROPERTYKEY(PKEY_PNPX_ServiceAddress, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00004000);   // VT_LPWSTR | VT_VECTOR
-DEFINE_PROPERTYKEY(PKEY_PNPX_ServiceId, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00004001);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_ServiceTypes, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00004002);   // VT_LPWSTR | VT_VECTOR
-        // Association DB PKEYs
-DEFINE_API_PKEY(PKEY_PNPX_Devnode, PnPXDevNode, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00000001); // VT_BOOL
-DEFINE_API_PKEY(PKEY_PNPX_AssociationState, AssociationState, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00000002); // VT_UINT
-DEFINE_API_PKEY(PKEY_PNPX_AssociatedInstanceId, AssociatedInstanceId, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00000003); // VT_LPWSTR
-        // for Computer Discovery
-DEFINE_PROPERTYKEY(PKEY_PNPX_DomainName, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00005000);   // VT_LPWSTR
-// Use PKEY_ComputerName (propkey.h) DEFINE_PROPERTYKEY(PKEY_PNPX_MachineName, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00005001);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_PNPX_ShareName, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00005002);   // VT_LPWSTR
-
-    // SSDP Provider custom properties
-DEFINE_PROPERTYKEY(PKEY_SSDP_AltLocationInfo, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00006000);   // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_SSDP_DevLifeTime, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00006001);   // VT_UI4
-DEFINE_PROPERTYKEY(PKEY_SSDP_NetworkInterface, 0x656A3BB3, 0xECC0, 0x43FD, 0x84, 0x77, 0x4A, 0xE0, 0x40, 0x4A, 0x96, 0xCD, 0x00006002);   // VT_BOOL
-
-// FMTID_PNPXDynamicProperty = {4FC5077E-B686-44BE-93E3-86CAFE368CCD}
-DEFINE_GUID(FMTID_PNPXDynamicProperty, 0x4FC5077E, 0xB686, 0x44BE, 0x93, 0xE3, 0x86, 0xCA, 0xFE, 0x36, 0x8C, 0xCD);
-
-DEFINE_PROPERTYKEY(PKEY_PNPX_Installable, 0x4FC5077E, 0xB686, 0x44BE, 0x93, 0xE3, 0x86, 0xCA, 0xFE, 0x36, 0x8C, 0xCD, 0x00000001); // VT_BOOL
-DEFINE_PROPERTYKEY(PKEY_PNPX_Associated, 0x4FC5077E, 0xB686, 0x44BE, 0x93, 0xE3, 0x86, 0xCA, 0xFE, 0x36, 0x8C, 0xCD, 0x00000002); // VT_BOOL
-// PKEY_PNPX_Installed to be deprecated in Longhorn Server timeframe
-// this PKEY really represents Associated state
-#define PKEY_PNPX_Installed PKEY_PNPX_Associated    // Deprecated! Please use PKEY_PNPX_Associated
-DEFINE_PROPERTYKEY(PKEY_PNPX_CompatibleTypes, 0x4FC5077E, 0xB686, 0x44BE, 0x93, 0xE3, 0x86, 0xCA, 0xFE, 0x36, 0x8C, 0xCD, 0x00000003); // VT_LPWSTR | VT_VECTOR
-
-    // WNET Provider properties
-DEFINE_PROPERTYKEY(PKEY_WNET_Scope, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000001); // VT_UINT
-DEFINE_PROPERTYKEY(PKEY_WNET_Type, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000002); // VT_UINT
-DEFINE_PROPERTYKEY(PKEY_WNET_DisplayType, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000003); // VT_UINT
-DEFINE_PROPERTYKEY(PKEY_WNET_Usage, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000004); // VT_UINT
-DEFINE_PROPERTYKEY(PKEY_WNET_LocalName, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000005); // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_WNET_RemoteName, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000006); // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_WNET_Comment, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000007); // VT_LPWSTR
-DEFINE_PROPERTYKEY(PKEY_WNET_Provider, 0xdebda43a, 0x37b3, 0x4383, 0x91, 0xE7, 0x44, 0x98, 0xda, 0x29, 0x95, 0xab, 0x00000008); // VT_LPWSTR
-
-
-    // WCN Provider properties
-
-DEFINE_PROPERTYKEY(PKEY_WCN_Version, 0x88190b80, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000001); // VT_UI1
-DEFINE_PROPERTYKEY(PKEY_WCN_RequestType, 0x88190b81, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000002); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_AuthType, 0x88190b82, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000003); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_EncryptType, 0x88190b83, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000004); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_ConnType, 0x88190b84, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000005); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_ConfigMethods, 0x88190b85, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000006); // VT_INT
-// map WCN DeviceType to PKEY_PNPX_DeviceCategory
-//DEFINE_PROPERTYKEY(PKEY_WCN_DeviceType, 0x88190b86, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000007); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_RfBand, 0x88190b87, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000008); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_AssocState, 0x88190b88, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x00000009); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_ConfigError, 0x88190b89, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x0000000a); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_ConfigState, 0x88190b89, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x0000000b); // VT_UI1
-DEFINE_PROPERTYKEY(PKEY_WCN_DevicePasswordId, 0x88190b89, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x0000000c); // VT_INT
-DEFINE_PROPERTYKEY(PKEY_WCN_OSVersion, 0x88190b89, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x0000000d); // VT_UINT
-DEFINE_PROPERTYKEY(PKEY_WCN_VendorExtension, 0x88190b8a, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x0000000e); // VT_UI1 | VT_VECTOR
-DEFINE_PROPERTYKEY(PKEY_WCN_RegistrarType, 0x88190b8b, 0x4684, 0x11da, 0xa2, 0x6a, 0x00, 0x02, 0xb3, 0x98, 0x8e, 0x81, 0x0000000f); // VT_INT
-
-//-----------------------------------------------------------------------------
-// DriverPackage properties
-
-#define PKEY_DriverPackage_Model                PKEY_DrvPkg_Model
-#define PKEY_DriverPackage_VendorWebSite        PKEY_DrvPkg_VendorWebSite
-#define PKEY_DriverPackage_DetailedDescription  PKEY_DrvPkg_DetailedDescription
-#define PKEY_DriverPackage_DocumentationLink    PKEY_DrvPkg_DocumentationLink
-#define PKEY_DriverPackage_Icon                 PKEY_DrvPkg_Icon
-#define PKEY_DriverPackage_BrandingIcon         PKEY_DrvPkg_BrandingIcon
-
-//-----------------------------------------------------------------------------
-// Hardware properties
-
-DEFINE_PROPERTYKEY(PKEY_Hardware_Devinst, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 4097);
-
-//  Name:     System.Hardware.DisplayAttribute -- PKEY_Hardware_DisplayAttribute
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 5
-DEFINE_PROPERTYKEY(PKEY_Hardware_DisplayAttribute, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 5);
-
-//  Name:     System.Hardware.DriverDate -- PKEY_Hardware_DriverDate
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 11
-DEFINE_PROPERTYKEY(PKEY_Hardware_DriverDate, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 11);
-
-//  Name:     System.Hardware.DriverProvider -- PKEY_Hardware_DriverProvider
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 10
-DEFINE_PROPERTYKEY(PKEY_Hardware_DriverProvider, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 10);
-
-//  Name:     System.Hardware.DriverVersion -- PKEY_Hardware_DriverVersion
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 9
-DEFINE_PROPERTYKEY(PKEY_Hardware_DriverVersion, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 9);
-
-//  Name:     System.Hardware.Function -- PKEY_Hardware_Function
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 4099
-DEFINE_PROPERTYKEY(PKEY_Hardware_Function, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 4099);
-
-//  Name:     System.Hardware.Icon -- PKEY_Hardware_Icon
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 3
-DEFINE_PROPERTYKEY(PKEY_Hardware_Icon, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 3);
-
-//  Name:     System.Hardware.Image -- PKEY_Hardware_Image
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 4098
-DEFINE_PROPERTYKEY(PKEY_Hardware_Image, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 4098);
-
-//  Name:     System.Hardware.Manufacturer -- PKEY_Hardware_Manufacturer
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 6
-DEFINE_PROPERTYKEY(PKEY_Hardware_Manufacturer, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 6);
-
-//  Name:     System.Hardware.Model -- PKEY_Hardware_Model
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 7
-DEFINE_PROPERTYKEY(PKEY_Hardware_Model, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 7);
-
-//  Name:     System.Hardware.Name -- PKEY_Hardware_Name
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 2
-DEFINE_PROPERTYKEY(PKEY_Hardware_Name, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 2);
-
-//  Name:     System.Hardware.SerialNumber -- PKEY_Hardware_SerialNumber
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 8
-DEFINE_PROPERTYKEY(PKEY_Hardware_SerialNumber, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 8);
-
-//  Name:     System.Hardware.ShellAttributes -- PKEY_Hardware_ShellAttributes
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 4100
-DEFINE_PROPERTYKEY(PKEY_Hardware_ShellAttributes, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 4100);
-
-//  Name:     System.Hardware.Status -- PKEY_Hardware_Status
-//  Type:     Unspecified -- VT_NULL
-//  FormatID: 5EAF3EF2-E0CA-4598-BF06-71ED1D9DD953, 4096
-DEFINE_PROPERTYKEY(PKEY_Hardware_Status, 0x5EAF3EF2, 0xE0CA, 0x4598, 0xBF, 0x06, 0x71, 0xED, 0x1D, 0x9D, 0xD9, 0x53, 4096);
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ks.h b/portaudio/src/hostapi/wasapi/mingw-include/ks.h
deleted file mode 100644
index 2261e6c27..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/ks.h
+++ /dev/null
@@ -1,3666 +0,0 @@
-/**
- * This file has no copyright assigned and is placed in the Public Domain.
- * This file is part of the w64 mingw-runtime package.
- * No warranty is given; refer to the file DISCLAIMER.PD within this package.
- */
-#ifndef _KS_
-#define _KS_
-
-#if __GNUC__ >= 3
-#pragma GCC system_header
-#endif
-
-#ifndef __MINGW_EXTENSION
-#if defined(__GNUC__) || defined(__GNUG__)
-#define __MINGW_EXTENSION __extension__
-#else
-#define __MINGW_EXTENSION
-#endif
-#endif 
-
-#ifdef __TCS__
-#define _KS_NO_ANONYMOUS_STRUCTURES_ 1
-#endif
-
-#ifdef  _KS_NO_ANONYMOUS_STRUCTURES_
-#define _KS_ANON_STRUCT(X)			struct X
-#else
-#define _KS_ANON_STRUCT(X)	__MINGW_EXTENSION struct
-#endif
-
-#ifndef _NTRTL_
-#ifndef DEFINE_GUIDEX
-#define DEFINE_GUIDEX(name) EXTERN_C const CDECL GUID name
-#endif
-#ifndef STATICGUIDOF
-#define STATICGUIDOF(guid) STATIC_##guid
-#endif
-#endif /* _NTRTL_ */
-
-#ifndef SIZEOF_ARRAY
-#define SIZEOF_ARRAY(ar) (sizeof(ar)/sizeof((ar)[0]))
-#endif
-
-#define DEFINE_GUIDSTRUCT(g,n) DEFINE_GUIDEX(n)
-#define DEFINE_GUIDNAMED(n) n
-
-#define STATIC_GUID_NULL						\
-	0x00000000L,0x0000,0x0000,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
-
-DEFINE_GUIDSTRUCT("00000000-0000-0000-0000-000000000000",GUID_NULL);
-#define GUID_NULL DEFINE_GUIDNAMED(GUID_NULL)
-
-#define IOCTL_KS_PROPERTY CTL_CODE(FILE_DEVICE_KS,0x000,METHOD_NEITHER,FILE_ANY_ACCESS)
-#define IOCTL_KS_ENABLE_EVENT CTL_CODE(FILE_DEVICE_KS,0x001,METHOD_NEITHER,FILE_ANY_ACCESS)
-#define IOCTL_KS_DISABLE_EVENT CTL_CODE(FILE_DEVICE_KS,0x002,METHOD_NEITHER,FILE_ANY_ACCESS)
-#define IOCTL_KS_METHOD CTL_CODE(FILE_DEVICE_KS,0x003,METHOD_NEITHER,FILE_ANY_ACCESS)
-#define IOCTL_KS_WRITE_STREAM CTL_CODE(FILE_DEVICE_KS,0x004,METHOD_NEITHER,FILE_WRITE_ACCESS)
-#define IOCTL_KS_READ_STREAM CTL_CODE(FILE_DEVICE_KS,0x005,METHOD_NEITHER,FILE_READ_ACCESS)
-#define IOCTL_KS_RESET_STATE CTL_CODE(FILE_DEVICE_KS,0x006,METHOD_NEITHER,FILE_ANY_ACCESS)
-
-typedef enum {
-  KSRESET_BEGIN,
-  KSRESET_END
-} KSRESET;
-
-typedef enum {
-  KSSTATE_STOP,
-  KSSTATE_ACQUIRE,
-  KSSTATE_PAUSE,
-  KSSTATE_RUN
-} KSSTATE,*PKSSTATE;
-
-#define KSPRIORITY_LOW		0x00000001
-#define KSPRIORITY_NORMAL	0x40000000
-#define KSPRIORITY_HIGH		0x80000000
-#define KSPRIORITY_EXCLUSIVE	0xFFFFFFFF
-
-typedef struct {
-  ULONG PriorityClass;
-  ULONG PrioritySubClass;
-} KSPRIORITY,*PKSPRIORITY;
-
-typedef struct {
-  __MINGW_EXTENSION union {
-    _KS_ANON_STRUCT(_IDENTIFIER)
-    {
-      GUID Set;
-      ULONG Id;
-      ULONG Flags;
-    };
-    LONGLONG Alignment;
-  };
-} KSIDENTIFIER,*PKSIDENTIFIER;
-
-typedef KSIDENTIFIER KSPROPERTY,*PKSPROPERTY,KSMETHOD,*PKSMETHOD,KSEVENT,*PKSEVENT;
-
-#define KSMETHOD_TYPE_NONE		0x00000000
-#define KSMETHOD_TYPE_READ		0x00000001
-#define KSMETHOD_TYPE_WRITE		0x00000002
-#define KSMETHOD_TYPE_MODIFY		0x00000003
-#define KSMETHOD_TYPE_SOURCE		0x00000004
-
-#define KSMETHOD_TYPE_SEND		0x00000001
-#define KSMETHOD_TYPE_SETSUPPORT	0x00000100
-#define KSMETHOD_TYPE_BASICSUPPORT	0x00000200
-
-#define KSMETHOD_TYPE_TOPOLOGY		0x10000000
-
-#define KSPROPERTY_TYPE_GET		0x00000001
-#define KSPROPERTY_TYPE_SET		0x00000002
-#define KSPROPERTY_TYPE_SETSUPPORT	0x00000100
-#define KSPROPERTY_TYPE_BASICSUPPORT	0x00000200
-#define KSPROPERTY_TYPE_RELATIONS	0x00000400
-#define KSPROPERTY_TYPE_SERIALIZESET	0x00000800
-#define KSPROPERTY_TYPE_UNSERIALIZESET	0x00001000
-#define KSPROPERTY_TYPE_SERIALIZERAW	0x00002000
-#define KSPROPERTY_TYPE_UNSERIALIZERAW	0x00004000
-#define KSPROPERTY_TYPE_SERIALIZESIZE	0x00008000
-#define KSPROPERTY_TYPE_DEFAULTVALUES	0x00010000
-
-#define KSPROPERTY_TYPE_TOPOLOGY	0x10000000
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG NodeId;
-  ULONG Reserved;
-} KSP_NODE,*PKSP_NODE;
-
-typedef struct {
-  KSMETHOD Method;
-  ULONG NodeId;
-  ULONG Reserved;
-} KSM_NODE,*PKSM_NODE;
-
-typedef struct {
-  KSEVENT Event;
-  ULONG NodeId;
-  ULONG Reserved;
-} KSE_NODE,*PKSE_NODE;
-
-#define STATIC_KSPROPTYPESETID_General					\
-	0x97E99BA0L,0xBDEA,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("97E99BA0-BDEA-11CF-A5D6-28DB04C10000",KSPROPTYPESETID_General);
-#define KSPROPTYPESETID_General DEFINE_GUIDNAMED(KSPROPTYPESETID_General)
-
-typedef struct {
-  ULONG Size;
-  ULONG Count;
-} KSMULTIPLE_ITEM,*PKSMULTIPLE_ITEM;
-
-typedef struct {
-  ULONG AccessFlags;
-  ULONG DescriptionSize;
-  KSIDENTIFIER PropTypeSet;
-  ULONG MembersListCount;
-  ULONG Reserved;
-} KSPROPERTY_DESCRIPTION,*PKSPROPERTY_DESCRIPTION;
-
-#define KSPROPERTY_MEMBER_RANGES		0x00000001
-#define KSPROPERTY_MEMBER_STEPPEDRANGES		0x00000002
-#define KSPROPERTY_MEMBER_VALUES		0x00000003
-
-#define KSPROPERTY_MEMBER_FLAG_DEFAULT		0x00000001
-#define KSPROPERTY_MEMBER_FLAG_BASICSUPPORT_MULTICHANNEL 0x00000002
-#define KSPROPERTY_MEMBER_FLAG_BASICSUPPORT_UNIFORM	0x00000004
-
-typedef struct {
-  ULONG MembersFlags;
-  ULONG MembersSize;
-  ULONG MembersCount;
-  ULONG Flags;
-} KSPROPERTY_MEMBERSHEADER,*PKSPROPERTY_MEMBERSHEADER;
-
-typedef union {
-  _KS_ANON_STRUCT(_SIGNED)
-  {
-    LONG SignedMinimum;
-    LONG SignedMaximum;
-  };
-  _KS_ANON_STRUCT(_UNSIGNED)
-  {
-    ULONG UnsignedMinimum;
-    ULONG UnsignedMaximum;
-  };
-} KSPROPERTY_BOUNDS_LONG,*PKSPROPERTY_BOUNDS_LONG;
-
-typedef union {
-  _KS_ANON_STRUCT(_SIGNED64)
-  {
-    LONGLONG SignedMinimum;
-    LONGLONG SignedMaximum;
-  };
-  _KS_ANON_STRUCT(_UNSIGNED64)
-  {
-    DWORDLONG UnsignedMinimum;
-    DWORDLONG UnsignedMaximum;
-  };
-} KSPROPERTY_BOUNDS_LONGLONG,*PKSPROPERTY_BOUNDS_LONGLONG;
-
-typedef struct {
-  ULONG SteppingDelta;
-  ULONG Reserved;
-  KSPROPERTY_BOUNDS_LONG Bounds;
-} KSPROPERTY_STEPPING_LONG,*PKSPROPERTY_STEPPING_LONG;
-
-typedef struct {
-  DWORDLONG SteppingDelta;
-  KSPROPERTY_BOUNDS_LONGLONG Bounds;
-} KSPROPERTY_STEPPING_LONGLONG,*PKSPROPERTY_STEPPING_LONGLONG;
-
-#if defined(_NTDDK_)
-typedef struct _KSDEVICE_DESCRIPTOR KSDEVICE_DESCRIPTOR, *PKSDEVICE_DESCRIPTOR;
-typedef struct _KSDEVICE_DISPATCH KSDEVICE_DISPATCH, *PKSDEVICE_DISPATCH;
-typedef struct _KSDEVICE KSDEVICE, *PKSDEVICE;
-typedef struct _KSFILTERFACTORY KSFILTERFACTORY, *PKSFILTERFACTORY;
-typedef struct _KSFILTER_DESCRIPTOR KSFILTER_DESCRIPTOR, *PKSFILTER_DESCRIPTOR;
-typedef struct _KSFILTER_DISPATCH KSFILTER_DISPATCH, *PKSFILTER_DISPATCH;
-typedef struct _KSFILTER KSFILTER, *PKSFILTER;
-typedef struct _KSPIN_DESCRIPTOR_EX KSPIN_DESCRIPTOR_EX, *PKSPIN_DESCRIPTOR_EX;
-typedef struct _KSPIN_DISPATCH KSPIN_DISPATCH, *PKSPIN_DISPATCH;
-typedef struct _KSCLOCK_DISPATCH KSCLOCK_DISPATCH, *PKSCLOCK_DISPATCH;
-typedef struct _KSALLOCATOR_DISPATCH KSALLOCATOR_DISPATCH, *PKSALLOCATOR_DISPATCH;
-typedef struct _KSPIN KSPIN, *PKSPIN;
-typedef struct _KSNODE_DESCRIPTOR KSNODE_DESCRIPTOR, *PKSNODE_DESCRIPTOR;
-typedef struct _KSSTREAM_POINTER_OFFSET KSSTREAM_POINTER_OFFSET, *PKSSTREAM_POINTER_OFFSET;
-typedef struct _KSSTREAM_POINTER KSSTREAM_POINTER, *PKSSTREAM_POINTER;
-typedef struct _KSMAPPING KSMAPPING, *PKSMAPPING;
-typedef struct _KSPROCESSPIN KSPROCESSPIN, *PKSPROCESSPIN;
-typedef struct _KSPROCESSPIN_INDEXENTRY KSPROCESSPIN_INDEXENTRY, *PKSPROCESSPIN_INDEXENTRY;
-#endif /* _NTDDK_ */
-
-typedef PVOID PKSWORKER;
-
-
-typedef struct {
-  ULONG NotificationType;
-  __MINGW_EXTENSION union {
-    struct {
-      HANDLE Event;
-      ULONG_PTR Reserved[2];
-    } EventHandle;
-    struct {
-      HANDLE Semaphore;
-      ULONG Reserved;
-      LONG Adjustment;
-    } SemaphoreHandle;
-#if defined(_NTDDK_)
-    struct {
-      PVOID Event;
-      KPRIORITY Increment;
-      ULONG_PTR Reserved;
-    } EventObject;
-    struct {
-      PVOID Semaphore;
-      KPRIORITY Increment;
-      LONG Adjustment;
-    } SemaphoreObject;
-    struct {
-      PKDPC Dpc;
-      ULONG ReferenceCount;
-      ULONG_PTR Reserved;
-    } Dpc;
-    struct {
-      PWORK_QUEUE_ITEM WorkQueueItem;
-      WORK_QUEUE_TYPE WorkQueueType;
-      ULONG_PTR Reserved;
-    } WorkItem;
-    struct {
-      PWORK_QUEUE_ITEM WorkQueueItem;
-      PKSWORKER KsWorkerObject;
-      ULONG_PTR Reserved;
-    } KsWorkItem;
-#endif /* _NTDDK_ */
-    struct {
-      PVOID Unused;
-      LONG_PTR Alignment[2];
-    } Alignment;
-  };
-} KSEVENTDATA,*PKSEVENTDATA;
-
-#define KSEVENTF_EVENT_HANDLE		0x00000001
-#define KSEVENTF_SEMAPHORE_HANDLE	0x00000002
-#if defined(_NTDDK_)
-#define KSEVENTF_EVENT_OBJECT		0x00000004
-#define KSEVENTF_SEMAPHORE_OBJECT	0x00000008
-#define KSEVENTF_DPC			0x00000010
-#define KSEVENTF_WORKITEM		0x00000020
-#define KSEVENTF_KSWORKITEM		0x00000080
-#endif /* _NTDDK_ */
-
-#define KSEVENT_TYPE_ENABLE		0x00000001
-#define KSEVENT_TYPE_ONESHOT		0x00000002
-#define KSEVENT_TYPE_ENABLEBUFFERED	0x00000004
-#define KSEVENT_TYPE_SETSUPPORT		0x00000100
-#define KSEVENT_TYPE_BASICSUPPORT	0x00000200
-#define KSEVENT_TYPE_QUERYBUFFER	0x00000400
-
-#define KSEVENT_TYPE_TOPOLOGY		0x10000000
-
-typedef struct {
-  KSEVENT Event;
-  PKSEVENTDATA EventData;
-  PVOID Reserved;
-} KSQUERYBUFFER,*PKSQUERYBUFFER;
-
-typedef struct {
-  ULONG Size;
-  ULONG Flags;
-  __MINGW_EXTENSION union {
-    HANDLE ObjectHandle;
-    PVOID ObjectPointer;
-  };
-  PVOID Reserved;
-  KSEVENT Event;
-  KSEVENTDATA EventData;
-} KSRELATIVEEVENT;
-
-#define KSRELATIVEEVENT_FLAG_HANDLE	0x00000001
-#define KSRELATIVEEVENT_FLAG_POINTER	0x00000002
-
-typedef struct {
-  KSEVENTDATA EventData;
-  LONGLONG MarkTime;
-} KSEVENT_TIME_MARK,*PKSEVENT_TIME_MARK;
-
-typedef struct {
-  KSEVENTDATA EventData;
-  LONGLONG TimeBase;
-  LONGLONG Interval;
-} KSEVENT_TIME_INTERVAL,*PKSEVENT_TIME_INTERVAL;
-
-typedef struct {
-  LONGLONG TimeBase;
-  LONGLONG Interval;
-} KSINTERVAL,*PKSINTERVAL;
-
-#define STATIC_KSPROPSETID_General					\
-	0x1464EDA5L,0x6A8F,0x11D1,0x9A,0xA7,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("1464EDA5-6A8F-11D1-9AA7-00A0C9223196",KSPROPSETID_General);
-#define KSPROPSETID_General DEFINE_GUIDNAMED(KSPROPSETID_General)
-
-typedef enum {
-  KSPROPERTY_GENERAL_COMPONENTID
-} KSPROPERTY_GENERAL;
-
-typedef struct {
-  GUID Manufacturer;
-  GUID Product;
-  GUID Component;
-  GUID Name;
-  ULONG Version;
-  ULONG Revision;
-} KSCOMPONENTID,*PKSCOMPONENTID;
-
-#define DEFINE_KSPROPERTY_ITEM_GENERAL_COMPONENTID(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_GENERAL_COMPONENTID,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSCOMPONENTID),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define STATIC_KSMETHODSETID_StreamIo	\
-	0x65D003CAL,0x1523,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("65D003CA-1523-11D2-B27A-00A0C9223196",KSMETHODSETID_StreamIo);
-#define KSMETHODSETID_StreamIo DEFINE_GUIDNAMED(KSMETHODSETID_StreamIo)
-
-typedef enum {
-  KSMETHOD_STREAMIO_READ,
-  KSMETHOD_STREAMIO_WRITE
-} KSMETHOD_STREAMIO;
-
-#define DEFINE_KSMETHOD_ITEM_STREAMIO_READ(Handler)			\
-	DEFINE_KSMETHOD_ITEM(						\
-				KSMETHOD_STREAMIO_READ,			\
-				KSMETHOD_TYPE_WRITE,			\
-				(Handler),				\
-				sizeof(KSMETHOD),			\
-				0,					\
-				NULL)
-
-#define DEFINE_KSMETHOD_ITEM_STREAMIO_WRITE(Handler)			\
-	DEFINE_KSMETHOD_ITEM(						\
-				KSMETHOD_STREAMIO_WRITE,		\
-				KSMETHOD_TYPE_READ,			\
-				(Handler),				\
-				sizeof(KSMETHOD),			\
-				0,					\
-				NULL)
-
-#define STATIC_KSPROPSETID_MediaSeeking					\
-	0xEE904F0CL,0xD09B,0x11D0,0xAB,0xE9,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("EE904F0C-D09B-11D0-ABE9-00A0C9223196",KSPROPSETID_MediaSeeking);
-#define KSPROPSETID_MediaSeeking DEFINE_GUIDNAMED(KSPROPSETID_MediaSeeking)
-
-typedef enum {
-  KSPROPERTY_MEDIASEEKING_CAPABILITIES,
-  KSPROPERTY_MEDIASEEKING_FORMATS,
-  KSPROPERTY_MEDIASEEKING_TIMEFORMAT,
-  KSPROPERTY_MEDIASEEKING_POSITION,
-  KSPROPERTY_MEDIASEEKING_STOPPOSITION,
-  KSPROPERTY_MEDIASEEKING_POSITIONS,
-  KSPROPERTY_MEDIASEEKING_DURATION,
-  KSPROPERTY_MEDIASEEKING_AVAILABLE,
-  KSPROPERTY_MEDIASEEKING_PREROLL,
-  KSPROPERTY_MEDIASEEKING_CONVERTTIMEFORMAT
-} KSPROPERTY_MEDIASEEKING;
-
-typedef enum {
-  KS_SEEKING_NoPositioning,
-  KS_SEEKING_AbsolutePositioning,
-  KS_SEEKING_RelativePositioning,
-  KS_SEEKING_IncrementalPositioning,
-  KS_SEEKING_PositioningBitsMask = 0x3,
-  KS_SEEKING_SeekToKeyFrame,
-  KS_SEEKING_ReturnTime = 0x8
-} KS_SEEKING_FLAGS;
-
-typedef enum {
-  KS_SEEKING_CanSeekAbsolute = 0x1,
-  KS_SEEKING_CanSeekForwards = 0x2,
-  KS_SEEKING_CanSeekBackwards = 0x4,
-  KS_SEEKING_CanGetCurrentPos = 0x8,
-  KS_SEEKING_CanGetStopPos = 0x10,
-  KS_SEEKING_CanGetDuration = 0x20,
-  KS_SEEKING_CanPlayBackwards = 0x40
-} KS_SEEKING_CAPABILITIES;
-
-typedef struct {
-  LONGLONG Current;
-  LONGLONG Stop;
-  KS_SEEKING_FLAGS CurrentFlags;
-  KS_SEEKING_FLAGS StopFlags;
-} KSPROPERTY_POSITIONS,*PKSPROPERTY_POSITIONS;
-
-typedef struct {
-  LONGLONG Earliest;
-  LONGLONG Latest;
-} KSPROPERTY_MEDIAAVAILABLE,*PKSPROPERTY_MEDIAAVAILABLE;
-
-typedef struct {
-  KSPROPERTY Property;
-  GUID SourceFormat;
-  GUID TargetFormat;
-  LONGLONG Time;
-} KSP_TIMEFORMAT,*PKSP_TIMEFORMAT;
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_CAPABILITIES(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_CAPABILITIES,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KS_SEEKING_CAPABILITIES),	\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_FORMATS(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_FORMATS,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_TIMEFORMAT(GetHandler,SetHandler) \
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_TIMEFORMAT,	\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(GUID),				\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_POSITION(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_POSITION,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(LONGLONG),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_STOPPOSITION(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_STOPPOSITION,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(LONGLONG),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_POSITIONS(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_POSITIONS,	\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSPROPERTY_POSITIONS),		\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_DURATION(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_DURATION,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(LONGLONG),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_AVAILABLE(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_AVAILABLE,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSPROPERTY_MEDIAAVAILABLE),	\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_PREROLL(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_PREROLL,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(LONGLONG),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_MEDIASEEKING_CONVERTTIMEFORMAT(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_MEDIASEEKING_CONVERTTIMEFORMAT, \
-				(Handler),				\
-				sizeof(KSP_TIMEFORMAT),			\
-				sizeof(LONGLONG),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define STATIC_KSPROPSETID_Topology					\
-	0x720D4AC0L,0x7533,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("720D4AC0-7533-11D0-A5D6-28DB04C10000",KSPROPSETID_Topology);
-#define KSPROPSETID_Topology DEFINE_GUIDNAMED(KSPROPSETID_Topology)
-
-typedef enum {
-  KSPROPERTY_TOPOLOGY_CATEGORIES,
-  KSPROPERTY_TOPOLOGY_NODES,
-  KSPROPERTY_TOPOLOGY_CONNECTIONS,
-  KSPROPERTY_TOPOLOGY_NAME
-} KSPROPERTY_TOPOLOGY;
-
-#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CATEGORIES(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_TOPOLOGY_CATEGORIES,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				NULL, NULL, 0,NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NODES(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_TOPOLOGY_NODES,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CONNECTIONS(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_TOPOLOGY_CONNECTIONS,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NAME(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_TOPOLOGY_NAME,		\
-				(Handler),				\
-				sizeof(KSP_NODE),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_TOPOLOGYSET(TopologySet,Handler)		\
-DEFINE_KSPROPERTY_TABLE(TopologySet) {					\
-	DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CATEGORIES(Handler),		\
-	DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NODES(Handler),			\
-	DEFINE_KSPROPERTY_ITEM_TOPOLOGY_CONNECTIONS(Handler),		\
-	DEFINE_KSPROPERTY_ITEM_TOPOLOGY_NAME(Handler)			\
-}
-
-#define STATIC_KSCATEGORY_BRIDGE					\
-	0x085AFF00L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("085AFF00-62CE-11CF-A5D6-28DB04C10000",KSCATEGORY_BRIDGE);
-#define KSCATEGORY_BRIDGE DEFINE_GUIDNAMED(KSCATEGORY_BRIDGE)
-
-#define STATIC_KSCATEGORY_CAPTURE					\
-	0x65E8773DL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("65E8773D-8F56-11D0-A3B9-00A0C9223196",KSCATEGORY_CAPTURE);
-#define KSCATEGORY_CAPTURE DEFINE_GUIDNAMED(KSCATEGORY_CAPTURE)
-
-#define STATIC_KSCATEGORY_RENDER					\
-	0x65E8773EL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("65E8773E-8F56-11D0-A3B9-00A0C9223196",KSCATEGORY_RENDER);
-#define KSCATEGORY_RENDER DEFINE_GUIDNAMED(KSCATEGORY_RENDER)
-
-#define STATIC_KSCATEGORY_MIXER						\
-	0xAD809C00L,0x7B88,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("AD809C00-7B88-11D0-A5D6-28DB04C10000",KSCATEGORY_MIXER);
-#define KSCATEGORY_MIXER DEFINE_GUIDNAMED(KSCATEGORY_MIXER)
-
-#define STATIC_KSCATEGORY_SPLITTER					\
-	0x0A4252A0L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("0A4252A0-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_SPLITTER);
-#define KSCATEGORY_SPLITTER DEFINE_GUIDNAMED(KSCATEGORY_SPLITTER)
-
-#define STATIC_KSCATEGORY_DATACOMPRESSOR				\
-	0x1E84C900L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("1E84C900-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_DATACOMPRESSOR);
-#define KSCATEGORY_DATACOMPRESSOR DEFINE_GUIDNAMED(KSCATEGORY_DATACOMPRESSOR)
-
-#define STATIC_KSCATEGORY_DATADECOMPRESSOR				\
-	0x2721AE20L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("2721AE20-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_DATADECOMPRESSOR);
-#define KSCATEGORY_DATADECOMPRESSOR DEFINE_GUIDNAMED(KSCATEGORY_DATADECOMPRESSOR)
-
-#define STATIC_KSCATEGORY_DATATRANSFORM					\
-	0x2EB07EA0L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("2EB07EA0-7E70-11D0-A5D6-28DB04C10000",KSCATEGORY_DATATRANSFORM);
-#define KSCATEGORY_DATATRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_DATATRANSFORM)
-
-#define STATIC_KSCATEGORY_COMMUNICATIONSTRANSFORM			\
-	0xCF1DDA2CL,0x9743,0x11D0,0xA3,0xEE,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("CF1DDA2C-9743-11D0-A3EE-00A0C9223196",KSCATEGORY_COMMUNICATIONSTRANSFORM);
-#define KSCATEGORY_COMMUNICATIONSTRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_COMMUNICATIONSTRANSFORM)
-
-#define STATIC_KSCATEGORY_INTERFACETRANSFORM				\
-	0xCF1DDA2DL,0x9743,0x11D0,0xA3,0xEE,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("CF1DDA2D-9743-11D0-A3EE-00A0C9223196",KSCATEGORY_INTERFACETRANSFORM);
-#define KSCATEGORY_INTERFACETRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_INTERFACETRANSFORM)
-
-#define STATIC_KSCATEGORY_MEDIUMTRANSFORM				\
-	0xCF1DDA2EL,0x9743,0x11D0,0xA3,0xEE,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("CF1DDA2E-9743-11D0-A3EE-00A0C9223196",KSCATEGORY_MEDIUMTRANSFORM);
-#define KSCATEGORY_MEDIUMTRANSFORM DEFINE_GUIDNAMED(KSCATEGORY_MEDIUMTRANSFORM)
-
-#define STATIC_KSCATEGORY_FILESYSTEM					\
-	0x760FED5EL,0x9357,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("760FED5E-9357-11D0-A3CC-00A0C9223196",KSCATEGORY_FILESYSTEM);
-#define KSCATEGORY_FILESYSTEM DEFINE_GUIDNAMED(KSCATEGORY_FILESYSTEM)
-
-#define STATIC_KSCATEGORY_CLOCK						\
-	0x53172480L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("53172480-4791-11D0-A5D6-28DB04C10000",KSCATEGORY_CLOCK);
-#define KSCATEGORY_CLOCK DEFINE_GUIDNAMED(KSCATEGORY_CLOCK)
-
-#define STATIC_KSCATEGORY_PROXY						\
-	0x97EBAACAL,0x95BD,0x11D0,0xA3,0xEA,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("97EBAACA-95BD-11D0-A3EA-00A0C9223196",KSCATEGORY_PROXY);
-#define KSCATEGORY_PROXY DEFINE_GUIDNAMED(KSCATEGORY_PROXY)
-
-#define STATIC_KSCATEGORY_QUALITY					\
-	0x97EBAACBL,0x95BD,0x11D0,0xA3,0xEA,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("97EBAACB-95BD-11D0-A3EA-00A0C9223196",KSCATEGORY_QUALITY);
-#define KSCATEGORY_QUALITY DEFINE_GUIDNAMED(KSCATEGORY_QUALITY)
-
-typedef struct {
-  ULONG FromNode;
-  ULONG FromNodePin;
-  ULONG ToNode;
-  ULONG ToNodePin;
-} KSTOPOLOGY_CONNECTION,*PKSTOPOLOGY_CONNECTION;
-
-typedef struct {
-  ULONG CategoriesCount;
-  const GUID *Categories;
-  ULONG TopologyNodesCount;
-  const GUID *TopologyNodes;
-  ULONG TopologyConnectionsCount;
-  const KSTOPOLOGY_CONNECTION *TopologyConnections;
-  const GUID *TopologyNodesNames;
-  ULONG Reserved;
-} KSTOPOLOGY,*PKSTOPOLOGY;
-
-#define KSFILTER_NODE	((ULONG)-1)
-#define KSALL_NODES	((ULONG)-1)
-
-typedef struct {
-  ULONG CreateFlags;
-  ULONG Node;
-} KSNODE_CREATE,*PKSNODE_CREATE;
-
-#define STATIC_KSTIME_FORMAT_NONE	STATIC_GUID_NULL
-#define KSTIME_FORMAT_NONE		GUID_NULL
-
-#define STATIC_KSTIME_FORMAT_FRAME					\
-	0x7b785570L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
-DEFINE_GUIDSTRUCT("7b785570-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_FRAME);
-#define KSTIME_FORMAT_FRAME DEFINE_GUIDNAMED(KSTIME_FORMAT_FRAME)
-
-#define STATIC_KSTIME_FORMAT_BYTE					\
-	0x7b785571L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
-DEFINE_GUIDSTRUCT("7b785571-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_BYTE);
-#define KSTIME_FORMAT_BYTE DEFINE_GUIDNAMED(KSTIME_FORMAT_BYTE)
-
-#define STATIC_KSTIME_FORMAT_SAMPLE					\
-	0x7b785572L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
-DEFINE_GUIDSTRUCT("7b785572-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_SAMPLE);
-#define KSTIME_FORMAT_SAMPLE DEFINE_GUIDNAMED(KSTIME_FORMAT_SAMPLE)
-
-#define STATIC_KSTIME_FORMAT_FIELD					\
-	0x7b785573L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
-DEFINE_GUIDSTRUCT("7b785573-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_FIELD);
-#define KSTIME_FORMAT_FIELD DEFINE_GUIDNAMED(KSTIME_FORMAT_FIELD)
-
-#define STATIC_KSTIME_FORMAT_MEDIA_TIME					\
-	0x7b785574L,0x8c82,0x11cf,0xbc,0x0c,0x00,0xaa,0x00,0xac,0x74,0xf6
-DEFINE_GUIDSTRUCT("7b785574-8c82-11cf-bc0c-00aa00ac74f6",KSTIME_FORMAT_MEDIA_TIME);
-#define KSTIME_FORMAT_MEDIA_TIME DEFINE_GUIDNAMED(KSTIME_FORMAT_MEDIA_TIME)
-
-typedef KSIDENTIFIER KSPIN_INTERFACE,*PKSPIN_INTERFACE;
-
-#define STATIC_KSINTERFACESETID_Standard				\
-	0x1A8766A0L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("1A8766A0-62CE-11CF-A5D6-28DB04C10000",KSINTERFACESETID_Standard);
-#define KSINTERFACESETID_Standard DEFINE_GUIDNAMED(KSINTERFACESETID_Standard)
-
-typedef enum {
-  KSINTERFACE_STANDARD_STREAMING,
-  KSINTERFACE_STANDARD_LOOPED_STREAMING,
-  KSINTERFACE_STANDARD_CONTROL
-} KSINTERFACE_STANDARD;
-
-#define STATIC_KSINTERFACESETID_FileIo					\
-	0x8C6F932CL,0xE771,0x11D0,0xB8,0xFF,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("8C6F932C-E771-11D0-B8FF-00A0C9223196",KSINTERFACESETID_FileIo);
-#define KSINTERFACESETID_FileIo DEFINE_GUIDNAMED(KSINTERFACESETID_FileIo)
-
-typedef enum {
-  KSINTERFACE_FILEIO_STREAMING
-} KSINTERFACE_FILEIO;
-
-#define KSMEDIUM_TYPE_ANYINSTANCE		0
-
-#define STATIC_KSMEDIUMSETID_Standard					\
-	0x4747B320L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("4747B320-62CE-11CF-A5D6-28DB04C10000",KSMEDIUMSETID_Standard);
-#define KSMEDIUMSETID_Standard DEFINE_GUIDNAMED(KSMEDIUMSETID_Standard)
-
-#define KSMEDIUM_STANDARD_DEVIO KSMEDIUM_TYPE_ANYINSTANCE
-
-#define STATIC_KSPROPSETID_Pin						\
-	0x8C134960L,0x51AD,0x11CF,0x87,0x8A,0x94,0xF8,0x01,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("8C134960-51AD-11CF-878A-94F801C10000",KSPROPSETID_Pin);
-#define KSPROPSETID_Pin DEFINE_GUIDNAMED(KSPROPSETID_Pin)
-
-typedef enum {
-  KSPROPERTY_PIN_CINSTANCES,
-  KSPROPERTY_PIN_CTYPES,
-  KSPROPERTY_PIN_DATAFLOW,
-  KSPROPERTY_PIN_DATARANGES,
-  KSPROPERTY_PIN_DATAINTERSECTION,
-  KSPROPERTY_PIN_INTERFACES,
-  KSPROPERTY_PIN_MEDIUMS,
-  KSPROPERTY_PIN_COMMUNICATION,
-  KSPROPERTY_PIN_GLOBALCINSTANCES,
-  KSPROPERTY_PIN_NECESSARYINSTANCES,
-  KSPROPERTY_PIN_PHYSICALCONNECTION,
-  KSPROPERTY_PIN_CATEGORY,
-  KSPROPERTY_PIN_NAME,
-  KSPROPERTY_PIN_CONSTRAINEDDATARANGES,
-  KSPROPERTY_PIN_PROPOSEDATAFORMAT
-} KSPROPERTY_PIN;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG PinId;
-  ULONG Reserved;
-} KSP_PIN,*PKSP_PIN;
-
-#define KSINSTANCE_INDETERMINATE	((ULONG)-1)
-
-typedef struct {
-  ULONG PossibleCount;
-  ULONG CurrentCount;
-} KSPIN_CINSTANCES,*PKSPIN_CINSTANCES;
-
-typedef enum {
-  KSPIN_DATAFLOW_IN = 1,
-  KSPIN_DATAFLOW_OUT
-} KSPIN_DATAFLOW,*PKSPIN_DATAFLOW;
-
-#define KSDATAFORMAT_BIT_TEMPORAL_COMPRESSION	0
-#define KSDATAFORMAT_TEMPORAL_COMPRESSION	(1 << KSDATAFORMAT_BIT_TEMPORAL_COMPRESSION)
-#define KSDATAFORMAT_BIT_ATTRIBUTES		1
-#define KSDATAFORMAT_ATTRIBUTES			(1 << KSDATAFORMAT_BIT_ATTRIBUTES)
-
-#define KSDATARANGE_BIT_ATTRIBUTES		1
-#define KSDATARANGE_ATTRIBUTES			(1 << KSDATARANGE_BIT_ATTRIBUTES)
-#define KSDATARANGE_BIT_REQUIRED_ATTRIBUTES	2
-#define KSDATARANGE_REQUIRED_ATTRIBUTES		(1 << KSDATARANGE_BIT_REQUIRED_ATTRIBUTES)
-
-typedef union {
-  __MINGW_EXTENSION struct {
-    ULONG FormatSize;
-    ULONG Flags;
-    ULONG SampleSize;
-    ULONG Reserved;
-    GUID MajorFormat;
-    GUID SubFormat;
-    GUID Specifier;
-  };
-  LONGLONG Alignment;
-} KSDATAFORMAT,*PKSDATAFORMAT,KSDATARANGE,*PKSDATARANGE;
-
-#define KSATTRIBUTE_REQUIRED		0x00000001
-
-typedef struct {
-  ULONG Size;
-  ULONG Flags;
-  GUID Attribute;
-} KSATTRIBUTE,*PKSATTRIBUTE;
-
-#if defined(_NTDDK_)
-typedef struct {
-  ULONG Count;
-  PKSATTRIBUTE *Attributes;
-} KSATTRIBUTE_LIST,*PKSATTRIBUTE_LIST;
-#endif /* _NTDDK_ */
-
-typedef enum {
-  KSPIN_COMMUNICATION_NONE,
-  KSPIN_COMMUNICATION_SINK,
-  KSPIN_COMMUNICATION_SOURCE,
-  KSPIN_COMMUNICATION_BOTH,
-  KSPIN_COMMUNICATION_BRIDGE
-} KSPIN_COMMUNICATION,*PKSPIN_COMMUNICATION;
-
-typedef KSIDENTIFIER KSPIN_MEDIUM,*PKSPIN_MEDIUM;
-
-typedef struct {
-  KSPIN_INTERFACE Interface;
-  KSPIN_MEDIUM Medium;
-  ULONG PinId;
-  HANDLE PinToHandle;
-  KSPRIORITY Priority;
-} KSPIN_CONNECT,*PKSPIN_CONNECT;
-
-typedef struct {
-  ULONG Size;
-  ULONG Pin;
-  WCHAR SymbolicLinkName[1];
-} KSPIN_PHYSICALCONNECTION,*PKSPIN_PHYSICALCONNECTION;
-
-#if defined(_NTDDK_)
-typedef NTSTATUS (*PFNKSINTERSECTHANDLER) ( PIRP Irp, PKSP_PIN Pin,
-					    PKSDATARANGE DataRange,
-					    PVOID Data);
-typedef NTSTATUS (*PFNKSINTERSECTHANDLEREX)(PVOID Context, PIRP Irp,
-					    PKSP_PIN Pin,
-					    PKSDATARANGE DataRange,
-					    PKSDATARANGE MatchingDataRange,
-					    ULONG DataBufferSize,
-					    PVOID Data,
-					    PULONG DataSize);
-#endif /* _NTDDK_ */
-
-#define DEFINE_KSPIN_INTERFACE_TABLE(tablename)				\
-	const KSPIN_INTERFACE tablename[] =
-
-#define DEFINE_KSPIN_INTERFACE_ITEM(guid,_interFace)			\
-	{								\
-		STATICGUIDOF(guid),					\
-		(_interFace),						\
-		0							\
-	}
-
-#define DEFINE_KSPIN_MEDIUM_TABLE(tablename)				\
-	const KSPIN_MEDIUM tablename[] =
-
-#define DEFINE_KSPIN_MEDIUM_ITEM(guid,medium)				\
-		DEFINE_KSPIN_INTERFACE_ITEM(guid,medium)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_CINSTANCES(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_CINSTANCES,		\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				sizeof(KSPIN_CINSTANCES),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_CTYPES(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_CTYPES,			\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(ULONG),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_DATAFLOW(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_DATAFLOW,		\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				sizeof(KSPIN_DATAFLOW),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_DATARANGES(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_DATARANGES,		\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_DATAINTERSECTION(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_DATAINTERSECTION,	\
-				(Handler),				\
-				sizeof(KSP_PIN) + sizeof(KSMULTIPLE_ITEM),\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_INTERFACES(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_INTERFACES,		\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_MEDIUMS(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_MEDIUMS,			\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_COMMUNICATION(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_COMMUNICATION,		\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				sizeof(KSPIN_COMMUNICATION),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_GLOBALCINSTANCES(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_GLOBALCINSTANCES,	\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				sizeof(KSPIN_CINSTANCES),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_NECESSARYINSTANCES(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_NECESSARYINSTANCES,	\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				sizeof(ULONG),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_PHYSICALCONNECTION(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_PHYSICALCONNECTION,	\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_CATEGORY(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_CATEGORY,		\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				sizeof(GUID),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_NAME(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_NAME,			\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_CONSTRAINEDDATARANGES(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_CONSTRAINEDDATARANGES,	\
-				(Handler),				\
-				sizeof(KSP_PIN),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_PIN_PROPOSEDATAFORMAT(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_PIN_PROPOSEDATAFORMAT,	\
-				NULL,					\
-				sizeof(KSP_PIN),			\
-				sizeof(KSDATAFORMAT),			\
-				(Handler), NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_PINSET(PinSet,PropGeneral,PropInstances,PropIntersection) \
-DEFINE_KSPROPERTY_TABLE(PinSet) {					\
-	DEFINE_KSPROPERTY_ITEM_PIN_CINSTANCES(PropInstances),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_CTYPES(PropGeneral),			\
-	DEFINE_KSPROPERTY_ITEM_PIN_DATAFLOW(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_DATARANGES(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_DATAINTERSECTION(PropIntersection),	\
-	DEFINE_KSPROPERTY_ITEM_PIN_INTERFACES(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_MEDIUMS(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_COMMUNICATION(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_CATEGORY(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_NAME(PropGeneral)			\
-}
-
-#define DEFINE_KSPROPERTY_PINSETCONSTRAINED(PinSet,PropGeneral,PropInstances,PropIntersection) \
-DEFINE_KSPROPERTY_TABLE(PinSet) {					\
-	DEFINE_KSPROPERTY_ITEM_PIN_CINSTANCES(PropInstances),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_CTYPES(PropGeneral),			\
-	DEFINE_KSPROPERTY_ITEM_PIN_DATAFLOW(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_DATARANGES(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_DATAINTERSECTION(PropIntersection),	\
-	DEFINE_KSPROPERTY_ITEM_PIN_INTERFACES(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_MEDIUMS(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_COMMUNICATION(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_CATEGORY(PropGeneral),		\
-	DEFINE_KSPROPERTY_ITEM_PIN_NAME(PropGeneral),			\
-	DEFINE_KSPROPERTY_ITEM_PIN_CONSTRAINEDDATARANGES(PropGeneral)	\
-}
-
-#define STATIC_KSNAME_Filter						\
-	0x9b365890L,0x165f,0x11d0,0xa1,0x95,0x00,0x20,0xaf,0xd1,0x56,0xe4
-DEFINE_GUIDSTRUCT("9b365890-165f-11d0-a195-0020afd156e4",KSNAME_Filter);
-#define KSNAME_Filter DEFINE_GUIDNAMED(KSNAME_Filter)
-
-#define KSSTRING_Filter		L"{9B365890-165F-11D0-A195-0020AFD156E4}"
-
-#define STATIC_KSNAME_Pin						\
-	0x146F1A80L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("146F1A80-4791-11D0-A5D6-28DB04C10000",KSNAME_Pin);
-#define KSNAME_Pin DEFINE_GUIDNAMED(KSNAME_Pin)
-
-#define KSSTRING_Pin		L"{146F1A80-4791-11D0-A5D6-28DB04C10000}"
-
-#define STATIC_KSNAME_Clock						\
-	0x53172480L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("53172480-4791-11D0-A5D6-28DB04C10000",KSNAME_Clock);
-#define KSNAME_Clock DEFINE_GUIDNAMED(KSNAME_Clock)
-
-#define KSSTRING_Clock		L"{53172480-4791-11D0-A5D6-28DB04C10000}"
-
-#define STATIC_KSNAME_Allocator						\
-	0x642F5D00L,0x4791,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("642F5D00-4791-11D0-A5D6-28DB04C10000",KSNAME_Allocator);
-#define KSNAME_Allocator DEFINE_GUIDNAMED(KSNAME_Allocator)
-
-#define KSSTRING_Allocator	L"{642F5D00-4791-11D0-A5D6-28DB04C10000}"
-
-#define KSSTRING_AllocatorEx	L"{091BB63B-603F-11D1-B067-00A0C9062802}"
-
-#define STATIC_KSNAME_TopologyNode					\
-	0x0621061AL,0xEE75,0x11D0,0xB9,0x15,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("0621061A-EE75-11D0-B915-00A0C9223196",KSNAME_TopologyNode);
-#define KSNAME_TopologyNode DEFINE_GUIDNAMED(KSNAME_TopologyNode)
-
-#define KSSTRING_TopologyNode	L"{0621061A-EE75-11D0-B915-00A0C9223196}"
-
-#if defined(_NTDDK_)
-typedef struct {
-  ULONG InterfacesCount;
-  const KSPIN_INTERFACE *Interfaces;
-  ULONG MediumsCount;
-  const KSPIN_MEDIUM *Mediums;
-  ULONG DataRangesCount;
-  const PKSDATARANGE *DataRanges;
-  KSPIN_DATAFLOW DataFlow;
-  KSPIN_COMMUNICATION Communication;
-  const GUID *Category;
-  const GUID *Name;
-  __MINGW_EXTENSION union {
-    LONGLONG Reserved;
-    __MINGW_EXTENSION struct {
-      ULONG ConstrainedDataRangesCount;
-      PKSDATARANGE *ConstrainedDataRanges;
-    };
-  };
-} KSPIN_DESCRIPTOR, *PKSPIN_DESCRIPTOR;
-typedef const KSPIN_DESCRIPTOR *PCKSPIN_DESCRIPTOR;
-
-#define DEFINE_KSPIN_DESCRIPTOR_TABLE(tablename)			\
-	const KSPIN_DESCRIPTOR tablename[] =
-
-#define DEFINE_KSPIN_DESCRIPTOR_ITEM(InterfacesCount,Interfaces,MediumsCount, Mediums,DataRangesCount,DataRanges,DataFlow,Communication)\
-{									\
-		InterfacesCount, Interfaces, MediumsCount, Mediums,	\
-		DataRangesCount, DataRanges, DataFlow, Communication,	\
-		NULL, NULL, 0						\
-}
-
-#define DEFINE_KSPIN_DESCRIPTOR_ITEMEX(InterfacesCount,Interfaces,MediumsCount,Mediums,DataRangesCount,DataRanges,DataFlow,Communication,Category,Name)\
-{									\
-		InterfacesCount, Interfaces, MediumsCount, Mediums,	\
-		DataRangesCount, DataRanges, DataFlow, Communication,	\
-		Category, Name, 0					\
-}
-#endif /* _NTDDK_ */
-
-#define STATIC_KSDATAFORMAT_TYPE_WILDCARD	STATIC_GUID_NULL
-#define KSDATAFORMAT_TYPE_WILDCARD		GUID_NULL
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_WILDCARD	STATIC_GUID_NULL
-#define KSDATAFORMAT_SUBTYPE_WILDCARD		GUID_NULL
-
-#define STATIC_KSDATAFORMAT_TYPE_STREAM					\
-	0xE436EB83L,0x524F,0x11CE,0x9F,0x53,0x00,0x20,0xAF,0x0B,0xA7,0x70
-DEFINE_GUIDSTRUCT("E436EB83-524F-11CE-9F53-0020AF0BA770",KSDATAFORMAT_TYPE_STREAM);
-#define KSDATAFORMAT_TYPE_STREAM DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STREAM)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_NONE				\
-	0xE436EB8EL,0x524F,0x11CE,0x9F,0x53,0x00,0x20,0xAF,0x0B,0xA7,0x70
-DEFINE_GUIDSTRUCT("E436EB8E-524F-11CE-9F53-0020AF0BA770",KSDATAFORMAT_SUBTYPE_NONE);
-#define KSDATAFORMAT_SUBTYPE_NONE DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_NONE)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_WILDCARD	STATIC_GUID_NULL
-#define KSDATAFORMAT_SPECIFIER_WILDCARD		GUID_NULL
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_FILENAME				\
-	0xAA797B40L,0xE974,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("AA797B40-E974-11CF-A5D6-28DB04C10000",KSDATAFORMAT_SPECIFIER_FILENAME);
-#define KSDATAFORMAT_SPECIFIER_FILENAME DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_FILENAME)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_FILEHANDLE			\
-	0x65E8773CL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("65E8773C-8F56-11D0-A3B9-00A0C9223196",KSDATAFORMAT_SPECIFIER_FILEHANDLE);
-#define KSDATAFORMAT_SPECIFIER_FILEHANDLE DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_FILEHANDLE)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_NONE				\
-	0x0F6417D6L,0xC318,0x11D0,0xA4,0x3F,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("0F6417D6-C318-11D0-A43F-00A0C9223196",KSDATAFORMAT_SPECIFIER_NONE);
-#define KSDATAFORMAT_SPECIFIER_NONE DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_NONE)
-
-#define STATIC_KSPROPSETID_Quality					\
-	0xD16AD380L,0xAC1A,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("D16AD380-AC1A-11CF-A5D6-28DB04C10000",KSPROPSETID_Quality);
-#define KSPROPSETID_Quality DEFINE_GUIDNAMED(KSPROPSETID_Quality)
-
-typedef enum {
-  KSPROPERTY_QUALITY_REPORT,
-  KSPROPERTY_QUALITY_ERROR
-} KSPROPERTY_QUALITY;
-
-#define DEFINE_KSPROPERTY_ITEM_QUALITY_REPORT(GetHandler,SetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_QUALITY_REPORT,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSQUALITY),			\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_QUALITY_ERROR(GetHandler,SetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_QUALITY_ERROR,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSERROR),			\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define STATIC_KSPROPSETID_Connection					\
-	0x1D58C920L,0xAC9B,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("1D58C920-AC9B-11CF-A5D6-28DB04C10000",KSPROPSETID_Connection);
-#define KSPROPSETID_Connection DEFINE_GUIDNAMED(KSPROPSETID_Connection)
-
-typedef enum {
-  KSPROPERTY_CONNECTION_STATE,
-  KSPROPERTY_CONNECTION_PRIORITY,
-  KSPROPERTY_CONNECTION_DATAFORMAT,
-  KSPROPERTY_CONNECTION_ALLOCATORFRAMING,
-  KSPROPERTY_CONNECTION_PROPOSEDATAFORMAT,
-  KSPROPERTY_CONNECTION_ACQUIREORDERING,
-  KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,
-  KSPROPERTY_CONNECTION_STARTAT
-} KSPROPERTY_CONNECTION;
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_STATE(GetHandler,SetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_STATE,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSSTATE),			\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_PRIORITY(GetHandler,SetHandler) \
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_PRIORITY,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSPRIORITY),			\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_DATAFORMAT(GetHandler,SetHandler)\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_DATAFORMAT,	\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_ALLOCATORFRAMING(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_ALLOCATORFRAMING,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSALLOCATOR_FRAMING),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_ALLOCATORFRAMING_EX(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_PROPOSEDATAFORMAT(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_PROPOSEDATAFORMAT,\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSDATAFORMAT),			\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_ACQUIREORDERING(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_ACQUIREORDERING,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(int),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CONNECTION_STARTAT(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CONNECTION_STARTAT,		\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSRELATIVEEVENT),		\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define KSALLOCATOR_REQUIREMENTF_INPLACE_MODIFIER	0x00000001
-#define KSALLOCATOR_REQUIREMENTF_SYSTEM_MEMORY		0x00000002
-#define KSALLOCATOR_REQUIREMENTF_FRAME_INTEGRITY	0x00000004
-#define KSALLOCATOR_REQUIREMENTF_MUST_ALLOCATE		0x00000008
-#define KSALLOCATOR_REQUIREMENTF_PREFERENCES_ONLY	0x80000000
-
-#define KSALLOCATOR_OPTIONF_COMPATIBLE			0x00000001
-#define KSALLOCATOR_OPTIONF_SYSTEM_MEMORY		0x00000002
-#define KSALLOCATOR_OPTIONF_VALID			0x00000003
-
-#define KSALLOCATOR_FLAG_PARTIAL_READ_SUPPORT		0x00000010
-#define KSALLOCATOR_FLAG_DEVICE_SPECIFIC		0x00000020
-#define KSALLOCATOR_FLAG_CAN_ALLOCATE			0x00000040
-#define KSALLOCATOR_FLAG_INSIST_ON_FRAMESIZE_RATIO	0x00000080
-#define KSALLOCATOR_FLAG_NO_FRAME_INTEGRITY		0x00000100
-#define KSALLOCATOR_FLAG_MULTIPLE_OUTPUT		0x00000200
-#define KSALLOCATOR_FLAG_CYCLE				0x00000400
-#define KSALLOCATOR_FLAG_ALLOCATOR_EXISTS		0x00000800
-#define KSALLOCATOR_FLAG_INDEPENDENT_RANGES		0x00001000
-#define KSALLOCATOR_FLAG_ATTENTION_STEPPING		0x00002000
-
-typedef struct {
-  __MINGW_EXTENSION union {
-    ULONG OptionsFlags;
-    ULONG RequirementsFlags;
-  };
-#if defined(_NTDDK_)
-  POOL_TYPE PoolType;
-#else
-  ULONG PoolType;
-#endif /* _NTDDK_ */
-  ULONG Frames;
-  ULONG FrameSize;
-  ULONG FileAlignment;
-  ULONG Reserved;
-} KSALLOCATOR_FRAMING,*PKSALLOCATOR_FRAMING;
-
-#if defined(_NTDDK_)
-typedef PVOID (*PFNKSDEFAULTALLOCATE)(PVOID Context);
-typedef VOID (*PFNKSDEFAULTFREE)(PVOID Context, PVOID Buffer);
-typedef NTSTATUS (*PFNKSINITIALIZEALLOCATOR)(PVOID InitialContext,
-					PKSALLOCATOR_FRAMING AllocatorFraming,
-					PVOID* Context);
-typedef VOID (*PFNKSDELETEALLOCATOR) (PVOID Context);
-#endif /* _NTDDK_ */
-
-typedef struct {
-  ULONG MinFrameSize;
-  ULONG MaxFrameSize;
-  ULONG Stepping;
-} KS_FRAMING_RANGE,*PKS_FRAMING_RANGE;
-
-typedef struct {
-  KS_FRAMING_RANGE Range;
-  ULONG InPlaceWeight;
-  ULONG NotInPlaceWeight;
-} KS_FRAMING_RANGE_WEIGHTED,*PKS_FRAMING_RANGE_WEIGHTED;
-
-typedef struct {
-  ULONG RatioNumerator;
-  ULONG RatioDenominator;
-  ULONG RatioConstantMargin;
-} KS_COMPRESSION,*PKS_COMPRESSION;
-
-typedef struct {
-  GUID MemoryType;
-  GUID BusType;
-  ULONG MemoryFlags;
-  ULONG BusFlags;
-  ULONG Flags;
-  ULONG Frames;
-  ULONG FileAlignment;
-  ULONG MemoryTypeWeight;
-  KS_FRAMING_RANGE PhysicalRange;
-  KS_FRAMING_RANGE_WEIGHTED FramingRange;
-} KS_FRAMING_ITEM,*PKS_FRAMING_ITEM;
-
-typedef struct {
-  ULONG CountItems;
-  ULONG PinFlags;
-  KS_COMPRESSION OutputCompression;
-  ULONG PinWeight;
-  KS_FRAMING_ITEM FramingItem[1];
-} KSALLOCATOR_FRAMING_EX,*PKSALLOCATOR_FRAMING_EX;
-
-#define KSMEMORY_TYPE_WILDCARD		GUID_NULL
-#define STATIC_KSMEMORY_TYPE_WILDCARD	STATIC_GUID_NULL
-
-#define KSMEMORY_TYPE_DONT_CARE		GUID_NULL
-#define STATIC_KSMEMORY_TYPE_DONT_CARE	STATIC_GUID_NULL
-
-#define KS_TYPE_DONT_CARE		GUID_NULL
-#define STATIC_KS_TYPE_DONT_CARE	STATIC_GUID_NULL
-
-#define STATIC_KSMEMORY_TYPE_SYSTEM					\
-	0x091bb638L,0x603f,0x11d1,0xb0,0x67,0x00,0xa0,0xc9,0x06,0x28,0x02
-DEFINE_GUIDSTRUCT("091bb638-603f-11d1-b067-00a0c9062802",KSMEMORY_TYPE_SYSTEM);
-#define KSMEMORY_TYPE_SYSTEM DEFINE_GUIDNAMED(KSMEMORY_TYPE_SYSTEM)
-
-#define STATIC_KSMEMORY_TYPE_USER					\
-	0x8cb0fc28L,0x7893,0x11d1,0xb0,0x69,0x00,0xa0,0xc9,0x06,0x28,0x02
-DEFINE_GUIDSTRUCT("8cb0fc28-7893-11d1-b069-00a0c9062802",KSMEMORY_TYPE_USER);
-#define KSMEMORY_TYPE_USER DEFINE_GUIDNAMED(KSMEMORY_TYPE_USER)
-
-#define STATIC_KSMEMORY_TYPE_KERNEL_PAGED				\
-	0xd833f8f8L,0x7894,0x11d1,0xb0,0x69,0x00,0xa0,0xc9,0x06,0x28,0x02
-DEFINE_GUIDSTRUCT("d833f8f8-7894-11d1-b069-00a0c9062802",KSMEMORY_TYPE_KERNEL_PAGED);
-#define KSMEMORY_TYPE_KERNEL_PAGED DEFINE_GUIDNAMED(KSMEMORY_TYPE_KERNEL_PAGED)
-
-#define STATIC_KSMEMORY_TYPE_KERNEL_NONPAGED				\
-	0x4a6d5fc4L,0x7895,0x11d1,0xb0,0x69,0x00,0xa0,0xc9,0x06,0x28,0x02
-DEFINE_GUIDSTRUCT("4a6d5fc4-7895-11d1-b069-00a0c9062802",KSMEMORY_TYPE_KERNEL_NONPAGED);
-#define KSMEMORY_TYPE_KERNEL_NONPAGED DEFINE_GUIDNAMED(KSMEMORY_TYPE_KERNEL_NONPAGED)
-
-#define STATIC_KSMEMORY_TYPE_DEVICE_UNKNOWN				\
-	0x091bb639L,0x603f,0x11d1,0xb0,0x67,0x00,0xa0,0xc9,0x06,0x28,0x02
-DEFINE_GUIDSTRUCT("091bb639-603f-11d1-b067-00a0c9062802",KSMEMORY_TYPE_DEVICE_UNKNOWN);
-#define KSMEMORY_TYPE_DEVICE_UNKNOWN DEFINE_GUIDNAMED(KSMEMORY_TYPE_DEVICE_UNKNOWN)
-
-#define DECLARE_SIMPLE_FRAMING_EX(FramingExName,MemoryType,Flags,Frames,Alignment,MinFrameSize,MaxFrameSize) \
-const KSALLOCATOR_FRAMING_EX FramingExName =				\
-{									\
-	1,								\
-	0,								\
-	{								\
-		1,							\
-		1,							\
-		0							\
-	},								\
-	0,								\
-	{								\
-		{							\
-			MemoryType,					\
-			STATIC_KS_TYPE_DONT_CARE,			\
-			0,						\
-			0,						\
-			Flags,						\
-			Frames,						\
-			Alignment,					\
-			0,						\
-			{						\
-				0,					\
-				(ULONG)-1,				\
-				1					\
-			},						\
-			{						\
-				{					\
-					MinFrameSize,			\
-					MaxFrameSize,			\
-					1				\
-				},					\
-				0,					\
-				0					\
-			}						\
-		}							\
-	}								\
-}
-
-#define SetDefaultKsCompression(KsCompressionPointer)			\
-{									\
-	KsCompressionPointer->RatioNumerator = 1;			\
-	KsCompressionPointer->RatioDenominator = 1;			\
-	KsCompressionPointer->RatioConstantMargin = 0;			\
-}
-
-#define SetDontCareKsFramingRange(KsFramingRangePointer)		\
-{									\
-	KsFramingRangePointer->MinFrameSize = 0;			\
-	KsFramingRangePointer->MaxFrameSize = (ULONG) -1;		\
-	KsFramingRangePointer->Stepping = 1;				\
-}
-
-#define SetKsFramingRange(KsFramingRangePointer,P_MinFrameSize,P_MaxFrameSize) \
-{									\
-	KsFramingRangePointer->MinFrameSize = P_MinFrameSize;		\
-	KsFramingRangePointer->MaxFrameSize = P_MaxFrameSize;		\
-	KsFramingRangePointer->Stepping = 1;				\
-}
-
-#define SetKsFramingRangeWeighted(KsFramingRangeWeightedPointer,P_MinFrameSize,P_MaxFrameSize) \
-{									\
-	KS_FRAMING_RANGE *KsFramingRange =				\
-				&KsFramingRangeWeightedPointer->Range;	\
-	SetKsFramingRange(KsFramingRange,P_MinFrameSize,P_MaxFrameSize);\
-	KsFramingRangeWeightedPointer->InPlaceWeight = 0;		\
-	KsFramingRangeWeightedPointer->NotInPlaceWeight = 0;		\
-}
-
-#define INITIALIZE_SIMPLE_FRAMING_EX(FramingExPointer,P_MemoryType,P_Flags,P_Frames,P_Alignment,P_MinFrameSize,P_MaxFrameSize) \
-{									\
-	KS_COMPRESSION *KsCompression =					\
-			&FramingExPointer->OutputCompression;		\
-	KS_FRAMING_RANGE *KsFramingRange =				\
-			&FramingExPointer->FramingItem[0].PhysicalRange;\
-	KS_FRAMING_RANGE_WEIGHTED *KsFramingRangeWeighted =		\
-			&FramingExPointer->FramingItem[0].FramingRange;	\
-	FramingExPointer->CountItems = 1;				\
-	FramingExPointer->PinFlags = 0;					\
-	SetDefaultKsCompression(KsCompression);				\
-	FramingExPointer->PinWeight = 0;				\
-	FramingExPointer->FramingItem[0].MemoryType = P_MemoryType;	\
-	FramingExPointer->FramingItem[0].BusType = KS_TYPE_DONT_CARE;	\
-	FramingExPointer->FramingItem[0].MemoryFlags = 0;		\
-	FramingExPointer->FramingItem[0].BusFlags = 0;			\
-	FramingExPointer->FramingItem[0].Flags = P_Flags;		\
-	FramingExPointer->FramingItem[0].Frames = P_Frames;		\
-	FramingExPointer->FramingItem[0].FileAlignment = P_Alignment;	\
-	FramingExPointer->FramingItem[0].MemoryTypeWeight = 0;		\
-	SetDontCareKsFramingRange(KsFramingRange);			\
-	SetKsFramingRangeWeighted(KsFramingRangeWeighted,		\
-				  P_MinFrameSize,P_MaxFrameSize);	\
-}
-
-#define STATIC_KSEVENTSETID_StreamAllocator				\
-	0x75d95571L,0x073c,0x11d0,0xa1,0x61,0x00,0x20,0xaf,0xd1,0x56,0xe4
-DEFINE_GUIDSTRUCT("75d95571-073c-11d0-a161-0020afd156e4",KSEVENTSETID_StreamAllocator);
-#define KSEVENTSETID_StreamAllocator DEFINE_GUIDNAMED(KSEVENTSETID_StreamAllocator)
-
-typedef enum {
-  KSEVENT_STREAMALLOCATOR_INTERNAL_FREEFRAME,
-  KSEVENT_STREAMALLOCATOR_FREEFRAME
-} KSEVENT_STREAMALLOCATOR;
-
-#define STATIC_KSMETHODSETID_StreamAllocator				\
-	0xcf6e4341L,0xec87,0x11cf,0xa1,0x30,0x00,0x20,0xaf,0xd1,0x56,0xe4
-DEFINE_GUIDSTRUCT("cf6e4341-ec87-11cf-a130-0020afd156e4",KSMETHODSETID_StreamAllocator);
-#define KSMETHODSETID_StreamAllocator DEFINE_GUIDNAMED(KSMETHODSETID_StreamAllocator)
-
-typedef enum {
-  KSMETHOD_STREAMALLOCATOR_ALLOC,
-  KSMETHOD_STREAMALLOCATOR_FREE
-} KSMETHOD_STREAMALLOCATOR;
-
-#define DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_ALLOC(Handler)		\
-	DEFINE_KSMETHOD_ITEM(						\
-				KSMETHOD_STREAMALLOCATOR_ALLOC,		\
-				KSMETHOD_TYPE_WRITE,			\
-				(Handler),				\
-				sizeof(KSMETHOD),			\
-				sizeof(PVOID),				\
-				NULL)
-
-#define DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_FREE(Handler)		\
-	DEFINE_KSMETHOD_ITEM(						\
-				KSMETHOD_STREAMALLOCATOR_FREE,		\
-				KSMETHOD_TYPE_READ,			\
-				(Handler),				\
-				sizeof(KSMETHOD),			\
-				sizeof(PVOID),				\
-				NULL)
-
-#define DEFINE_KSMETHOD_ALLOCATORSET(AllocatorSet,MethodAlloc,MethodFree)\
-DEFINE_KSMETHOD_TABLE(AllocatorSet) {					\
-	DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_ALLOC(MethodAlloc),	\
-	DEFINE_KSMETHOD_ITEM_STREAMALLOCATOR_FREE(MethodFree)		\
-}
-
-#define STATIC_KSPROPSETID_StreamAllocator				\
-	0xcf6e4342L,0xec87,0x11cf,0xa1,0x30,0x00,0x20,0xaf,0xd1,0x56,0xe4
-DEFINE_GUIDSTRUCT("cf6e4342-ec87-11cf-a130-0020afd156e4",KSPROPSETID_StreamAllocator);
-#define KSPROPSETID_StreamAllocator DEFINE_GUIDNAMED(KSPROPSETID_StreamAllocator)
-
-#if defined(_NTDDK_)
-typedef enum {
-  KSPROPERTY_STREAMALLOCATOR_FUNCTIONTABLE,
-  KSPROPERTY_STREAMALLOCATOR_STATUS
-} KSPROPERTY_STREAMALLOCATOR;
-
-#define DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_FUNCTIONTABLE(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAMALLOCATOR_FUNCTIONTABLE,\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSSTREAMALLOCATOR_FUNCTIONTABLE),\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_STATUS(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAMALLOCATOR_STATUS,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSSTREAMALLOCATOR_STATUS),	\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ALLOCATORSET(AllocatorSet,PropFunctionTable,PropStatus)\
-DEFINE_KSPROPERTY_TABLE(AllocatorSet) {					\
-	DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_STATUS(PropStatus),	\
-	DEFINE_KSPROPERTY_ITEM_STREAMALLOCATOR_FUNCTIONTABLE(PropFunctionTable)\
-}
-
-typedef NTSTATUS (*PFNALLOCATOR_ALLOCATEFRAME) (PFILE_OBJECT FileObject,
-						PVOID *Frame);
-typedef VOID (*PFNALLOCATOR_FREEFRAME) (PFILE_OBJECT FileObject, PVOID Frame);
-
-typedef struct {
-  PFNALLOCATOR_ALLOCATEFRAME AllocateFrame;
-  PFNALLOCATOR_FREEFRAME FreeFrame;
-} KSSTREAMALLOCATOR_FUNCTIONTABLE, *PKSSTREAMALLOCATOR_FUNCTIONTABLE;
-#endif /* _NTDDK_ */
-
-typedef struct {
-  KSALLOCATOR_FRAMING Framing;
-  ULONG AllocatedFrames;
-  ULONG Reserved;
-} KSSTREAMALLOCATOR_STATUS,*PKSSTREAMALLOCATOR_STATUS;
-
-typedef struct {
-  KSALLOCATOR_FRAMING_EX Framing;
-  ULONG AllocatedFrames;
-  ULONG Reserved;
-} KSSTREAMALLOCATOR_STATUS_EX,*PKSSTREAMALLOCATOR_STATUS_EX;
-
-#define KSSTREAM_HEADER_OPTIONSF_SPLICEPOINT		0x00000001
-#define KSSTREAM_HEADER_OPTIONSF_PREROLL		0x00000002
-#define KSSTREAM_HEADER_OPTIONSF_DATADISCONTINUITY	0x00000004
-#define KSSTREAM_HEADER_OPTIONSF_TYPECHANGED		0x00000008
-#define KSSTREAM_HEADER_OPTIONSF_TIMEVALID		0x00000010
-#define KSSTREAM_HEADER_OPTIONSF_TIMEDISCONTINUITY	0x00000040
-#define KSSTREAM_HEADER_OPTIONSF_FLUSHONPAUSE		0x00000080
-#define KSSTREAM_HEADER_OPTIONSF_DURATIONVALID		0x00000100
-#define KSSTREAM_HEADER_OPTIONSF_ENDOFSTREAM		0x00000200
-#define KSSTREAM_HEADER_OPTIONSF_LOOPEDDATA		0x80000000
-
-typedef struct {
-  LONGLONG Time;
-  ULONG Numerator;
-  ULONG Denominator;
-} KSTIME,*PKSTIME;
-
-typedef struct {
-  ULONG Size;
-  ULONG TypeSpecificFlags;
-  KSTIME PresentationTime;
-  LONGLONG Duration;
-  ULONG FrameExtent;
-  ULONG DataUsed;
-  PVOID Data;
-  ULONG OptionsFlags;
-#ifdef _WIN64
-  ULONG Reserved;
-#endif
-} KSSTREAM_HEADER,*PKSSTREAM_HEADER;
-
-#define STATIC_KSPROPSETID_StreamInterface				\
-	0x1fdd8ee1L,0x9cd3,0x11d0,0x82,0xaa,0x00,0x00,0xf8,0x22,0xfe,0x8a
-DEFINE_GUIDSTRUCT("1fdd8ee1-9cd3-11d0-82aa-0000f822fe8a",KSPROPSETID_StreamInterface);
-#define KSPROPSETID_StreamInterface DEFINE_GUIDNAMED(KSPROPSETID_StreamInterface)
-
-typedef enum {
-  KSPROPERTY_STREAMINTERFACE_HEADERSIZE
-} KSPROPERTY_STREAMINTERFACE;
-
-#define DEFINE_KSPROPERTY_ITEM_STREAMINTERFACE_HEADERSIZE(GetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAMINTERFACE_HEADERSIZE,	\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(ULONG),				\
-				NULL,NULL,0,NULL,NULL,0)
-
-#define DEFINE_KSPROPERTY_STREAMINTERFACESET(StreamInterfaceSet,HeaderSizeHandler) \
-DEFINE_KSPROPERTY_TABLE(StreamInterfaceSet) {				\
-	DEFINE_KSPROPERTY_ITEM_STREAMINTERFACE_HEADERSIZE(HeaderSizeHandler)\
-}
-
-#define STATIC_KSPROPSETID_Stream					\
-	0x65aaba60L,0x98ae,0x11cf,0xa1,0x0d,0x00,0x20,0xaf,0xd1,0x56,0xe4
-DEFINE_GUIDSTRUCT("65aaba60-98ae-11cf-a10d-0020afd156e4",KSPROPSETID_Stream);
-#define KSPROPSETID_Stream DEFINE_GUIDNAMED(KSPROPSETID_Stream)
-
-typedef enum {
-  KSPROPERTY_STREAM_ALLOCATOR,
-  KSPROPERTY_STREAM_QUALITY,
-  KSPROPERTY_STREAM_DEGRADATION,
-  KSPROPERTY_STREAM_MASTERCLOCK,
-  KSPROPERTY_STREAM_TIMEFORMAT,
-  KSPROPERTY_STREAM_PRESENTATIONTIME,
-  KSPROPERTY_STREAM_PRESENTATIONEXTENT,
-  KSPROPERTY_STREAM_FRAMETIME,
-  KSPROPERTY_STREAM_RATECAPABILITY,
-  KSPROPERTY_STREAM_RATE,
-  KSPROPERTY_STREAM_PIPE_ID
-} KSPROPERTY_STREAM;
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_ALLOCATOR(GetHandler,SetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_ALLOCATOR,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(HANDLE),				\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_QUALITY(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_QUALITY,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSQUALITY_MANAGER),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_DEGRADATION(GetHandler,SetHandler)\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_DEGRADATION,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_MASTERCLOCK(GetHandler,SetHandler)\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_MASTERCLOCK,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(HANDLE),				\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_TIMEFORMAT(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_TIMEFORMAT,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(GUID),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_PRESENTATIONTIME(GetHandler,SetHandler)\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_PRESENTATIONTIME,	\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSTIME),				\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_PRESENTATIONEXTENT(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_PRESENTATIONEXTENT,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(LONGLONG),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_FRAMETIME(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_FRAMETIME,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSFRAMETIME),			\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_RATECAPABILITY(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_RATECAPABILITY,	\
-				(Handler),				\
-				sizeof(KSRATE_CAPABILITY),		\
-				sizeof(KSRATE),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_RATE(GetHandler,SetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_RATE,			\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSRATE),				\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_STREAM_PIPE_ID(GetHandler,SetHandler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_STREAM_PIPE_ID,		\
-				(GetHandler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(HANDLE),				\
-				(SetHandler),				\
-				NULL, 0, NULL, NULL, 0)
-
-typedef struct {
-  HANDLE QualityManager;
-  PVOID Context;
-} KSQUALITY_MANAGER,*PKSQUALITY_MANAGER;
-
-typedef struct {
-  LONGLONG Duration;
-  ULONG FrameFlags;
-  ULONG Reserved;
-} KSFRAMETIME,*PKSFRAMETIME;
-
-#define KSFRAMETIME_VARIABLESIZE	0x00000001
-
-typedef struct {
-  LONGLONG PresentationStart;
-  LONGLONG Duration;
-  KSPIN_INTERFACE Interface;
-  LONG Rate;
-  ULONG Flags;
-} KSRATE,*PKSRATE;
-
-#define KSRATE_NOPRESENTATIONSTART	0x00000001
-#define KSRATE_NOPRESENTATIONDURATION	0x00000002
-
-typedef struct {
-  KSPROPERTY Property;
-  KSRATE Rate;
-} KSRATE_CAPABILITY,*PKSRATE_CAPABILITY;
-
-#define STATIC_KSPROPSETID_Clock					\
-	0xDF12A4C0L,0xAC17,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("DF12A4C0-AC17-11CF-A5D6-28DB04C10000",KSPROPSETID_Clock);
-#define KSPROPSETID_Clock DEFINE_GUIDNAMED(KSPROPSETID_Clock)
-
-#define NANOSECONDS 10000000
-#define KSCONVERT_PERFORMANCE_TIME(Frequency,PerformanceTime)		\
-	((((ULONGLONG)(ULONG)(PerformanceTime).HighPart *NANOSECONDS / (Frequency)) << 32) +	\
-	 ((((((ULONGLONG)(ULONG)(PerformanceTime).HighPart *NANOSECONDS) % (Frequency)) << 32) +\
-	 ((ULONGLONG)(PerformanceTime).LowPart *NANOSECONDS)) / (Frequency)))
-
-typedef struct {
-  ULONG CreateFlags;
-} KSCLOCK_CREATE,*PKSCLOCK_CREATE;
-
-typedef struct {
-  LONGLONG Time;
-  LONGLONG SystemTime;
-} KSCORRELATED_TIME,*PKSCORRELATED_TIME;
-
-typedef struct {
-  LONGLONG Granularity;
-  LONGLONG Error;
-} KSRESOLUTION,*PKSRESOLUTION;
-
-typedef enum {
-  KSPROPERTY_CLOCK_TIME,
-  KSPROPERTY_CLOCK_PHYSICALTIME,
-  KSPROPERTY_CLOCK_CORRELATEDTIME,
-  KSPROPERTY_CLOCK_CORRELATEDPHYSICALTIME,
-  KSPROPERTY_CLOCK_RESOLUTION,
-  KSPROPERTY_CLOCK_STATE,
-#if defined(_NTDDK_)
-  KSPROPERTY_CLOCK_FUNCTIONTABLE
-#endif /* _NTDDK_ */
-} KSPROPERTY_CLOCK;
-
-#if defined(_NTDDK_)
-typedef LONGLONG (FASTCALL *PFNKSCLOCK_GETTIME)(PFILE_OBJECT FileObject);
-typedef LONGLONG (FASTCALL *PFNKSCLOCK_CORRELATEDTIME)(PFILE_OBJECT FileObject,
-							PLONGLONG SystemTime);
-
-typedef struct {
-   PFNKSCLOCK_GETTIME GetTime;
-   PFNKSCLOCK_GETTIME GetPhysicalTime;
-   PFNKSCLOCK_CORRELATEDTIME GetCorrelatedTime;
-   PFNKSCLOCK_CORRELATEDTIME GetCorrelatedPhysicalTime;
-} KSCLOCK_FUNCTIONTABLE, *PKSCLOCK_FUNCTIONTABLE;
-
-typedef BOOLEAN (*PFNKSSETTIMER)(PVOID Context, PKTIMER Timer,
-				 LARGE_INTEGER DueTime, PKDPC Dpc);
-typedef BOOLEAN (*PFNKSCANCELTIMER) (PVOID Context, PKTIMER Timer);
-typedef LONGLONG (FASTCALL *PFNKSCORRELATEDTIME)(PVOID Context,
-						 PLONGLONG SystemTime);
-
-typedef PVOID			PKSDEFAULTCLOCK;
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_TIME(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_TIME,			\
-				(Handler),				\
-				sizeof(KSPROPERTY), sizeof(LONGLONG),	\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_PHYSICALTIME(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_PHYSICALTIME,		\
-				(Handler),				\
-				sizeof(KSPROPERTY), sizeof(LONGLONG),	\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDTIME(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_CORRELATEDTIME,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSCORRELATED_TIME),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDPHYSICALTIME(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_CORRELATEDPHYSICALTIME,\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSCORRELATED_TIME),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_RESOLUTION(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_RESOLUTION,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),sizeof(KSRESOLUTION),\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_STATE(Handler)			\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_STATE,			\
-				(Handler),				\
-				sizeof(KSPROPERTY), sizeof(KSSTATE),	\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_CLOCK_FUNCTIONTABLE(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_CLOCK_FUNCTIONTABLE,		\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSCLOCK_FUNCTIONTABLE),		\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_CLOCKSET(ClockSet,PropTime,PropPhysicalTime,PropCorrelatedTime,PropCorrelatedPhysicalTime,PropResolution,PropState,PropFunctionTable)\
-DEFINE_KSPROPERTY_TABLE(ClockSet) {					\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_TIME(PropTime),			\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_PHYSICALTIME(PropPhysicalTime),	\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDTIME(PropCorrelatedTime),\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_CORRELATEDPHYSICALTIME(PropCorrelatedPhysicalTime),\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_RESOLUTION(PropResolution),	\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_STATE(PropState),			\
-	DEFINE_KSPROPERTY_ITEM_CLOCK_FUNCTIONTABLE(PropFunctionTable),	\
-}
-#endif /* _NTDDK_ */
-
-#define STATIC_KSEVENTSETID_Clock					\
-	0x364D8E20L,0x62C7,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("364D8E20-62C7-11CF-A5D6-28DB04C10000",KSEVENTSETID_Clock);
-#define KSEVENTSETID_Clock DEFINE_GUIDNAMED(KSEVENTSETID_Clock)
-
-typedef enum {
-  KSEVENT_CLOCK_INTERVAL_MARK,
-  KSEVENT_CLOCK_POSITION_MARK
-} KSEVENT_CLOCK_POSITION;
-
-#define STATIC_KSEVENTSETID_Connection					\
-	0x7f4bcbe0L,0x9ea5,0x11cf,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00
-DEFINE_GUIDSTRUCT("7f4bcbe0-9ea5-11cf-a5d6-28db04c10000",KSEVENTSETID_Connection);
-#define KSEVENTSETID_Connection DEFINE_GUIDNAMED(KSEVENTSETID_Connection)
-
-typedef enum {
-  KSEVENT_CONNECTION_POSITIONUPDATE,
-  KSEVENT_CONNECTION_DATADISCONTINUITY,
-  KSEVENT_CONNECTION_TIMEDISCONTINUITY,
-  KSEVENT_CONNECTION_PRIORITY,
-  KSEVENT_CONNECTION_ENDOFSTREAM
-} KSEVENT_CONNECTION;
-
-typedef struct {
-  PVOID Context;
-  ULONG Proportion;
-  LONGLONG DeltaTime;
-} KSQUALITY,*PKSQUALITY;
-
-typedef struct {
-  PVOID Context;
-  ULONG Status;
-} KSERROR,*PKSERROR;
-
-typedef KSIDENTIFIER KSDEGRADE,*PKSDEGRADE;
-
-#define STATIC_KSDEGRADESETID_Standard					\
-	0x9F564180L,0x704C,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("9F564180-704C-11D0-A5D6-28DB04C10000",KSDEGRADESETID_Standard);
-#define KSDEGRADESETID_Standard DEFINE_GUIDNAMED(KSDEGRADESETID_Standard)
-
-typedef enum {
-  KSDEGRADE_STANDARD_SAMPLE,
-  KSDEGRADE_STANDARD_QUALITY,
-  KSDEGRADE_STANDARD_COMPUTATION,
-  KSDEGRADE_STANDARD_SKIP
-} KSDEGRADE_STANDARD;
-
-#if defined(_NTDDK_)
-
-#define KSPROBE_STREAMREAD		0x00000000
-#define KSPROBE_STREAMWRITE		0x00000001
-#define KSPROBE_ALLOCATEMDL		0x00000010
-#define KSPROBE_PROBEANDLOCK		0x00000020
-#define KSPROBE_SYSTEMADDRESS		0x00000040
-#define KSPROBE_MODIFY			0x00000200
-#define KSPROBE_STREAMWRITEMODIFY	(KSPROBE_MODIFY | KSPROBE_STREAMWRITE)
-#define KSPROBE_ALLOWFORMATCHANGE	0x00000080
-#define KSSTREAM_READ			KSPROBE_STREAMREAD
-#define KSSTREAM_WRITE			KSPROBE_STREAMWRITE
-#define KSSTREAM_PAGED_DATA		0x00000000
-#define KSSTREAM_NONPAGED_DATA		0x00000100
-#define KSSTREAM_SYNCHRONOUS		0x00001000
-#define KSSTREAM_FAILUREEXCEPTION	0x00002000
-
-typedef NTSTATUS (*PFNKSCONTEXT_DISPATCH)(PVOID Context, PIRP Irp);
-typedef NTSTATUS (*PFNKSHANDLER)(PIRP Irp, PKSIDENTIFIER Request, PVOID Data);
-typedef BOOLEAN (*PFNKSFASTHANDLER)(PFILE_OBJECT FileObject,
-				    PKSIDENTIFIER Request,
-				    ULONG RequestLength, PVOID Data,
-				    ULONG DataLength,
-				    PIO_STATUS_BLOCK IoStatus);
-typedef NTSTATUS (*PFNKSALLOCATOR) (PIRP Irp, ULONG BufferSize,
-				    BOOLEAN InputOperation);
-
-typedef struct {
-  KSPROPERTY_MEMBERSHEADER MembersHeader;
-  const VOID *Members;
-} KSPROPERTY_MEMBERSLIST, *PKSPROPERTY_MEMBERSLIST;
-
-typedef struct {
-  KSIDENTIFIER PropTypeSet;
-  ULONG MembersListCount;
-  const KSPROPERTY_MEMBERSLIST *MembersList;
-} KSPROPERTY_VALUES, *PKSPROPERTY_VALUES;
-
-#define DEFINE_KSPROPERTY_TABLE(tablename)				\
-	const KSPROPERTY_ITEM tablename[] =
-
-#define DEFINE_KSPROPERTY_ITEM(PropertyId,GetHandler,MinProperty,MinData,SetHandler,Values,RelationsCount,Relations,SupportHandler,SerializedSize)\
-{									\
-			PropertyId, (PFNKSHANDLER)GetHandler,		\
-			MinProperty, MinData,				\
-			(PFNKSHANDLER)SetHandler,			\
-			(PKSPROPERTY_VALUES)Values, RelationsCount,	\
-			(PKSPROPERTY)Relations,				\
-			(PFNKSHANDLER)SupportHandler,			\
-			(ULONG)SerializedSize				\
-}
-
-typedef struct {
-  ULONG PropertyId;
-  __MINGW_EXTENSION union {
-    PFNKSHANDLER GetPropertyHandler;
-    BOOLEAN GetSupported;
-  };
-  ULONG MinProperty;
-  ULONG MinData;
-  __MINGW_EXTENSION union {
-    PFNKSHANDLER SetPropertyHandler;
-    BOOLEAN SetSupported;
-  };
-  const KSPROPERTY_VALUES *Values;
-  ULONG RelationsCount;
-  const KSPROPERTY *Relations;
-  PFNKSHANDLER SupportHandler;
-  ULONG SerializedSize;
-} KSPROPERTY_ITEM, *PKSPROPERTY_ITEM;
-
-#define DEFINE_KSFASTPROPERTY_ITEM(PropertyId, GetHandler, SetHandler)	\
-{									\
-			PropertyId, (PFNKSFASTHANDLER)GetHandler,	\
-			(PFNKSFASTHANDLER)SetHandler, 0			\
-}
-
-typedef struct {
-  ULONG PropertyId;
-  __MINGW_EXTENSION union {
-    PFNKSFASTHANDLER GetPropertyHandler;
-    BOOLEAN GetSupported;
-  };
-  __MINGW_EXTENSION union {
-    PFNKSFASTHANDLER SetPropertyHandler;
-    BOOLEAN SetSupported;
-  };
-  ULONG Reserved;
-} KSFASTPROPERTY_ITEM, *PKSFASTPROPERTY_ITEM;
-
-#define DEFINE_KSPROPERTY_SET(Set,PropertiesCount,PropertyItem,FastIoCount,FastIoTable)\
-{									\
-			Set,						\
-			PropertiesCount, PropertyItem,			\
-			FastIoCount, FastIoTable			\
-}
-
-#define DEFINE_KSPROPERTY_SET_TABLE(tablename)				\
-	const KSPROPERTY_SET tablename[] =
-
-typedef struct {
-  const GUID *Set;
-  ULONG PropertiesCount;
-  const KSPROPERTY_ITEM *PropertyItem;
-  ULONG FastIoCount;
-  const KSFASTPROPERTY_ITEM *FastIoTable;
-} KSPROPERTY_SET, *PKSPROPERTY_SET;
-
-#define DEFINE_KSMETHOD_TABLE(tablename)				\
-	const KSMETHOD_ITEM tablename[] =
-
-#define DEFINE_KSMETHOD_ITEM(MethodId,Flags,MethodHandler,MinMethod,MinData,SupportHandler)\
-{									\
-			MethodId, (PFNKSHANDLER)MethodHandler,		\
-			MinMethod, MinData,				\
-			SupportHandler, Flags				\
-}
-
-typedef struct {
-  ULONG MethodId;
-  __MINGW_EXTENSION union {
-    PFNKSHANDLER MethodHandler;
-    BOOLEAN MethodSupported;
-  };
-  ULONG MinMethod;
-  ULONG MinData;
-  PFNKSHANDLER SupportHandler;
-  ULONG Flags;
-} KSMETHOD_ITEM, *PKSMETHOD_ITEM;
-
-#define DEFINE_KSFASTMETHOD_ITEM(MethodId,MethodHandler)		\
-{									\
-			MethodId, (PFNKSFASTHANDLER)MethodHandler	\
-}
-
-typedef struct {
-  ULONG MethodId;
-  __MINGW_EXTENSION union {
-    PFNKSFASTHANDLER MethodHandler;
-    BOOLEAN MethodSupported;
-  };
-} KSFASTMETHOD_ITEM, *PKSFASTMETHOD_ITEM;
-
-#define DEFINE_KSMETHOD_SET(Set,MethodsCount,MethodItem,FastIoCount,FastIoTable)\
-{									\
-			Set,						\
-			MethodsCount, MethodItem,			\
-			FastIoCount, FastIoTable			\
-}
-
-#define DEFINE_KSMETHOD_SET_TABLE(tablename)				\
-	const KSMETHOD_SET tablename[] =
-
-typedef struct {
-  const GUID *Set;
-  ULONG MethodsCount;
-  const KSMETHOD_ITEM *MethodItem;
-  ULONG FastIoCount;
-  const KSFASTMETHOD_ITEM *FastIoTable;
-} KSMETHOD_SET, *PKSMETHOD_SET;
-
-typedef struct _KSEVENT_ENTRY	KSEVENT_ENTRY, *PKSEVENT_ENTRY;
-typedef NTSTATUS (*PFNKSADDEVENT)(PIRP Irp, PKSEVENTDATA EventData,
-				  struct _KSEVENT_ENTRY* EventEntry);
-typedef VOID (*PFNKSREMOVEEVENT)(PFILE_OBJECT FileObject,
-				 struct _KSEVENT_ENTRY* EventEntry);
-
-#define DEFINE_KSEVENT_TABLE(tablename)					\
-	const KSEVENT_ITEM tablename[] =
-
-#define DEFINE_KSEVENT_ITEM(EventId,DataInput,ExtraEntryData,AddHandler,RemoveHandler,SupportHandler)\
-{									\
-			EventId, DataInput, ExtraEntryData,		\
-			AddHandler, RemoveHandler, SupportHandler	\
-}
-
-typedef struct {
-  ULONG EventId;
-  ULONG DataInput;
-  ULONG ExtraEntryData;
-  PFNKSADDEVENT AddHandler;
-  PFNKSREMOVEEVENT RemoveHandler;
-  PFNKSHANDLER SupportHandler;
-} KSEVENT_ITEM, *PKSEVENT_ITEM;
-
-#define DEFINE_KSEVENT_SET(Set,EventsCount,EventItem)			\
-{									\
-			Set, EventsCount, EventItem			\
-}
-
-#define DEFINE_KSEVENT_SET_TABLE(tablename)				\
-	const KSEVENT_SET tablename[] =
-
-typedef struct {
-  const GUID *Set;
-  ULONG EventsCount;
-  const KSEVENT_ITEM *EventItem;
-} KSEVENT_SET, *PKSEVENT_SET;
-
-typedef struct {
-  KDPC Dpc;
-  ULONG ReferenceCount;
-  KSPIN_LOCK AccessLock;
-} KSDPC_ITEM, *PKSDPC_ITEM;
-
-typedef struct {
-  KSDPC_ITEM DpcItem;
-  LIST_ENTRY BufferList;
-} KSBUFFER_ITEM, *PKSBUFFER_ITEM;
-
-
-#define KSEVENT_ENTRY_DELETED		1
-#define KSEVENT_ENTRY_ONESHOT		2
-#define KSEVENT_ENTRY_BUFFERED		4
-
-struct _KSEVENT_ENTRY {
-  LIST_ENTRY ListEntry;
-  PVOID Object;
-  __MINGW_EXTENSION union {
-    PKSDPC_ITEM DpcItem;
-    PKSBUFFER_ITEM BufferItem;
-  };
-  PKSEVENTDATA EventData;
-  ULONG NotificationType;
-  const KSEVENT_SET *EventSet;
-  const KSEVENT_ITEM *EventItem;
-  PFILE_OBJECT FileObject;
-  ULONG SemaphoreAdjustment;
-  ULONG Reserved;
-  ULONG Flags;
-};
-
-typedef enum {
-  KSEVENTS_NONE,
-  KSEVENTS_SPINLOCK,
-  KSEVENTS_MUTEX,
-  KSEVENTS_FMUTEX,
-  KSEVENTS_FMUTEXUNSAFE,
-  KSEVENTS_INTERRUPT,
-  KSEVENTS_ERESOURCE
-} KSEVENTS_LOCKTYPE;
-
-#define KSDISPATCH_FASTIO			0x80000000
-
-typedef struct {
-  PDRIVER_DISPATCH Create;
-  PVOID Context;
-  UNICODE_STRING ObjectClass;
-  PSECURITY_DESCRIPTOR SecurityDescriptor;
-  ULONG Flags;
-} KSOBJECT_CREATE_ITEM, *PKSOBJECT_CREATE_ITEM;
-
-typedef VOID (*PFNKSITEMFREECALLBACK)(PKSOBJECT_CREATE_ITEM CreateItem);
-
-#define KSCREATE_ITEM_SECURITYCHANGED		0x00000001
-#define KSCREATE_ITEM_WILDCARD			0x00000002
-#define KSCREATE_ITEM_NOPARAMETERS		0x00000004
-#define KSCREATE_ITEM_FREEONSTOP		0x00000008
-
-#define DEFINE_KSCREATE_DISPATCH_TABLE( tablename )			\
-	KSOBJECT_CREATE_ITEM tablename[] =
-
-#define DEFINE_KSCREATE_ITEM(DispatchCreate,TypeName,Context)		\
-{									\
-			(DispatchCreate), (PVOID)(Context),		\
-			{						\
-				sizeof(TypeName) - sizeof(UNICODE_NULL),\
-				sizeof(TypeName),			\
-				(PWCHAR)(TypeName)			\
-			},						\
-			NULL, 0						\
-}
-
-#define DEFINE_KSCREATE_ITEMEX(DispatchCreate,TypeName,Context,Flags)	\
-{									\
-			(DispatchCreate),				\
-			(PVOID)(Context),				\
-			{						\
-				sizeof(TypeName) - sizeof(UNICODE_NULL),\
-				sizeof(TypeName),			\
-				(PWCHAR)(TypeName)			\
-			},						\
-			NULL, (Flags)					\
-}
-
-#define DEFINE_KSCREATE_ITEMNULL(DispatchCreate,Context)		\
-{									\
-			DispatchCreate, Context,			\
-			{						\
-				0, 0, NULL,				\
-			},						\
-			NULL, 0						\
-}
-
-typedef struct {
-  ULONG CreateItemsCount;
-  PKSOBJECT_CREATE_ITEM CreateItemsList;
-} KSOBJECT_CREATE, *PKSOBJECT_CREATE;
-
-typedef struct {
-  PDRIVER_DISPATCH DeviceIoControl;
-  PDRIVER_DISPATCH Read;
-  PDRIVER_DISPATCH Write;
-  PDRIVER_DISPATCH Flush;
-  PDRIVER_DISPATCH Close;
-  PDRIVER_DISPATCH QuerySecurity;
-  PDRIVER_DISPATCH SetSecurity;
-  PFAST_IO_DEVICE_CONTROL FastDeviceIoControl;
-  PFAST_IO_READ FastRead;
-  PFAST_IO_WRITE FastWrite;
-} KSDISPATCH_TABLE, *PKSDISPATCH_TABLE;
-
-#define DEFINE_KSDISPATCH_TABLE(tablename,DeviceIoControl,Read,Write,Flush,Close,QuerySecurity,SetSecurity,FastDeviceIoControl,FastRead,FastWrite)\
-	const KSDISPATCH_TABLE tablename =				\
-	{								\
-		DeviceIoControl,					\
-		Read,							\
-		Write,							\
-		Flush,							\
-		Close,							\
-		QuerySecurity,						\
-		SetSecurity,						\
-		FastDeviceIoControl,					\
-		FastRead,						\
-		FastWrite,						\
-	}
-
-#define KSCREATE_ITEM_IRP_STORAGE(Irp)					\
-	(*(PKSOBJECT_CREATE_ITEM *)&(Irp)->Tail.Overlay.DriverContext[0])
-#define KSEVENT_SET_IRP_STORAGE(Irp)					\
-	(*(const KSEVENT_SET **)&(Irp)->Tail.Overlay.DriverContext[0])
-#define KSEVENT_ITEM_IRP_STORAGE(Irp)					\
-	(*(const KSEVENT_ITEM **)&(Irp)->Tail.Overlay.DriverContext[3])
-#define KSEVENT_ENTRY_IRP_STORAGE(Irp)					\
-	(*(PKSEVENT_ENTRY *)&(Irp)->Tail.Overlay.DriverContext[0])
-#define KSMETHOD_SET_IRP_STORAGE(Irp)					\
-	(*(const KSMETHOD_SET **)&(Irp)->Tail.Overlay.DriverContext[0])
-#define KSMETHOD_ITEM_IRP_STORAGE(Irp)					\
-	(*(const KSMETHOD_ITEM **)&(Irp)->Tail.Overlay.DriverContext[3])
-#define KSMETHOD_TYPE_IRP_STORAGE(Irp)					\
-	(*(ULONG_PTR *)(&(Irp)->Tail.Overlay.DriverContext[2]))
-#define KSQUEUE_SPINLOCK_IRP_STORAGE(Irp)				\
-	(*(PKSPIN_LOCK *)&(Irp)->Tail.Overlay.DriverContext[1])
-#define KSPROPERTY_SET_IRP_STORAGE(Irp)					\
-	(*(const KSPROPERTY_SET **)&(Irp)->Tail.Overlay.DriverContext[0])
-#define KSPROPERTY_ITEM_IRP_STORAGE(Irp)				\
-	(*(const KSPROPERTY_ITEM **)&(Irp)->Tail.Overlay.DriverContext[3])
-#define KSPROPERTY_ATTRIBUTES_IRP_STORAGE(Irp)				\
-	(*(PKSATTRIBUTE_LIST *)&(Irp)->Tail.Overlay.DriverContext[2])
-
-typedef PVOID		KSDEVICE_HEADER, KSOBJECT_HEADER;
-
-typedef enum {
-  KsInvokeOnSuccess = 1,
-  KsInvokeOnError = 2,
-  KsInvokeOnCancel = 4
-} KSCOMPLETION_INVOCATION;
-
-typedef enum {
-  KsListEntryTail,
-  KsListEntryHead
-} KSLIST_ENTRY_LOCATION;
-
-typedef enum {
-  KsAcquireOnly,
-  KsAcquireAndRemove,
-  KsAcquireOnlySingleItem,
-  KsAcquireAndRemoveOnlySingleItem
-} KSIRP_REMOVAL_OPERATION;
-
-typedef enum {
-  KsStackCopyToNewLocation,
-  KsStackReuseCurrentLocation,
-  KsStackUseNewLocation
-} KSSTACK_USE;
-
-typedef enum {
-  KSTARGET_STATE_DISABLED,
-  KSTARGET_STATE_ENABLED
-} KSTARGET_STATE;
-
-typedef NTSTATUS (*PFNKSIRPLISTCALLBACK)(PIRP Irp, PVOID Context);
-typedef VOID (*PFNREFERENCEDEVICEOBJECT)(PVOID Context);
-typedef VOID (*PFNDEREFERENCEDEVICEOBJECT)(PVOID Context);
-typedef NTSTATUS (*PFNQUERYREFERENCESTRING)(PVOID Context, PWCHAR *String);
-
-#define BUS_INTERFACE_REFERENCE_VERSION			0x100
-
-typedef struct {
-  INTERFACE Interface;
-
-  PFNREFERENCEDEVICEOBJECT ReferenceDeviceObject;
-  PFNDEREFERENCEDEVICEOBJECT DereferenceDeviceObject;
-  PFNQUERYREFERENCESTRING QueryReferenceString;
-} BUS_INTERFACE_REFERENCE, *PBUS_INTERFACE_REFERENCE;
-
-#define STATIC_REFERENCE_BUS_INTERFACE		STATIC_KSMEDIUMSETID_Standard
-#define REFERENCE_BUS_INTERFACE			KSMEDIUMSETID_Standard
-
-#endif /* _NTDDK_ */
-
-#ifndef PACK_PRAGMAS_NOT_SUPPORTED
-#include <pshpack1.h>
-#endif
-
-typedef struct {
-  GUID PropertySet;
-  ULONG Count;
-} KSPROPERTY_SERIALHDR,*PKSPROPERTY_SERIALHDR;
-
-#ifndef PACK_PRAGMAS_NOT_SUPPORTED
-#include <poppack.h>
-#endif
-
-typedef struct {
-  KSIDENTIFIER PropTypeSet;
-  ULONG Id;
-  ULONG PropertyLength;
-} KSPROPERTY_SERIAL,*PKSPROPERTY_SERIAL;
-
-
-#if defined(_NTDDK_)
-
-#define IOCTL_KS_HANDSHAKE						\
-	CTL_CODE(FILE_DEVICE_KS, 0x007, METHOD_NEITHER, FILE_ANY_ACCESS)
-
-typedef struct {
-  GUID ProtocolId;
-  PVOID Argument1;
-  PVOID Argument2;
-} KSHANDSHAKE, *PKSHANDSHAKE;
-
-typedef struct _KSGATE		KSGATE, *PKSGATE;
-
-struct _KSGATE {
-  LONG Count;
-  PKSGATE NextGate;
-};
-
-typedef PVOID KSOBJECT_BAG;
-
-
-typedef BOOLEAN (*PFNKSGENERATEEVENTCALLBACK)(PVOID Context,
-					      PKSEVENT_ENTRY EventEntry);
-
-typedef NTSTATUS (*PFNKSDEVICECREATE)(PKSDEVICE Device);
-
-typedef NTSTATUS (*PFNKSDEVICEPNPSTART)(PKSDEVICE Device,PIRP Irp,
-				PCM_RESOURCE_LIST TranslatedResourceList,
-				PCM_RESOURCE_LIST UntranslatedResourceList);
-
-typedef NTSTATUS (*PFNKSDEVICE)(PKSDEVICE Device);
-
-typedef NTSTATUS (*PFNKSDEVICEIRP)(PKSDEVICE Device,PIRP Irp);
-
-typedef void (*PFNKSDEVICEIRPVOID)(PKSDEVICE Device,PIRP Irp);
-
-typedef NTSTATUS (*PFNKSDEVICEQUERYCAPABILITIES)(PKSDEVICE Device,PIRP Irp,
-					 PDEVICE_CAPABILITIES Capabilities);
-
-typedef NTSTATUS (*PFNKSDEVICEQUERYPOWER)(PKSDEVICE Device,PIRP Irp,
-					  DEVICE_POWER_STATE DeviceTo,
-					  DEVICE_POWER_STATE DeviceFrom,
-					  SYSTEM_POWER_STATE SystemTo,
-					  SYSTEM_POWER_STATE SystemFrom,
-					  POWER_ACTION Action);
-
-typedef void (*PFNKSDEVICESETPOWER)(PKSDEVICE Device,PIRP Irp,
-				    DEVICE_POWER_STATE To,
-				    DEVICE_POWER_STATE From);
-
-typedef NTSTATUS (*PFNKSFILTERFACTORYVOID)(PKSFILTERFACTORY FilterFactory);
-
-typedef void (*PFNKSFILTERFACTORYPOWER)(PKSFILTERFACTORY FilterFactory,
-					DEVICE_POWER_STATE State);
-
-typedef NTSTATUS (*PFNKSFILTERIRP)(PKSFILTER Filter,PIRP Irp);
-
-typedef NTSTATUS (*PFNKSFILTERPROCESS)(PKSFILTER Filter,
-					PKSPROCESSPIN_INDEXENTRY Index);
-
-typedef NTSTATUS (*PFNKSFILTERVOID)(PKSFILTER Filter);
-
-typedef void (*PFNKSFILTERPOWER)(PKSFILTER Filter,DEVICE_POWER_STATE State);
-
-typedef NTSTATUS (*PFNKSPINIRP)(PKSPIN Pin,PIRP Irp);
-
-typedef NTSTATUS (*PFNKSPINSETDEVICESTATE)(PKSPIN Pin,KSSTATE ToState,
-					   KSSTATE FromState);
-
-typedef NTSTATUS (*PFNKSPINSETDATAFORMAT)(PKSPIN Pin,PKSDATAFORMAT OldFormat,
-					  PKSMULTIPLE_ITEM OldAttributeList,
-					  const KSDATARANGE *DataRange,
-					  const KSATTRIBUTE_LIST *AttributeRange);
-
-typedef NTSTATUS (*PFNKSPINHANDSHAKE)(PKSPIN Pin,PKSHANDSHAKE In,
-				      PKSHANDSHAKE Out);
-
-typedef NTSTATUS (*PFNKSPIN)(PKSPIN Pin);
-
-typedef void (*PFNKSPINVOID)(PKSPIN Pin);
-
-typedef void (*PFNKSPINPOWER)(PKSPIN Pin,DEVICE_POWER_STATE State);
-
-typedef BOOLEAN (*PFNKSPINSETTIMER)(PKSPIN Pin,PKTIMER Timer,
-				    LARGE_INTEGER DueTime,PKDPC Dpc);
-
-typedef BOOLEAN (*PFNKSPINCANCELTIMER)(PKSPIN Pin,PKTIMER Timer);
-
-typedef LONGLONG (FASTCALL *PFNKSPINCORRELATEDTIME)(PKSPIN Pin,
-						    PLONGLONG SystemTime);
-
-typedef void (*PFNKSPINRESOLUTION)(PKSPIN Pin,PKSRESOLUTION Resolution);
-
-typedef NTSTATUS (*PFNKSPININITIALIZEALLOCATOR)(PKSPIN Pin,
-					PKSALLOCATOR_FRAMING AllocatorFraming,
-					PVOID *Context);
-
-typedef void (*PFNKSSTREAMPOINTER)(PKSSTREAM_POINTER StreamPointer);
-
-
-typedef struct KSAUTOMATION_TABLE_ KSAUTOMATION_TABLE,*PKSAUTOMATION_TABLE;
-
-struct KSAUTOMATION_TABLE_ {
-  ULONG PropertySetsCount;
-  ULONG PropertyItemSize;
-  const KSPROPERTY_SET *PropertySets;
-  ULONG MethodSetsCount;
-  ULONG MethodItemSize;
-  const KSMETHOD_SET *MethodSets;
-  ULONG EventSetsCount;
-  ULONG EventItemSize;
-  const KSEVENT_SET *EventSets;
-#ifndef _WIN64
-  PVOID Alignment;
-#endif
-};
-
-#define DEFINE_KSAUTOMATION_TABLE(table)				\
-		const KSAUTOMATION_TABLE table =
-
-#define DEFINE_KSAUTOMATION_PROPERTIES(table)				\
-		SIZEOF_ARRAY(table),					\
-		sizeof(KSPROPERTY_ITEM),				\
-		table
-
-#define DEFINE_KSAUTOMATION_METHODS(table)				\
-		SIZEOF_ARRAY(table),					\
-		sizeof(KSMETHOD_ITEM),					\
-		table
-
-#define DEFINE_KSAUTOMATION_EVENTS(table)				\
-		SIZEOF_ARRAY(table),					\
-		sizeof(KSEVENT_ITEM),					\
-		table
-
-#define DEFINE_KSAUTOMATION_PROPERTIES_NULL				\
-		0,							\
-		sizeof(KSPROPERTY_ITEM),				\
-		NULL
-
-#define DEFINE_KSAUTOMATION_METHODS_NULL				\
-		0,							\
-		sizeof(KSMETHOD_ITEM),					\
-		NULL
-
-#define DEFINE_KSAUTOMATION_EVENTS_NULL					\
-		0,							\
-		sizeof(KSEVENT_ITEM),					\
-		NULL
-
-#define MIN_DEV_VER_FOR_QI		(0x100)
-
-struct _KSDEVICE_DISPATCH {
-  PFNKSDEVICECREATE Add;
-  PFNKSDEVICEPNPSTART Start;
-  PFNKSDEVICE PostStart;
-  PFNKSDEVICEIRP QueryStop;
-  PFNKSDEVICEIRPVOID CancelStop;
-  PFNKSDEVICEIRPVOID Stop;
-  PFNKSDEVICEIRP QueryRemove;
-  PFNKSDEVICEIRPVOID CancelRemove;
-  PFNKSDEVICEIRPVOID Remove;
-  PFNKSDEVICEQUERYCAPABILITIES QueryCapabilities;
-  PFNKSDEVICEIRPVOID SurpriseRemoval;
-  PFNKSDEVICEQUERYPOWER QueryPower;
-  PFNKSDEVICESETPOWER SetPower;
-  PFNKSDEVICEIRP QueryInterface;
-};
-
-struct _KSFILTER_DISPATCH {
-  PFNKSFILTERIRP Create;
-  PFNKSFILTERIRP Close;
-  PFNKSFILTERPROCESS Process;
-  PFNKSFILTERVOID Reset;
-};
-
-struct _KSPIN_DISPATCH {
-  PFNKSPINIRP Create;
-  PFNKSPINIRP Close;
-  PFNKSPIN Process;
-  PFNKSPINVOID Reset;
-  PFNKSPINSETDATAFORMAT SetDataFormat;
-  PFNKSPINSETDEVICESTATE SetDeviceState;
-  PFNKSPIN Connect;
-  PFNKSPINVOID Disconnect;
-  const KSCLOCK_DISPATCH *Clock;
-  const KSALLOCATOR_DISPATCH *Allocator;
-};
-
-struct _KSCLOCK_DISPATCH {
-  PFNKSPINSETTIMER SetTimer;
-  PFNKSPINCANCELTIMER CancelTimer;
-  PFNKSPINCORRELATEDTIME CorrelatedTime;
-  PFNKSPINRESOLUTION Resolution;
-};
-
-struct _KSALLOCATOR_DISPATCH {
-  PFNKSPININITIALIZEALLOCATOR InitializeAllocator;
-  PFNKSDELETEALLOCATOR DeleteAllocator;
-  PFNKSDEFAULTALLOCATE Allocate;
-  PFNKSDEFAULTFREE Free;
-};
-
-#define KSDEVICE_DESCRIPTOR_VERSION	(0x100)
-
-struct _KSDEVICE_DESCRIPTOR {
-  const KSDEVICE_DISPATCH *Dispatch;
-  ULONG FilterDescriptorsCount;
-  const KSFILTER_DESCRIPTOR*const *FilterDescriptors;
-  ULONG Version;
-};
-
-struct _KSFILTER_DESCRIPTOR {
-  const KSFILTER_DISPATCH *Dispatch;
-  const KSAUTOMATION_TABLE *AutomationTable;
-  ULONG Version;
-#define KSFILTER_DESCRIPTOR_VERSION	((ULONG)-1)
-  ULONG Flags;
-#define KSFILTER_FLAG_DISPATCH_LEVEL_PROCESSING		0x00000001
-#define KSFILTER_FLAG_CRITICAL_PROCESSING		0x00000002
-#define KSFILTER_FLAG_HYPERCRITICAL_PROCESSING		0x00000004
-#define KSFILTER_FLAG_RECEIVE_ZERO_LENGTH_SAMPLES	0x00000008
-#define KSFILTER_FLAG_DENY_USERMODE_ACCESS		0x80000000
-  const GUID *ReferenceGuid;
-  ULONG PinDescriptorsCount;
-  ULONG PinDescriptorSize;
-  const KSPIN_DESCRIPTOR_EX *PinDescriptors;
-  ULONG CategoriesCount;
-  const GUID *Categories;
-  ULONG NodeDescriptorsCount;
-  ULONG NodeDescriptorSize;
-  const KSNODE_DESCRIPTOR *NodeDescriptors;
-  ULONG ConnectionsCount;
-  const KSTOPOLOGY_CONNECTION *Connections;
-  const KSCOMPONENTID *ComponentId;
-};
-
-#define DEFINE_KSFILTER_DESCRIPTOR(descriptor)				\
-	const KSFILTER_DESCRIPTOR descriptor =
-
-#define DEFINE_KSFILTER_PIN_DESCRIPTORS(table)				\
-	SIZEOF_ARRAY(table),						\
-	sizeof(table[0]),						\
-	table
-
-#define DEFINE_KSFILTER_CATEGORIES(table)				\
-	SIZEOF_ARRAY(table),						\
-	table
-
-#define DEFINE_KSFILTER_CATEGORY(category)				\
-	1,								\
-	&(category)
-
-#define DEFINE_KSFILTER_CATEGORIES_NULL					\
-	0,								\
-	NULL
-
-#define DEFINE_KSFILTER_NODE_DESCRIPTORS(table)				\
-	SIZEOF_ARRAY(table),						\
-	sizeof(table[0]),						\
-	table
-
-#define DEFINE_KSFILTER_NODE_DESCRIPTORS_NULL				\
-	0,								\
-	sizeof(KSNODE_DESCRIPTOR),					\
-	NULL
-
-#define DEFINE_KSFILTER_CONNECTIONS(table)				\
-	SIZEOF_ARRAY(table),						\
-	table
-
-#define DEFINE_KSFILTER_DEFAULT_CONNECTIONS				\
-	0,								\
-	NULL
-
-#define DEFINE_KSFILTER_DESCRIPTOR_TABLE(table)				\
-	const KSFILTER_DESCRIPTOR*const table[] =
-
-struct _KSPIN_DESCRIPTOR_EX {
-  const KSPIN_DISPATCH *Dispatch;
-  const KSAUTOMATION_TABLE *AutomationTable;
-  KSPIN_DESCRIPTOR PinDescriptor;
-  ULONG Flags;
-#define KSPIN_FLAG_DISPATCH_LEVEL_PROCESSING	KSFILTER_FLAG_DISPATCH_LEVEL_PROCESSING
-#define KSPIN_FLAG_CRITICAL_PROCESSING		KSFILTER_FLAG_CRITICAL_PROCESSING
-#define KSPIN_FLAG_HYPERCRITICAL_PROCESSING	KSFILTER_FLAG_HYPERCRITICAL_PROCESSING
-#define KSPIN_FLAG_ASYNCHRONOUS_PROCESSING			0x00000008
-#define KSPIN_FLAG_DO_NOT_INITIATE_PROCESSING			0x00000010
-#define KSPIN_FLAG_INITIATE_PROCESSING_ON_EVERY_ARRIVAL		0x00000020
-#define KSPIN_FLAG_FRAMES_NOT_REQUIRED_FOR_PROCESSING		0x00000040
-#define KSPIN_FLAG_ENFORCE_FIFO					0x00000080
-#define KSPIN_FLAG_GENERATE_MAPPINGS				0x00000100
-#define KSPIN_FLAG_DISTINCT_TRAILING_EDGE			0x00000200
-#define KSPIN_FLAG_PROCESS_IN_RUN_STATE_ONLY			0x00010000
-#define KSPIN_FLAG_SPLITTER					0x00020000
-#define KSPIN_FLAG_USE_STANDARD_TRANSPORT			0x00040000
-#define KSPIN_FLAG_DO_NOT_USE_STANDARD_TRANSPORT		0x00080000
-#define KSPIN_FLAG_FIXED_FORMAT					0x00100000
-#define KSPIN_FLAG_GENERATE_EOS_EVENTS				0x00200000
-#define KSPIN_FLAG_RENDERER			(KSPIN_FLAG_PROCESS_IN_RUN_STATE_ONLY|KSPIN_FLAG_GENERATE_EOS_EVENTS)
-#define KSPIN_FLAG_IMPLEMENT_CLOCK				0x00400000
-#define KSPIN_FLAG_SOME_FRAMES_REQUIRED_FOR_PROCESSING		0x00800000
-#define KSPIN_FLAG_PROCESS_IF_ANY_IN_RUN_STATE			0x01000000
-#define KSPIN_FLAG_DENY_USERMODE_ACCESS				0x80000000
-  ULONG InstancesPossible;
-  ULONG InstancesNecessary;
-  const KSALLOCATOR_FRAMING_EX *AllocatorFraming;
-  PFNKSINTERSECTHANDLEREX IntersectHandler;
-};
-
-#define DEFINE_KSPIN_DEFAULT_INTERFACES					\
-	0,								\
-	NULL
-
-#define DEFINE_KSPIN_DEFAULT_MEDIUMS					\
-	0,								\
-	NULL
-
-struct _KSNODE_DESCRIPTOR {
-  const KSAUTOMATION_TABLE *AutomationTable;
-  const GUID *Type;
-  const GUID *Name;
-#ifndef _WIN64
-  PVOID Alignment;
-#endif
-};
-
-#ifndef _WIN64
-#define DEFINE_NODE_DESCRIPTOR(automation,type,name)			\
-	{ (automation), (type), (name), NULL }
-#else
-#define DEFINE_NODE_DESCRIPTOR(automation,type,name)			\
-	{ (automation), (type), (name) }
-#endif
-
-struct _KSDEVICE {
-  const KSDEVICE_DESCRIPTOR *Descriptor;
-  KSOBJECT_BAG Bag;
-  PVOID Context;
-  PDEVICE_OBJECT FunctionalDeviceObject;
-  PDEVICE_OBJECT PhysicalDeviceObject;
-  PDEVICE_OBJECT NextDeviceObject;
-  BOOLEAN Started;
-  SYSTEM_POWER_STATE SystemPowerState;
-  DEVICE_POWER_STATE DevicePowerState;
-};
-
-struct _KSFILTERFACTORY {
-  const KSFILTER_DESCRIPTOR *FilterDescriptor;
-  KSOBJECT_BAG Bag;
-  PVOID Context;
-};
-
-struct _KSFILTER {
-  const KSFILTER_DESCRIPTOR *Descriptor;
-  KSOBJECT_BAG Bag;
-  PVOID Context;
-};
-
-struct _KSPIN {
-  const KSPIN_DESCRIPTOR_EX *Descriptor;
-  KSOBJECT_BAG Bag;
-  PVOID Context;
-  ULONG Id;
-  KSPIN_COMMUNICATION Communication;
-  BOOLEAN ConnectionIsExternal;
-  KSPIN_INTERFACE ConnectionInterface;
-  KSPIN_MEDIUM ConnectionMedium;
-  KSPRIORITY ConnectionPriority;
-  PKSDATAFORMAT ConnectionFormat;
-  PKSMULTIPLE_ITEM AttributeList;
-  ULONG StreamHeaderSize;
-  KSPIN_DATAFLOW DataFlow;
-  KSSTATE DeviceState;
-  KSRESET ResetState;
-  KSSTATE ClientState;
-};
-
-struct _KSMAPPING {
-  PHYSICAL_ADDRESS PhysicalAddress;
-  ULONG ByteCount;
-  ULONG Alignment;
-};
-
-struct _KSSTREAM_POINTER_OFFSET
-{
-#if defined(_NTDDK_)
-  __MINGW_EXTENSION union {
-    PUCHAR Data;
-    PKSMAPPING Mappings;
-  };
-#else
-  PUCHAR Data;
-#endif /* _NTDDK_ */
-#ifndef _WIN64
-  PVOID Alignment;
-#endif
-  ULONG Count;
-  ULONG Remaining;
-};
-
-struct _KSSTREAM_POINTER
-{
-  PVOID Context;
-  PKSPIN Pin;
-  PKSSTREAM_HEADER StreamHeader;
-  PKSSTREAM_POINTER_OFFSET Offset;
-  KSSTREAM_POINTER_OFFSET OffsetIn;
-  KSSTREAM_POINTER_OFFSET OffsetOut;
-};
-
-struct _KSPROCESSPIN {
-  PKSPIN Pin;
-  PKSSTREAM_POINTER StreamPointer;
-  PKSPROCESSPIN InPlaceCounterpart;
-  PKSPROCESSPIN DelegateBranch;
-  PKSPROCESSPIN CopySource;
-  PVOID Data;
-  ULONG BytesAvailable;
-  ULONG BytesUsed;
-  ULONG Flags;
-  BOOLEAN Terminate;
-};
-
-struct _KSPROCESSPIN_INDEXENTRY {
-  PKSPROCESSPIN *Pins;
-  ULONG Count;
-};
-
-typedef enum {
-  KsObjectTypeDevice,
-  KsObjectTypeFilterFactory,
-  KsObjectTypeFilter,
-  KsObjectTypePin
-} KSOBJECTTYPE;
-
-
-typedef void (*PFNKSFREE)(PVOID Data);
-
-typedef void (*PFNKSPINFRAMERETURN)(PKSPIN Pin,PVOID Data,ULONG Size,PMDL Mdl,
-				    PVOID Context,NTSTATUS Status);
-
-typedef void (*PFNKSPINIRPCOMPLETION)(PKSPIN Pin,PIRP Irp);
-
-
-#if defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__)
-#ifndef _IKsControl_
-#define _IKsControl_
-
-typedef struct IKsControl *PIKSCONTROL;
-
-#ifndef DEFINE_ABSTRACT_UNKNOWN
-#define DEFINE_ABSTRACT_UNKNOWN()					\
-	STDMETHOD_(NTSTATUS,QueryInterface) (THIS_ 			\
-						REFIID InterfaceId,	\
-						PVOID *Interface	\
-					    ) PURE;			\
-	STDMETHOD_(ULONG,AddRef)(THIS) PURE;				\
-	STDMETHOD_(ULONG,Release)(THIS) PURE;
-#endif
-
-#undef INTERFACE
-#define INTERFACE IKsControl
-DECLARE_INTERFACE_(IKsControl,IUnknown)
-{
-  DEFINE_ABSTRACT_UNKNOWN()
-  STDMETHOD_(NTSTATUS,KsProperty)(THIS_
-					PKSPROPERTY Property,
-					ULONG PropertyLength,
-					PVOID PropertyData,
-					ULONG DataLength,
-					ULONG *BytesReturned
-				 ) PURE;
-  STDMETHOD_(NTSTATUS,KsMethod)	(THIS_
-					PKSMETHOD Method,
-					ULONG MethodLength,
-					PVOID MethodData,
-					ULONG DataLength,
-					ULONG *BytesReturned
-				 ) PURE;
-  STDMETHOD_(NTSTATUS,KsEvent)	(THIS_
-					PKSEVENT Event,
-					ULONG EventLength,
-					PVOID EventData,
-					ULONG DataLength,
-					ULONG *BytesReturned
-				) PURE;
-};
-typedef struct IKsReferenceClock *PIKSREFERENCECLOCK;
-
-#undef INTERFACE
-#define INTERFACE IKsReferenceClock
-DECLARE_INTERFACE_(IKsReferenceClock,IUnknown)
-{
-  DEFINE_ABSTRACT_UNKNOWN()
-  STDMETHOD_(LONGLONG,GetTime)		(THIS) PURE;
-  STDMETHOD_(LONGLONG,GetPhysicalTime)	(THIS) PURE;
-  STDMETHOD_(LONGLONG,GetCorrelatedTime)(THIS_
-  						PLONGLONG SystemTime
-  					) PURE;
-  STDMETHOD_(LONGLONG,GetCorrelatedPhysicalTime)(THIS_
-						PLONGLONG SystemTime
-					) PURE;
-  STDMETHOD_(NTSTATUS,GetResolution)	(THIS_
-						PKSRESOLUTION Resolution
-					) PURE;
-  STDMETHOD_(NTSTATUS,GetState)		(THIS_
-						PKSSTATE State
-					) PURE;
-};
-#undef INTERFACE
-
-#define INTERFACE IKsDeviceFunctions
-DECLARE_INTERFACE_(IKsDeviceFunctions,IUnknown)
-{
-  DEFINE_ABSTRACT_UNKNOWN()
-  STDMETHOD_(NTSTATUS,RegisterAdapterObjectEx)	(THIS_
-						  PADAPTER_OBJECT AdapterObject,
-						  PDEVICE_DESCRIPTION DeviceDescription,
-						  ULONG NumberOfMapRegisters,
-						  ULONG MaxMappingsByteCount,
-						  ULONG MappingTableStride
-						) PURE;
-};
-
-#undef INTERFACE
-#define STATIC_IID_IKsControl						\
-	0x28F54685L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUID(IID_IKsControl,
-	0x28F54685L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96);
-#define STATIC_IID_IKsFastClock						\
-	0xc9902485,0xc180,0x11d2,0x84,0x73,0xd4,0x23,0x94,0x45,0x9e,0x5e
-DEFINE_GUID(IID_IKsFastClock,
-	0xc9902485,0xc180,0x11d2,0x84,0x73,0xd4,0x23,0x94,0x45,0x9e,0x5e);
-#define STATIC_IID_IKsDeviceFunctions					\
-	0xe234f2e2,0xbd69,0x4f8c,0xb3,0xf2,0x7c,0xd7,0x9e,0xd4,0x66,0xbd
-DEFINE_GUID(IID_IKsDeviceFunctions,
-	0xe234f2e2,0xbd69,0x4f8c,0xb3,0xf2,0x7c,0xd7,0x9e,0xd4,0x66,0xbd);
-#endif /* _IKsControl_ */
-#endif /* defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__) */
-
-#endif /* _NTDDK_ */
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef _KSDDK_
-#define KSDDKAPI
-#else
-#define KSDDKAPI DECLSPEC_IMPORT
-#endif
-
-#if defined(_NTDDK_)
-
-KSDDKAPI NTSTATUS NTAPI KsEnableEvent
-			(PIRP Irp, ULONG EventSetsCount, const KSEVENT_SET *EventSet,
-			 PLIST_ENTRY EventsList, KSEVENTS_LOCKTYPE EventsFlags,
-			 PVOID EventsLock);
-
-KSDDKAPI NTSTATUS NTAPI KsEnableEventWithAllocator
-			(PIRP Irp, ULONG EventSetsCount, const KSEVENT_SET *EventSet,
-			 PLIST_ENTRY EventsList, KSEVENTS_LOCKTYPE EventsFlags,
-			 PVOID EventsLock, PFNKSALLOCATOR Allocator, ULONG EventItemSize);
-
-KSDDKAPI NTSTATUS NTAPI KsDisableEvent
-			(PIRP Irp, PLIST_ENTRY EventsList, KSEVENTS_LOCKTYPE EventsFlags,
-			 PVOID EventsLock);
-
-KSDDKAPI VOID NTAPI KsDiscardEvent (PKSEVENT_ENTRY EventEntry);
-
-KSDDKAPI VOID NTAPI KsFreeEventList
-			(PFILE_OBJECT FileObject, PLIST_ENTRY EventsList,
-			 KSEVENTS_LOCKTYPE EventsFlags, PVOID EventsLock);
-
-KSDDKAPI NTSTATUS NTAPI KsGenerateEvent (PKSEVENT_ENTRY EventEntry);
-
-KSDDKAPI NTSTATUS NTAPI KsGenerateDataEvent
-			(PKSEVENT_ENTRY EventEntry, ULONG DataSize, PVOID Data);
-
-KSDDKAPI VOID NTAPI KsGenerateEventList
-			(GUID *Set, ULONG EventId, PLIST_ENTRY EventsList,
-			 KSEVENTS_LOCKTYPE EventsFlags, PVOID EventsLock);
-
-KSDDKAPI NTSTATUS NTAPI KsPropertyHandler
-			(PIRP Irp, ULONG PropertySetsCount,
-			 const KSPROPERTY_SET *PropertySet);
-
-KSDDKAPI NTSTATUS NTAPI KsPropertyHandlerWithAllocator
-			(PIRP Irp, ULONG PropertySetsCount,
-			 const KSPROPERTY_SET *PropertySet, PFNKSALLOCATOR Allocator,
-			 ULONG PropertyItemSize);
-
-KSDDKAPI BOOLEAN NTAPI KsFastPropertyHandler
-			(PFILE_OBJECT FileObject, PKSPROPERTY Property,
-			 ULONG PropertyLength, PVOID Data, ULONG DataLength,
-			 PIO_STATUS_BLOCK IoStatus, ULONG PropertySetsCount,
-			 const KSPROPERTY_SET *PropertySet);
-
-KSDDKAPI NTSTATUS NTAPI KsMethodHandler
-			(PIRP Irp, ULONG MethodSetsCount,
-			 const KSMETHOD_SET *MethodSet);
-
-KSDDKAPI NTSTATUS NTAPI KsMethodHandlerWithAllocator
-			(PIRP Irp, ULONG MethodSetsCount,
-			 const KSMETHOD_SET *MethodSet, PFNKSALLOCATOR Allocator,
-			 ULONG MethodItemSize);
-
-KSDDKAPI BOOLEAN NTAPI KsFastMethodHandler
-			(PFILE_OBJECT FileObject, PKSMETHOD Method, ULONG MethodLength,
-			 PVOID Data, ULONG DataLength, PIO_STATUS_BLOCK IoStatus,
-			 ULONG MethodSetsCount, const KSMETHOD_SET *MethodSet);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateDefaultAllocator (PIRP Irp);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateDefaultAllocatorEx
-			(PIRP Irp, PVOID InitializeContext,
-			 PFNKSDEFAULTALLOCATE DefaultAllocate,
-			 PFNKSDEFAULTFREE DefaultFree,
-			 PFNKSINITIALIZEALLOCATOR InitializeAllocator,
-			 PFNKSDELETEALLOCATOR DeleteAllocator);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateAllocator
-			(HANDLE ConnectionHandle, PKSALLOCATOR_FRAMING AllocatorFraming,
-			 PHANDLE AllocatorHandle);
-
-KSDDKAPI NTSTATUS NTAPI KsValidateAllocatorCreateRequest
-			(PIRP Irp, PKSALLOCATOR_FRAMING *AllocatorFraming);
-
-KSDDKAPI NTSTATUS NTAPI KsValidateAllocatorFramingEx
-			(PKSALLOCATOR_FRAMING_EX Framing, ULONG BufferSize,
-			 const KSALLOCATOR_FRAMING_EX *PinFraming);
-
-KSDDKAPI NTSTATUS NTAPI KsAllocateDefaultClock (PKSDEFAULTCLOCK *DefaultClock);
-
-KSDDKAPI NTSTATUS NTAPI KsAllocateDefaultClockEx
-			(PKSDEFAULTCLOCK *DefaultClock, PVOID Context,
-			 PFNKSSETTIMER SetTimer, PFNKSCANCELTIMER CancelTimer,
-			 PFNKSCORRELATEDTIME CorrelatedTime,
-			 const KSRESOLUTION *Resolution, ULONG Flags);
-
-KSDDKAPI VOID NTAPI KsFreeDefaultClock (PKSDEFAULTCLOCK DefaultClock);
-KSDDKAPI NTSTATUS NTAPI KsCreateDefaultClock (PIRP Irp, PKSDEFAULTCLOCK DefaultClock);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateClock
-			(HANDLE ConnectionHandle, PKSCLOCK_CREATE ClockCreate,
-			 PHANDLE ClockHandle);
-
-KSDDKAPI NTSTATUS NTAPI KsValidateClockCreateRequest
-			(PIRP Irp, PKSCLOCK_CREATE *ClockCreate);
-
-KSDDKAPI KSSTATE NTAPI KsGetDefaultClockState (PKSDEFAULTCLOCK DefaultClock);
-KSDDKAPI VOID NTAPI KsSetDefaultClockState(PKSDEFAULTCLOCK DefaultClock, KSSTATE State);
-KSDDKAPI LONGLONG NTAPI KsGetDefaultClockTime (PKSDEFAULTCLOCK DefaultClock);
-KSDDKAPI VOID NTAPI KsSetDefaultClockTime(PKSDEFAULTCLOCK DefaultClock, LONGLONG Time);
-
-KSDDKAPI NTSTATUS NTAPI KsCreatePin
-			(HANDLE FilterHandle, PKSPIN_CONNECT Connect,
-			 ACCESS_MASK DesiredAccess, PHANDLE ConnectionHandle);
-
-KSDDKAPI NTSTATUS NTAPI KsValidateConnectRequest
-			(PIRP Irp, ULONG DescriptorsCount,
-			 const KSPIN_DESCRIPTOR *Descriptor, PKSPIN_CONNECT *Connect);
-
-KSDDKAPI NTSTATUS NTAPI KsPinPropertyHandler
-			(PIRP Irp, PKSPROPERTY Property, PVOID Data,
-			 ULONG DescriptorsCount, const KSPIN_DESCRIPTOR *Descriptor);
-
-KSDDKAPI NTSTATUS NTAPI KsPinDataIntersection
-			(PIRP Irp, PKSP_PIN Pin, PVOID Data, ULONG DescriptorsCount,
-			 const KSPIN_DESCRIPTOR *Descriptor,
-			 PFNKSINTERSECTHANDLER IntersectHandler);
-
-KSDDKAPI NTSTATUS NTAPI KsPinDataIntersectionEx
-			(PIRP Irp, PKSP_PIN Pin, PVOID Data, ULONG DescriptorsCount,
-			 const KSPIN_DESCRIPTOR *Descriptor, ULONG DescriptorSize,
-			 PFNKSINTERSECTHANDLEREX IntersectHandler, PVOID HandlerContext);
-
-KSDDKAPI NTSTATUS NTAPI KsHandleSizedListQuery
-			(PIRP Irp, ULONG DataItemsCount, ULONG DataItemSize,
-			 const VOID *DataItems);
-
-#ifndef MAKEINTRESOURCE
-#define MAKEINTRESOURCE(r)		((ULONG_PTR) (USHORT) r)
-#endif
-#ifndef RT_STRING
-#define RT_STRING			MAKEINTRESOURCE(6)
-#define RT_RCDATA			MAKEINTRESOURCE(10)
-#endif
-
-KSDDKAPI NTSTATUS NTAPI KsLoadResource
-			(PVOID ImageBase, POOL_TYPE PoolType, ULONG_PTR ResourceName,
-			 ULONG ResourceType, PVOID *Resource, PULONG ResourceSize);
-
-KSDDKAPI NTSTATUS NTAPI KsGetImageNameAndResourceId
-			(HANDLE RegKey, PUNICODE_STRING ImageName, PULONG_PTR ResourceId,
-			 PULONG ValueType);
-
-KSDDKAPI NTSTATUS NTAPI KsMapModuleName
-			(PDEVICE_OBJECT PhysicalDeviceObject, PUNICODE_STRING ModuleName,
-			 PUNICODE_STRING ImageName, PULONG_PTR ResourceId,
-			 PULONG ValueType);
-
-KSDDKAPI NTSTATUS NTAPI KsReferenceBusObject (KSDEVICE_HEADER Header);
-KSDDKAPI VOID NTAPI KsDereferenceBusObject (KSDEVICE_HEADER Header);
-KSDDKAPI NTSTATUS NTAPI KsDispatchQuerySecurity (PDEVICE_OBJECT DeviceObject, PIRP Irp);
-KSDDKAPI NTSTATUS NTAPI KsDispatchSetSecurity (PDEVICE_OBJECT DeviceObject, PIRP Irp);
-KSDDKAPI NTSTATUS NTAPI KsDispatchSpecificProperty (PIRP Irp, PFNKSHANDLER Handler);
-KSDDKAPI NTSTATUS NTAPI KsDispatchSpecificMethod (PIRP Irp, PFNKSHANDLER Handler);
-
-KSDDKAPI NTSTATUS NTAPI KsReadFile
-			(PFILE_OBJECT FileObject, PKEVENT Event, PVOID PortContext,
-			 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length,
-			 ULONG Key, KPROCESSOR_MODE RequestorMode);
-
-KSDDKAPI NTSTATUS NTAPI KsWriteFile
-			(PFILE_OBJECT FileObject, PKEVENT Event, PVOID PortContext,
-			 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length,
-			 ULONG Key, KPROCESSOR_MODE RequestorMode);
-
-KSDDKAPI NTSTATUS NTAPI KsQueryInformationFile
-			(PFILE_OBJECT FileObject, PVOID FileInformation, ULONG Length,
-			 FILE_INFORMATION_CLASS FileInformationClass);
-
-KSDDKAPI NTSTATUS NTAPI KsSetInformationFile
-			(PFILE_OBJECT FileObject, PVOID FileInformation, ULONG Length,
-			 FILE_INFORMATION_CLASS FileInformationClass);
-
-KSDDKAPI NTSTATUS NTAPI KsStreamIo
-			(PFILE_OBJECT FileObject, PKEVENT Event, PVOID PortContext,
-			 PIO_COMPLETION_ROUTINE CompletionRoutine, PVOID CompletionContext,
-			 KSCOMPLETION_INVOCATION CompletionInvocationFlags,
-			 PIO_STATUS_BLOCK IoStatusBlock, PVOID StreamHeaders, ULONG Length,
-			 ULONG Flags, KPROCESSOR_MODE RequestorMode);
-
-KSDDKAPI NTSTATUS NTAPI KsProbeStreamIrp(PIRP Irp, ULONG ProbeFlags, ULONG HeaderSize);
-KSDDKAPI NTSTATUS NTAPI KsAllocateExtraData(PIRP Irp, ULONG ExtraSize, PVOID *ExtraBuffer);
-KSDDKAPI VOID NTAPI KsNullDriverUnload (PDRIVER_OBJECT DriverObject);
-
-KSDDKAPI NTSTATUS NTAPI KsSetMajorFunctionHandler
-			(PDRIVER_OBJECT DriverObject, ULONG MajorFunction);
-
-KSDDKAPI NTSTATUS NTAPI KsDispatchInvalidDeviceRequest
-			(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-
-KSDDKAPI NTSTATUS NTAPI KsDefaultDeviceIoCompletion
-			(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-
-KSDDKAPI NTSTATUS NTAPI KsDispatchIrp(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-
-KSDDKAPI BOOLEAN NTAPI KsDispatchFastIoDeviceControlFailure
-			(PFILE_OBJECT FileObject, BOOLEAN Wait, PVOID InputBuffer,
-			 ULONG InputBufferLength, PVOID OutputBuffer,
-			 ULONG OutputBufferLength, ULONG IoControlCode,
-			 PIO_STATUS_BLOCK IoStatus, PDEVICE_OBJECT DeviceObject);
-
-KSDDKAPI BOOLEAN NTAPI KsDispatchFastReadFailure
-			(PFILE_OBJECT FileObject, PLARGE_INTEGER FileOffset,
-			 ULONG Length, BOOLEAN Wait, ULONG LockKey, PVOID Buffer,
-			 PIO_STATUS_BLOCK IoStatus, PDEVICE_OBJECT DeviceObject);
-
-#define KsDispatchFastWriteFailure		KsDispatchFastReadFailure
-
-KSDDKAPI VOID NTAPI KsCancelRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-KSDDKAPI VOID NTAPI KsCancelIo(PLIST_ENTRY QueueHead, PKSPIN_LOCK SpinLock);
-KSDDKAPI VOID NTAPI KsReleaseIrpOnCancelableQueue(PIRP Irp, PDRIVER_CANCEL DriverCancel);
-
-KSDDKAPI PIRP NTAPI KsRemoveIrpFromCancelableQueue
-			(PLIST_ENTRY QueueHead, PKSPIN_LOCK SpinLock,
-			 KSLIST_ENTRY_LOCATION ListLocation,
-			 KSIRP_REMOVAL_OPERATION RemovalOperation);
-
-KSDDKAPI NTSTATUS NTAPI KsMoveIrpsOnCancelableQueue
-			(PLIST_ENTRY SourceList, PKSPIN_LOCK SourceLock,
-			 PLIST_ENTRY DestinationList, PKSPIN_LOCK DestinationLock,
-			 KSLIST_ENTRY_LOCATION ListLocation,
-			 PFNKSIRPLISTCALLBACK ListCallback, PVOID Context);
-
-KSDDKAPI VOID NTAPI KsRemoveSpecificIrpFromCancelableQueue (PIRP Irp);
-
-KSDDKAPI VOID NTAPI KsAddIrpToCancelableQueue
-			(PLIST_ENTRY QueueHead, PKSPIN_LOCK SpinLock, PIRP Irp,
-			 KSLIST_ENTRY_LOCATION ListLocation, PDRIVER_CANCEL DriverCancel);
-
-KSDDKAPI NTSTATUS NTAPI KsAcquireResetValue(PIRP Irp, KSRESET *ResetValue);
-
-KSDDKAPI NTSTATUS NTAPI KsTopologyPropertyHandler
-			(PIRP Irp, PKSPROPERTY Property, PVOID Data,
-			 const KSTOPOLOGY *Topology);
-
-KSDDKAPI VOID NTAPI KsAcquireDeviceSecurityLock(KSDEVICE_HEADER Header, BOOLEAN Exclusive);
-KSDDKAPI VOID NTAPI KsReleaseDeviceSecurityLock (KSDEVICE_HEADER Header);
-KSDDKAPI NTSTATUS NTAPI KsDefaultDispatchPnp(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-KSDDKAPI NTSTATUS NTAPI KsDefaultDispatchPower(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-KSDDKAPI NTSTATUS NTAPI KsDefaultForwardIrp(PDEVICE_OBJECT DeviceObject, PIRP Irp);
-
-KSDDKAPI VOID NTAPI KsSetDevicePnpAndBaseObject
-			(KSDEVICE_HEADER Header, PDEVICE_OBJECT PnpDeviceObject,
-			 PDEVICE_OBJECT BaseObject);
-
-KSDDKAPI PDEVICE_OBJECT NTAPI KsQueryDevicePnpObject (KSDEVICE_HEADER Header);
-KSDDKAPI ACCESS_MASK NTAPI KsQueryObjectAccessMask (KSOBJECT_HEADER Header);
-
-KSDDKAPI VOID NTAPI KsRecalculateStackDepth
-			(KSDEVICE_HEADER Header, BOOLEAN ReuseStackLocation);
-
-KSDDKAPI VOID NTAPI KsSetTargetState
-			(KSOBJECT_HEADER Header, KSTARGET_STATE TargetState);
-
-KSDDKAPI VOID NTAPI KsSetTargetDeviceObject
-			(KSOBJECT_HEADER Header, PDEVICE_OBJECT TargetDevice);
-
-KSDDKAPI VOID NTAPI KsSetPowerDispatch
-			(KSOBJECT_HEADER Header, PFNKSCONTEXT_DISPATCH PowerDispatch,
-			 PVOID PowerContext);
-
-KSDDKAPI PKSOBJECT_CREATE_ITEM NTAPI KsQueryObjectCreateItem (KSOBJECT_HEADER Header);
-
-KSDDKAPI NTSTATUS NTAPI KsAllocateDeviceHeader
-			(KSDEVICE_HEADER *Header, ULONG ItemsCount,
-			 PKSOBJECT_CREATE_ITEM ItemsList);
-
-KSDDKAPI VOID NTAPI KsFreeDeviceHeader (KSDEVICE_HEADER Header);
-
-KSDDKAPI NTSTATUS NTAPI KsAllocateObjectHeader
-			(KSOBJECT_HEADER *Header, ULONG ItemsCount,
-			 PKSOBJECT_CREATE_ITEM ItemsList, PIRP Irp,
-			 const KSDISPATCH_TABLE *Table);
-
-KSDDKAPI VOID NTAPI KsFreeObjectHeader (KSOBJECT_HEADER Header);
-
-KSDDKAPI NTSTATUS NTAPI KsAddObjectCreateItemToDeviceHeader
-			(KSDEVICE_HEADER Header, PDRIVER_DISPATCH Create, PVOID Context,
-			 PWSTR ObjectClass, PSECURITY_DESCRIPTOR SecurityDescriptor);
-
-KSDDKAPI NTSTATUS NTAPI KsAddObjectCreateItemToObjectHeader
-			(KSOBJECT_HEADER Header, PDRIVER_DISPATCH Create, PVOID Context,
-			 PWSTR ObjectClass, PSECURITY_DESCRIPTOR SecurityDescriptor);
-
-KSDDKAPI NTSTATUS NTAPI KsAllocateObjectCreateItem
-			(KSDEVICE_HEADER Header, PKSOBJECT_CREATE_ITEM CreateItem,
-			 BOOLEAN AllocateEntry, PFNKSITEMFREECALLBACK ItemFreeCallback);
-
-KSDDKAPI NTSTATUS NTAPI KsFreeObjectCreateItem
-			(KSDEVICE_HEADER Header, PUNICODE_STRING CreateItem);
-
-KSDDKAPI NTSTATUS NTAPI KsFreeObjectCreateItemsByContext
-			(KSDEVICE_HEADER Header, PVOID Context);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateDefaultSecurity
-			(PSECURITY_DESCRIPTOR ParentSecurity,
-			 PSECURITY_DESCRIPTOR *DefaultSecurity);
-
-KSDDKAPI NTSTATUS NTAPI KsForwardIrp
-			(PIRP Irp, PFILE_OBJECT FileObject, BOOLEAN ReuseStackLocation);
-
-KSDDKAPI NTSTATUS NTAPI KsForwardAndCatchIrp
-			(PDEVICE_OBJECT DeviceObject, PIRP Irp, PFILE_OBJECT FileObject,
-			 KSSTACK_USE StackUse);
-
-KSDDKAPI NTSTATUS NTAPI KsSynchronousIoControlDevice
-			(PFILE_OBJECT FileObject, KPROCESSOR_MODE RequestorMode,
-			 ULONG IoControl, PVOID InBuffer, ULONG InSize, PVOID OutBuffer,
-			 ULONG OutSize, PULONG BytesReturned);
-
-KSDDKAPI NTSTATUS NTAPI KsUnserializeObjectPropertiesFromRegistry
-			(PFILE_OBJECT FileObject, HANDLE ParentKey,
-			 PUNICODE_STRING RegistryPath);
-
-KSDDKAPI NTSTATUS NTAPI KsCacheMedium
-			(PUNICODE_STRING SymbolicLink, PKSPIN_MEDIUM Medium,
-			 ULONG PinDirection);
-
-KSDDKAPI NTSTATUS NTAPI KsRegisterWorker
-			(WORK_QUEUE_TYPE WorkQueueType, PKSWORKER *Worker);
-
-KSDDKAPI NTSTATUS NTAPI KsRegisterCountedWorker
-			(WORK_QUEUE_TYPE WorkQueueType, PWORK_QUEUE_ITEM CountedWorkItem,
-			 PKSWORKER *Worker);
-
-KSDDKAPI VOID NTAPI KsUnregisterWorker (PKSWORKER Worker);
-KSDDKAPI NTSTATUS NTAPI KsQueueWorkItem(PKSWORKER Worker, PWORK_QUEUE_ITEM WorkItem);
-KSDDKAPI ULONG NTAPI KsIncrementCountedWorker (PKSWORKER Worker);
-KSDDKAPI ULONG NTAPI KsDecrementCountedWorker (PKSWORKER Worker);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateTopologyNode
-			(HANDLE ParentHandle, PKSNODE_CREATE NodeCreate,
-			 ACCESS_MASK DesiredAccess, PHANDLE NodeHandle);
-
-KSDDKAPI NTSTATUS NTAPI KsValidateTopologyNodeCreateRequest
-			(PIRP Irp, PKSTOPOLOGY Topology, PKSNODE_CREATE *NodeCreate);
-
-KSDDKAPI NTSTATUS NTAPI KsMergeAutomationTables
-			(PKSAUTOMATION_TABLE *AutomationTableAB,
-			 PKSAUTOMATION_TABLE AutomationTableA,
-			 PKSAUTOMATION_TABLE AutomationTableB,
-			 KSOBJECT_BAG Bag);
-
-KSDDKAPI NTSTATUS NTAPI KsInitializeDriver
-			(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPathName,
-			 const KSDEVICE_DESCRIPTOR *Descriptor);
-
-KSDDKAPI NTSTATUS NTAPI KsAddDevice
-			(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT PhysicalDeviceObject);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateDevice
-			(PDRIVER_OBJECT DriverObject, PDEVICE_OBJECT PhysicalDeviceObject,
-			 const KSDEVICE_DESCRIPTOR *Descriptor, ULONG ExtensionSize,
-			 PKSDEVICE *Device);
-
-KSDDKAPI NTSTATUS NTAPI KsInitializeDevice
-			(PDEVICE_OBJECT FunctionalDeviceObject,
-			 PDEVICE_OBJECT PhysicalDeviceObject,
-			 PDEVICE_OBJECT NextDeviceObject,
-			 const KSDEVICE_DESCRIPTOR *Descriptor);
-
-KSDDKAPI void NTAPI KsTerminateDevice (PDEVICE_OBJECT DeviceObject);
-KSDDKAPI PKSDEVICE NTAPI KsGetDeviceForDeviceObject (PDEVICE_OBJECT FunctionalDeviceObject);
-KSDDKAPI void NTAPI KsAcquireDevice (PKSDEVICE Device);
-KSDDKAPI void NTAPI KsReleaseDevice (PKSDEVICE Device);
-
-KSDDKAPI void NTAPI KsDeviceRegisterAdapterObject
-			(PKSDEVICE Device, PADAPTER_OBJECT AdapterObject,
-			 ULONG MaxMappingsByteCount, ULONG MappingTableStride);
-
-KSDDKAPI ULONG NTAPI KsDeviceGetBusData
-			(PKSDEVICE Device, ULONG DataType, PVOID Buffer, ULONG Offset,
-			 ULONG Length);
-
-KSDDKAPI ULONG NTAPI KsDeviceSetBusData
-			(PKSDEVICE Device, ULONG DataType, PVOID Buffer, ULONG Offset,
-			 ULONG Length);
-
-KSDDKAPI NTSTATUS NTAPI KsCreateFilterFactory
-			(PDEVICE_OBJECT DeviceObject, const KSFILTER_DESCRIPTOR *Descriptor,
-			 PWSTR RefString, PSECURITY_DESCRIPTOR SecurityDescriptor,
-			 ULONG CreateItemFlags, PFNKSFILTERFACTORYPOWER SleepCallback,
-			 PFNKSFILTERFACTORYPOWER WakeCallback,
-			 PKSFILTERFACTORY *FilterFactory);
-
-#define KsDeleteFilterFactory(FilterFactory)												\
-	KsFreeObjectCreateItemsByContext( *(KSDEVICE_HEADER *)(										\
-						KsFilterFactoryGetParentDevice(FilterFactory)->FunctionalDeviceObject->DeviceExtension),\
-					   FilterFactory)
-
-KSDDKAPI NTSTATUS NTAPI KsFilterFactoryUpdateCacheData
-			(PKSFILTERFACTORY FilterFactory,
-			 const KSFILTER_DESCRIPTOR *FilterDescriptor);
-
-KSDDKAPI NTSTATUS NTAPI KsFilterFactoryAddCreateItem
-			(PKSFILTERFACTORY FilterFactory, PWSTR RefString,
-			 PSECURITY_DESCRIPTOR SecurityDescriptor, ULONG CreateItemFlags);
-
-KSDDKAPI NTSTATUS NTAPI KsFilterFactorySetDeviceClassesState
-			(PKSFILTERFACTORY FilterFactory, BOOLEAN NewState);
-
-KSDDKAPI PUNICODE_STRING NTAPI KsFilterFactoryGetSymbolicLink
-			(PKSFILTERFACTORY FilterFactory);
-
-KSDDKAPI void NTAPI KsAddEvent(PVOID Object, PKSEVENT_ENTRY EventEntry);
-
-void __forceinline KsFilterAddEvent (PKSFILTER Filter, PKSEVENT_ENTRY EventEntry)
-{
-	KsAddEvent(Filter, EventEntry);
-}
-
-void __forceinline KsPinAddEvent (PKSPIN Pin, PKSEVENT_ENTRY EventEntry)
-{
-	KsAddEvent(Pin, EventEntry);
-}
-
-KSDDKAPI NTSTATUS NTAPI KsDefaultAddEventHandler
-			(PIRP Irp, PKSEVENTDATA EventData, PKSEVENT_ENTRY EventEntry);
-
-KSDDKAPI void NTAPI KsGenerateEvents
-			(PVOID Object, const GUID *EventSet, ULONG EventId,
-			 ULONG DataSize, PVOID Data, PFNKSGENERATEEVENTCALLBACK CallBack,
-			 PVOID CallBackContext);
-
-void __forceinline KsFilterGenerateEvents
-			(PKSFILTER Filter, const GUID *EventSet, ULONG EventId,
-			 ULONG DataSize, PVOID Data, PFNKSGENERATEEVENTCALLBACK CallBack,
-			 PVOID CallBackContext)
-{
-	KsGenerateEvents(Filter, EventSet, EventId, DataSize, Data, CallBack,
-			 CallBackContext);
-}
-
-void __forceinline KsPinGenerateEvents
-			(PKSPIN Pin, const GUID *EventSet, ULONG EventId,
-			 ULONG DataSize, PVOID Data, PFNKSGENERATEEVENTCALLBACK CallBack,
-			 PVOID CallBackContext)
-{
-	KsGenerateEvents(Pin, EventSet, EventId, DataSize, Data, CallBack,
-			 CallBackContext);
-}
-
-typedef enum {
-  KSSTREAM_POINTER_STATE_UNLOCKED = 0,
-  KSSTREAM_POINTER_STATE_LOCKED
-} KSSTREAM_POINTER_STATE;
-
-KSDDKAPI NTSTATUS NTAPI KsPinGetAvailableByteCount
-			(PKSPIN Pin, PLONG InputDataBytes, PLONG OutputBufferBytes);
-
-KSDDKAPI PKSSTREAM_POINTER NTAPI KsPinGetLeadingEdgeStreamPointer
-			(PKSPIN Pin, KSSTREAM_POINTER_STATE State);
-
-KSDDKAPI PKSSTREAM_POINTER NTAPI KsPinGetTrailingEdgeStreamPointer
-			(PKSPIN Pin, KSSTREAM_POINTER_STATE State);
-
-KSDDKAPI NTSTATUS NTAPI KsStreamPointerSetStatusCode
-			(PKSSTREAM_POINTER StreamPointer, NTSTATUS Status);
-
-KSDDKAPI NTSTATUS NTAPI KsStreamPointerLock (PKSSTREAM_POINTER StreamPointer);
-KSDDKAPI void NTAPI KsStreamPointerUnlock(PKSSTREAM_POINTER StreamPointer, BOOLEAN Eject);
-
-KSDDKAPI void NTAPI KsStreamPointerAdvanceOffsetsAndUnlock
-			(PKSSTREAM_POINTER StreamPointer, ULONG InUsed, ULONG OutUsed,
-			 BOOLEAN Eject);
-
-KSDDKAPI void NTAPI KsStreamPointerDelete (PKSSTREAM_POINTER StreamPointer);
-
-KSDDKAPI NTSTATUS NTAPI KsStreamPointerClone
-			(PKSSTREAM_POINTER StreamPointer, PFNKSSTREAMPOINTER CancelCallback,
-			 ULONG ContextSize, PKSSTREAM_POINTER *CloneStreamPointer);
-
-KSDDKAPI NTSTATUS NTAPI KsStreamPointerAdvanceOffsets
-			(PKSSTREAM_POINTER StreamPointer, ULONG InUsed, ULONG OutUsed,
-			 BOOLEAN Eject);
-
-KSDDKAPI NTSTATUS NTAPI KsStreamPointerAdvance (PKSSTREAM_POINTER StreamPointer);
-KSDDKAPI PMDL NTAPI KsStreamPointerGetMdl (PKSSTREAM_POINTER StreamPointer);
-
-KSDDKAPI PIRP NTAPI KsStreamPointerGetIrp
-			(PKSSTREAM_POINTER StreamPointer, PBOOLEAN FirstFrameInIrp,
-			 PBOOLEAN LastFrameInIrp);
-
-KSDDKAPI void NTAPI KsStreamPointerScheduleTimeout
-			(PKSSTREAM_POINTER StreamPointer, PFNKSSTREAMPOINTER Callback,
-			 ULONGLONG Interval);
-
-KSDDKAPI void NTAPI KsStreamPointerCancelTimeout (PKSSTREAM_POINTER StreamPointer);
-KSDDKAPI PKSSTREAM_POINTER NTAPI KsPinGetFirstCloneStreamPointer (PKSPIN Pin);
-
-KSDDKAPI PKSSTREAM_POINTER NTAPI KsStreamPointerGetNextClone
-			(PKSSTREAM_POINTER StreamPointer);
-
-KSDDKAPI NTSTATUS NTAPI KsPinHandshake(PKSPIN Pin, PKSHANDSHAKE In, PKSHANDSHAKE Out);
-KSDDKAPI void NTAPI KsCompletePendingRequest (PIRP Irp);
-KSDDKAPI KSOBJECTTYPE NTAPI KsGetObjectTypeFromIrp (PIRP Irp);
-KSDDKAPI PVOID NTAPI KsGetObjectFromFileObject (PFILE_OBJECT FileObject);
-KSDDKAPI KSOBJECTTYPE NTAPI KsGetObjectTypeFromFileObject (PFILE_OBJECT FileObject);
-
-PKSFILTER __forceinline KsGetFilterFromFileObject (PFILE_OBJECT FileObject)
-{
-	return (PKSFILTER) KsGetObjectFromFileObject(FileObject);
-}
-
-PKSPIN __forceinline KsGetPinFromFileObject (PFILE_OBJECT FileObject)
-{
-	return (PKSPIN) KsGetObjectFromFileObject(FileObject);
-}
-
-KSDDKAPI PKSGATE NTAPI KsFilterGetAndGate (PKSFILTER Filter);
-KSDDKAPI void NTAPI KsFilterAcquireProcessingMutex (PKSFILTER Filter);
-KSDDKAPI void NTAPI KsFilterReleaseProcessingMutex (PKSFILTER Filter);
-KSDDKAPI void NTAPI KsFilterAttemptProcessing(PKSFILTER Filter, BOOLEAN Asynchronous);
-KSDDKAPI PKSGATE NTAPI KsPinGetAndGate(PKSPIN Pin);
-KSDDKAPI void NTAPI KsPinAttachAndGate(PKSPIN Pin, PKSGATE AndGate);
-KSDDKAPI void NTAPI KsPinAttachOrGate (PKSPIN Pin, PKSGATE OrGate);
-KSDDKAPI void NTAPI KsPinAcquireProcessingMutex (PKSPIN Pin);
-KSDDKAPI void NTAPI KsPinReleaseProcessingMutex (PKSPIN Pin);
-KSDDKAPI BOOLEAN NTAPI KsProcessPinUpdate (PKSPROCESSPIN ProcessPin);
-
-KSDDKAPI void NTAPI KsPinGetCopyRelationships
-			(PKSPIN Pin, PKSPIN *CopySource, PKSPIN *DelegateBranch);
-
-KSDDKAPI void NTAPI KsPinAttemptProcessing(PKSPIN Pin, BOOLEAN Asynchronous);
-KSDDKAPI PVOID NTAPI KsGetParent (PVOID Object);
-
-PKSDEVICE __forceinline KsFilterFactoryGetParentDevice (PKSFILTERFACTORY FilterFactory)
-{
-	return (PKSDEVICE) KsGetParent((PVOID) FilterFactory);
-}
-
-PKSFILTERFACTORY __forceinline KsFilterGetParentFilterFactory (PKSFILTER Filter)
-{
-	return (PKSFILTERFACTORY) KsGetParent((PVOID) Filter);
-}
-
-KSDDKAPI PKSFILTER NTAPI KsPinGetParentFilter (PKSPIN Pin);
-KSDDKAPI PVOID NTAPI KsGetFirstChild (PVOID Object);
-
-PKSFILTERFACTORY __forceinline KsDeviceGetFirstChildFilterFactory (PKSDEVICE Device)
-{
-	return (PKSFILTERFACTORY) KsGetFirstChild((PVOID) Device);
-}
-
-PKSFILTER __forceinline KsFilterFactoryGetFirstChildFilter (PKSFILTERFACTORY FilterFactory)
-{
-	return (PKSFILTER) KsGetFirstChild((PVOID) FilterFactory);
-}
-
-KSDDKAPI ULONG NTAPI KsFilterGetChildPinCount(PKSFILTER Filter, ULONG PinId);
-KSDDKAPI PKSPIN NTAPI KsFilterGetFirstChildPin(PKSFILTER Filter, ULONG PinId);
-KSDDKAPI PVOID NTAPI KsGetNextSibling (PVOID Object);
-KSDDKAPI PKSPIN NTAPI KsPinGetNextSiblingPin (PKSPIN Pin);
-
-PKSFILTERFACTORY __forceinline KsFilterFactoryGetNextSiblingFilterFactory
-			(PKSFILTERFACTORY FilterFactory)
-{
-	return (PKSFILTERFACTORY) KsGetNextSibling((PVOID) FilterFactory);
-}
-
-PKSFILTER __forceinline KsFilterGetNextSiblingFilter (PKSFILTER Filter)
-{
-	return (PKSFILTER) KsGetNextSibling((PVOID) Filter);
-}
-
-KSDDKAPI PKSDEVICE NTAPI KsGetDevice (PVOID Object);
-
-PKSDEVICE __forceinline KsFilterFactoryGetDevice (PKSFILTERFACTORY FilterFactory)
-{
-	return KsGetDevice((PVOID) FilterFactory);
-}
-
-PKSDEVICE __forceinline KsFilterGetDevice (PKSFILTER Filter)
-{
-	return KsGetDevice((PVOID) Filter);
-}
-
-PKSDEVICE __forceinline KsPinGetDevice (PKSPIN Pin)
-{
-	return KsGetDevice((PVOID) Pin);
-}
-
-KSDDKAPI PKSFILTER NTAPI KsGetFilterFromIrp (PIRP Irp);
-KSDDKAPI PKSPIN NTAPI KsGetPinFromIrp (PIRP Irp);
-KSDDKAPI ULONG NTAPI KsGetNodeIdFromIrp (PIRP Irp);
-KSDDKAPI void NTAPI KsAcquireControl (PVOID Object);
-KSDDKAPI void NTAPI KsReleaseControl (PVOID Object);
-
-void __forceinline KsFilterAcquireControl (PKSFILTER Filter)
-{
-	KsAcquireControl((PVOID) Filter);
-}
-
-void __forceinline KsFilterReleaseControl (PKSFILTER Filter)
-{
-	KsReleaseControl((PVOID) Filter);
-}
-
-void __forceinline KsPinAcquireControl (PKSPIN Pin)
-{
-	KsAcquireControl((PVOID) Pin);
-}
-
-void __forceinline KsPinReleaseControl (PKSPIN Pin)
-{
-	KsReleaseControl((PVOID) Pin);
-}
-
-KSDDKAPI NTSTATUS NTAPI KsAddItemToObjectBag
-			(KSOBJECT_BAG ObjectBag, PVOID Item, PFNKSFREE Free);
-
-KSDDKAPI ULONG NTAPI KsRemoveItemFromObjectBag
-			(KSOBJECT_BAG ObjectBag, PVOID Item, BOOLEAN Free);
-
-#define KsDiscard(Object,Pointer)					\
-	KsRemoveItemFromObjectBag((Object)->Bag, (PVOID)(Pointer), TRUE)
-
-KSDDKAPI NTSTATUS NTAPI KsAllocateObjectBag(PKSDEVICE Device, KSOBJECT_BAG *ObjectBag);
-KSDDKAPI void NTAPI KsFreeObjectBag (KSOBJECT_BAG ObjectBag);
-
-KSDDKAPI NTSTATUS NTAPI KsCopyObjectBagItems
-			(KSOBJECT_BAG ObjectBagDestination, KSOBJECT_BAG ObjectBagSource);
-
-KSDDKAPI NTSTATUS NTAPI _KsEdit
-			(KSOBJECT_BAG ObjectBag, PVOID *PointerToPointerToItem,
-			 ULONG NewSize, ULONG OldSize, ULONG Tag);
-
-#define KsEdit(Object, PointerToPointer, Tag)						\
-	_KsEdit((Object)->Bag, (PVOID*)(PointerToPointer),				\
-		sizeof(**(PointerToPointer)), sizeof(**(PointerToPointer)), (Tag))
-
-#define KsEditSized(Object, PointerToPointer, NewSize, OldSize, Tag)			\
-	_KsEdit((Object)->Bag, (PVOID*)(PointerToPointer), (NewSize), (OldSize), (Tag))
-
-KSDDKAPI NTSTATUS NTAPI KsRegisterFilterWithNoKSPins
-			(PDEVICE_OBJECT DeviceObject, const GUID *InterfaceClassGUID,
-			 ULONG PinCount, WINBOOL *PinDirection, KSPIN_MEDIUM *MediumList,
-			 GUID *CategoryList);
-
-KSDDKAPI NTSTATUS NTAPI KsFilterCreatePinFactory
-			(PKSFILTER Filter, const KSPIN_DESCRIPTOR_EX *const PinDescriptor,
-			 PULONG PinID);
-
-KSDDKAPI NTSTATUS NTAPI KsFilterCreateNode
-			(PKSFILTER Filter, const KSNODE_DESCRIPTOR *const NodeDescriptor,
-			 PULONG NodeID);
-
-KSDDKAPI NTSTATUS NTAPI KsFilterAddTopologyConnections
-			(PKSFILTER Filter, ULONG NewConnectionsCount,
-			 const KSTOPOLOGY_CONNECTION *const NewTopologyConnections);
-
-KSDDKAPI NTSTATUS NTAPI KsPinGetConnectedPinInterface
-			(PKSPIN Pin, const GUID *InterfaceId, PVOID *Interface);
-
-KSDDKAPI PFILE_OBJECT NTAPI KsPinGetConnectedPinFileObject (PKSPIN Pin);
-KSDDKAPI PDEVICE_OBJECT NTAPI KsPinGetConnectedPinDeviceObject (PKSPIN Pin);
-
-KSDDKAPI NTSTATUS NTAPI KsPinGetConnectedFilterInterface
-			(PKSPIN Pin, const GUID *InterfaceId, PVOID *Interface);
-
-#if defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__)
-KSDDKAPI NTSTATUS NTAPI KsPinGetReferenceClockInterface
-			(PKSPIN Pin, PIKSREFERENCECLOCK *Interface);
-#endif /* defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__) */
-
-KSDDKAPI VOID NTAPI KsPinSetPinClockTime(PKSPIN Pin, LONGLONG Time);
-
-KSDDKAPI NTSTATUS NTAPI KsPinSubmitFrame
-			(PKSPIN Pin, PVOID Data, ULONG Size,
-			 PKSSTREAM_HEADER StreamHeader, PVOID Context);
-
-KSDDKAPI NTSTATUS NTAPI KsPinSubmitFrameMdl
-			(PKSPIN Pin, PMDL Mdl, PKSSTREAM_HEADER StreamHeader,
-			 PVOID Context);
-
-KSDDKAPI void NTAPI KsPinRegisterFrameReturnCallback
-			(PKSPIN Pin, PFNKSPINFRAMERETURN FrameReturn);
-
-KSDDKAPI void NTAPI KsPinRegisterIrpCompletionCallback
-			(PKSPIN Pin, PFNKSPINIRPCOMPLETION IrpCompletion);
-
-KSDDKAPI void NTAPI KsPinRegisterHandshakeCallback
-			(PKSPIN Pin, PFNKSPINHANDSHAKE Handshake);
-
-KSDDKAPI void NTAPI KsFilterRegisterPowerCallbacks
-			(PKSFILTER Filter, PFNKSFILTERPOWER Sleep, PFNKSFILTERPOWER Wake);
-
-KSDDKAPI void NTAPI KsPinRegisterPowerCallbacks
-			(PKSPIN Pin, PFNKSPINPOWER Sleep, PFNKSPINPOWER Wake);
-
-#if defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__)
-KSDDKAPI PUNKNOWN NTAPI KsRegisterAggregatedClientUnknown
-			(PVOID Object, PUNKNOWN ClientUnknown);
-
-KSDDKAPI PUNKNOWN NTAPI KsGetOuterUnknown (PVOID Object);
-
-PUNKNOWN __forceinline KsDeviceRegisterAggregatedClientUnknown
-			(PKSDEVICE Device, PUNKNOWN ClientUnknown)
-{
-	return KsRegisterAggregatedClientUnknown((PVOID)Device, ClientUnknown);
-}
-
-PUNKNOWN __forceinline KsDeviceGetOuterUnknown (PKSDEVICE Device)
-{
-	return KsGetOuterUnknown((PVOID) Device);
-}
-
-PUNKNOWN __forceinline KsFilterFactoryRegisterAggregatedClientUnknown
-			(PKSFILTERFACTORY FilterFactory, PUNKNOWN ClientUnknown)
-{
-	return KsRegisterAggregatedClientUnknown((PVOID)FilterFactory, ClientUnknown);
-}
-
-PUNKNOWN __forceinline KsFilterFactoryGetOuterUnknown (PKSFILTERFACTORY FilterFactory)
-{
-	return KsGetOuterUnknown((PVOID)FilterFactory);
-}
-
-PUNKNOWN __forceinline KsFilterRegisterAggregatedClientUnknown
-			(PKSFILTER Filter, PUNKNOWN ClientUnknown)
-{
-	return KsRegisterAggregatedClientUnknown((PVOID)Filter, ClientUnknown);
-}
-
-PUNKNOWN __forceinline KsFilterGetOuterUnknown (PKSFILTER Filter)
-{
-	return KsGetOuterUnknown((PVOID)Filter);
-}
-
-PUNKNOWN __forceinline KsPinRegisterAggregatedClientUnknown
-			(PKSPIN Pin, PUNKNOWN ClientUnknown)
-{
-	return KsRegisterAggregatedClientUnknown((PVOID)Pin, ClientUnknown);
-}
-
-PUNKNOWN __forceinline KsPinGetOuterUnknown (PKSPIN Pin)
-{
-	return KsGetOuterUnknown((PVOID)Pin);
-}
-#endif /* defined(_UNKNOWN_H_) || defined(__IUnknown_INTERFACE_DEFINED__) */
-
-#else /* _NTDDK_ */
-
-#ifndef KS_NO_CREATE_FUNCTIONS
-KSDDKAPI DWORD WINAPI KsCreateAllocator(HANDLE ConnectionHandle,PKSALLOCATOR_FRAMING AllocatorFraming,PHANDLE AllocatorHandle);
-KSDDKAPI DWORD NTAPI KsCreateClock(HANDLE ConnectionHandle,PKSCLOCK_CREATE ClockCreate,PHANDLE ClockHandle);
-KSDDKAPI DWORD WINAPI KsCreatePin(HANDLE FilterHandle,PKSPIN_CONNECT Connect,ACCESS_MASK DesiredAccess,PHANDLE ConnectionHandle);
-KSDDKAPI DWORD WINAPI KsCreateTopologyNode(HANDLE ParentHandle,PKSNODE_CREATE NodeCreate,ACCESS_MASK DesiredAccess,PHANDLE NodeHandle);
-#endif
-
-#endif /* _NTDDK_ */
-
-#ifdef __cplusplus
-}
-#endif
-
-#define DENY_USERMODE_ACCESS(pIrp,CompleteRequest)			\
-	if(pIrp->RequestorMode!=KernelMode) {				\
-		pIrp->IoStatus.Information = 0;				\
-		pIrp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;	\
-		if(CompleteRequest)					\
-			IoCompleteRequest (pIrp,IO_NO_INCREMENT);	\
-		return STATUS_INVALID_DEVICE_REQUEST;			\
-	}
-
-#endif /* _KS_ */
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ksguid.h b/portaudio/src/hostapi/wasapi/mingw-include/ksguid.h
deleted file mode 100644
index f0774d06c..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/ksguid.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * This file has no copyright assigned and is placed in the Public Domain.
- * This file is part of the w64 mingw-runtime package.
- * No warranty is given; refer to the file DISCLAIMER.PD within this package.
- */
-#define INITGUID
-#include <guiddef.h>
-
-#ifndef DECLSPEC_SELECTANY
-#define DECLSPEC_SELECTANY __declspec(selectany)
-#endif
-
-#ifdef DEFINE_GUIDEX
-#undef DEFINE_GUIDEX
-#endif
-
-#ifdef __cplusplus
-#define DEFINE_GUIDEX(name) EXTERN_C const CDECL GUID DECLSPEC_SELECTANY name = { STATICGUIDOF(name) }
-#else
-#define DEFINE_GUIDEX(name) const CDECL GUID DECLSPEC_SELECTANY name = { STATICGUIDOF(name) }
-#endif
-#ifndef STATICGUIDOF
-#define STATICGUIDOF(guid) STATIC_##guid
-#endif
-
-#ifndef DEFINE_WAVEFORMATEX_GUID
-#define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x),0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-#endif
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h b/portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h
deleted file mode 100644
index 2242c1e03..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/ksmedia.h
+++ /dev/null
@@ -1,4551 +0,0 @@
-/**
- * This file has no copyright assigned and is placed in the Public Domain.
- * This file is part of the w64 mingw-runtime package.
- * No warranty is given; refer to the file DISCLAIMER.PD within this package.
- */
-#if !defined(_KS_)
-#warning ks.h must be included before ksmedia.h
-#include "ks.h"
-#endif
-
-#if __GNUC__ >= 3
-#pragma GCC system_header
-#endif
-
-#if !defined(_KSMEDIA_)
-#define _KSMEDIA_
-
-typedef struct {
-  KSPROPERTY Property;
-  KSMULTIPLE_ITEM MultipleItem;
-} KSMULTIPLE_DATA_PROP,*PKSMULTIPLE_DATA_PROP;
-
-#define STATIC_KSMEDIUMSETID_MidiBus					\
-	0x05908040L,0x3246,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("05908040-3246-11D0-A5D6-28DB04C10000",KSMEDIUMSETID_MidiBus);
-#define KSMEDIUMSETID_MidiBus DEFINE_GUIDNAMED(KSMEDIUMSETID_MidiBus)
-
-#define STATIC_KSMEDIUMSETID_VPBus					\
-	0xA18C15ECL,0xCE43,0x11D0,0xAB,0xE7,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("A18C15EC-CE43-11D0-ABE7-00A0C9223196",KSMEDIUMSETID_VPBus);
-#define KSMEDIUMSETID_VPBus DEFINE_GUIDNAMED(KSMEDIUMSETID_VPBus)
-
-#define STATIC_KSINTERFACESETID_Media					\
-	0x3A13EB40L,0x30A7,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("3A13EB40-30A7-11D0-A5D6-28DB04C10000",KSINTERFACESETID_Media);
-#define KSINTERFACESETID_Media DEFINE_GUIDNAMED(KSINTERFACESETID_Media)
-
-typedef enum {
-  KSINTERFACE_MEDIA_MUSIC,
-  KSINTERFACE_MEDIA_WAVE_BUFFERED,
-  KSINTERFACE_MEDIA_WAVE_QUEUED
-} KSINTERFACE_MEDIA;
-
-#ifndef INIT_USBAUDIO_MID
-#define INIT_USBAUDIO_MID(guid,id)					\
-{									\
-	(guid)->Data1 = 0x4e1cecd2 + (USHORT)(id);			\
-	(guid)->Data2 = 0x1679;						\
-	(guid)->Data3 = 0x463b;						\
-	(guid)->Data4[0] = 0xa7;					\
-	(guid)->Data4[1] = 0x2f;					\
-	(guid)->Data4[2] = 0xa5;					\
-	(guid)->Data4[3] = 0xbf;					\
-	(guid)->Data4[4] = 0x64;					\
-	(guid)->Data4[5] = 0xc8;					\
-	(guid)->Data4[6] = 0x6e;					\
-	(guid)->Data4[7] = 0xba;					\
-}
-#define EXTRACT_USBAUDIO_MID(guid)					\
-	(USHORT)((guid)->Data1 - 0x4e1cecd2)
-#define DEFINE_USBAUDIO_MID_GUID(id)					\
-	0x4e1cecd2+(USHORT)(id),0x1679,0x463b,0xa7,0x2f,0xa5,0xbf,0x64,0xc8,0x6e,0xba
-#define IS_COMPATIBLE_USBAUDIO_MID(guid)				\
-	(((guid)->Data1 >= 0x4e1cecd2) &&				\
-	 ((guid)->Data1 < 0x4e1cecd2 + 0xffff) &&			\
-	 ((guid)->Data2 == 0x1679) &&					\
-	 ((guid)->Data3 == 0x463b) &&					\
-	 ((guid)->Data4[0] == 0xa7) &&					\
-	 ((guid)->Data4[1] == 0x2f) &&					\
-	 ((guid)->Data4[2] == 0xa5) &&					\
-	 ((guid)->Data4[3] == 0xbf) &&					\
-	 ((guid)->Data4[4] == 0x64) &&					\
-	 ((guid)->Data4[5] == 0xc8) &&					\
-	 ((guid)->Data4[6] == 0x6e) &&					\
-	 ((guid)->Data4[7] == 0xba) )
-#endif /* INIT_USBAUDIO_MID */
-
-#ifndef INIT_USBAUDIO_PID
-#define INIT_USBAUDIO_PID(guid,id)					\
-{									\
-	(guid)->Data1 = 0xabcc5a5e + (USHORT)(id);			\
-	(guid)->Data2 = 0xc263;						\
-	(guid)->Data3 = 0x463b;						\
-	(guid)->Data4[0] = 0xa7;					\
-	(guid)->Data4[1] = 0x2f;					\
-	(guid)->Data4[2] = 0xa5;					\
-	(guid)->Data4[3] = 0xbf;					\
-	(guid)->Data4[4] = 0x64;					\
-	(guid)->Data4[5] = 0xc8;					\
-	(guid)->Data4[6] = 0x6e;					\
-	(guid)->Data4[7] = 0xba;					\
-}
-#define EXTRACT_USBAUDIO_PID(guid)					\
-	(USHORT)((guid)->Data1 - 0xabcc5a5e)
-#define DEFINE_USBAUDIO_PID_GUID(id)					\
-	0xabcc5a5e+(USHORT)(id),0xc263,0x463b,0xa7,0x2f,0xa5,0xbf,0x64,0xc8,0x6e,0xba
-#define IS_COMPATIBLE_USBAUDIO_PID(guid)				\
-	(((guid)->Data1 >= 0xabcc5a5e) &&				\
-	 ((guid)->Data1 < 0xabcc5a5e + 0xffff) &&			\
-	 ((guid)->Data2 == 0xc263) &&					\
-	 ((guid)->Data3 == 0x463b) &&					\
-	 ((guid)->Data4[0] == 0xa7) &&					\
-	 ((guid)->Data4[1] == 0x2f) &&					\
-	 ((guid)->Data4[2] == 0xa5) &&					\
-	 ((guid)->Data4[3] == 0xbf) &&					\
-	 ((guid)->Data4[4] == 0x64) &&					\
-	 ((guid)->Data4[5] == 0xc8) &&					\
-	 ((guid)->Data4[6] == 0x6e) &&					\
-	 ((guid)->Data4[7] == 0xba) )
-#endif /* INIT_USBAUDIO_PID */
-
-#ifndef INIT_USBAUDIO_PRODUCT_NAME
-#define INIT_USBAUDIO_PRODUCT_NAME(guid,vid,pid,strIndex)		\
-{									\
-	(guid)->Data1 = 0XFC575048 + (USHORT)(vid);			\
-	(guid)->Data2 = 0x2E08 + (USHORT)(pid);				\
-	(guid)->Data3 = 0x463B + (USHORT)(strIndex);			\
-	(guid)->Data4[0] = 0xA7;					\
-	(guid)->Data4[1] = 0x2F;					\
-	(guid)->Data4[2] = 0xA5;					\
-	(guid)->Data4[3] = 0xBF;					\
-	(guid)->Data4[4] = 0x64;					\
-	(guid)->Data4[5] = 0xC8;					\
-	(guid)->Data4[6] = 0x6E;					\
-	(guid)->Data4[7] = 0xBA;					\
-}
-#define DEFINE_USBAUDIO_PRODUCT_NAME(vid,pid,strIndex)			\
-	0xFC575048+(USHORT)(vid),0x2E08+(USHORT)(pid),0x463B+(USHORT)(strIndex),0xA7,0x2F,0xA5,0xBF,0x64,0xC8,0x6E,0xBA
-#endif /* INIT_USBAUDIO_PRODUCT_NAME */
-
-#define STATIC_KSCOMPONENTID_USBAUDIO					\
-	0x8F1275F0,0x26E9,0x4264,0xBA,0x4D,0x39,0xFF,0xF0,0x1D,0x94,0xAA
-DEFINE_GUIDSTRUCT("8F1275F0-26E9-4264-BA4D-39FFF01D94AA",KSCOMPONENTID_USBAUDIO);
-#define KSCOMPONENTID_USBAUDIO DEFINE_GUIDNAMED(KSCOMPONENTID_USBAUDIO)
-
-#define INIT_USB_TERMINAL(guid,id)					\
-{									\
-	(guid)->Data1 = 0xDFF219E0 + (USHORT)(id);			\
-	(guid)->Data2 = 0xF70F;						\
-	(guid)->Data3 = 0x11D0;						\
-	(guid)->Data4[0] = 0xb9;					\
-	(guid)->Data4[1] = 0x17;					\
-	(guid)->Data4[2] = 0x00;					\
-	(guid)->Data4[3] = 0xa0;					\
-	(guid)->Data4[4] = 0xc9;					\
-	(guid)->Data4[5] = 0x22;					\
-	(guid)->Data4[6] = 0x31;					\
-	(guid)->Data4[7] = 0x96;					\
-}
-#define EXTRACT_USB_TERMINAL(guid)					\
-	(USHORT)((guid)->Data1 - 0xDFF219E0)
-#define DEFINE_USB_TERMINAL_GUID(id)					\
-	0xDFF219E0+(USHORT)(id),0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#define STATIC_KSNODETYPE_MICROPHONE					\
-	DEFINE_USB_TERMINAL_GUID(0x0201)
-DEFINE_GUIDSTRUCT("DFF21BE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MICROPHONE);
-#define KSNODETYPE_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_MICROPHONE)
-
-#define STATIC_KSNODETYPE_DESKTOP_MICROPHONE				\
-	DEFINE_USB_TERMINAL_GUID(0x0202)
-DEFINE_GUIDSTRUCT("DFF21BE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DESKTOP_MICROPHONE);
-#define KSNODETYPE_DESKTOP_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_DESKTOP_MICROPHONE)
-
-#define STATIC_KSNODETYPE_PERSONAL_MICROPHONE				\
-	DEFINE_USB_TERMINAL_GUID(0x0203)
-DEFINE_GUIDSTRUCT("DFF21BE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PERSONAL_MICROPHONE);
-#define KSNODETYPE_PERSONAL_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_PERSONAL_MICROPHONE)
-
-#define STATIC_KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE			\
-	DEFINE_USB_TERMINAL_GUID(0x0204)
-DEFINE_GUIDSTRUCT("DFF21BE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE);
-#define KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE DEFINE_GUIDNAMED(KSNODETYPE_OMNI_DIRECTIONAL_MICROPHONE)
-
-#define STATIC_KSNODETYPE_MICROPHONE_ARRAY				\
-	DEFINE_USB_TERMINAL_GUID(0x0205)
-DEFINE_GUIDSTRUCT("DFF21BE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MICROPHONE_ARRAY);
-#define KSNODETYPE_MICROPHONE_ARRAY DEFINE_GUIDNAMED(KSNODETYPE_MICROPHONE_ARRAY)
-
-#define STATIC_KSNODETYPE_PROCESSING_MICROPHONE_ARRAY			\
-	DEFINE_USB_TERMINAL_GUID(0x0206)
-DEFINE_GUIDSTRUCT("DFF21BE6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PROCESSING_MICROPHONE_ARRAY);
-#define KSNODETYPE_PROCESSING_MICROPHONE_ARRAY DEFINE_GUIDNAMED(KSNODETYPE_PROCESSING_MICROPHONE_ARRAY)
-
-#define STATIC_KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR			\
-	0x830a44f2,0xa32d,0x476b,0xbe,0x97,0x42,0x84,0x56,0x73,0xb3,0x5a
-DEFINE_GUIDSTRUCT("830a44f2-a32d-476b-be97-42845673b35a",KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR);
-#define KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR DEFINE_GUIDNAMED(KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR)
-
-#define STATIC_KSNODETYPE_SPEAKER					\
-	DEFINE_USB_TERMINAL_GUID(0x0301)
-DEFINE_GUIDSTRUCT("DFF21CE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SPEAKER);
-#define KSNODETYPE_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_SPEAKER)
-
-#define STATIC_KSNODETYPE_HEADPHONES					\
-	DEFINE_USB_TERMINAL_GUID(0x0302)
-DEFINE_GUIDSTRUCT("DFF21CE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HEADPHONES);
-#define KSNODETYPE_HEADPHONES DEFINE_GUIDNAMED(KSNODETYPE_HEADPHONES)
-
-#define STATIC_KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO			\
-	DEFINE_USB_TERMINAL_GUID(0x0303)
-DEFINE_GUIDSTRUCT("DFF21CE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO);
-#define KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_HEAD_MOUNTED_DISPLAY_AUDIO)
-
-#define STATIC_KSNODETYPE_DESKTOP_SPEAKER				\
-	DEFINE_USB_TERMINAL_GUID(0x0304)
-DEFINE_GUIDSTRUCT("DFF21CE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DESKTOP_SPEAKER);
-#define KSNODETYPE_DESKTOP_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_DESKTOP_SPEAKER)
-
-#define STATIC_KSNODETYPE_ROOM_SPEAKER					\
-	DEFINE_USB_TERMINAL_GUID(0x0305)
-DEFINE_GUIDSTRUCT("DFF21CE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ROOM_SPEAKER);
-#define KSNODETYPE_ROOM_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_ROOM_SPEAKER)
-
-#define STATIC_KSNODETYPE_COMMUNICATION_SPEAKER				\
-	DEFINE_USB_TERMINAL_GUID(0x0306)
-DEFINE_GUIDSTRUCT("DFF21CE6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_COMMUNICATION_SPEAKER);
-#define KSNODETYPE_COMMUNICATION_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_COMMUNICATION_SPEAKER)
-
-#define STATIC_KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER			\
-	DEFINE_USB_TERMINAL_GUID(0x0307)
-DEFINE_GUIDSTRUCT("DFF21CE7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER);
-#define KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER DEFINE_GUIDNAMED(KSNODETYPE_LOW_FREQUENCY_EFFECTS_SPEAKER)
-
-#define STATIC_KSNODETYPE_HANDSET					\
-	DEFINE_USB_TERMINAL_GUID(0x0401)
-DEFINE_GUIDSTRUCT("DFF21DE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HANDSET);
-#define KSNODETYPE_HANDSET DEFINE_GUIDNAMED(KSNODETYPE_HANDSET)
-
-#define STATIC_KSNODETYPE_HEADSET					\
-	DEFINE_USB_TERMINAL_GUID(0x0402)
-DEFINE_GUIDSTRUCT("DFF21DE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_HEADSET);
-#define KSNODETYPE_HEADSET DEFINE_GUIDNAMED(KSNODETYPE_HEADSET)
-
-#define STATIC_KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION		\
-	DEFINE_USB_TERMINAL_GUID(0x0403)
-DEFINE_GUIDSTRUCT("DFF21DE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION);
-#define KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION DEFINE_GUIDNAMED(KSNODETYPE_SPEAKERPHONE_NO_ECHO_REDUCTION)
-
-#define STATIC_KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE			\
-	DEFINE_USB_TERMINAL_GUID(0x0404)
-DEFINE_GUIDSTRUCT("DFF21DE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE);
-#define KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE DEFINE_GUIDNAMED(KSNODETYPE_ECHO_SUPPRESSING_SPEAKERPHONE)
-
-#define STATIC_KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE			\
-	DEFINE_USB_TERMINAL_GUID(0x0405)
-DEFINE_GUIDSTRUCT("DFF21DE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE);
-#define KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE DEFINE_GUIDNAMED(KSNODETYPE_ECHO_CANCELING_SPEAKERPHONE)
-
-#define STATIC_KSNODETYPE_PHONE_LINE					\
-	DEFINE_USB_TERMINAL_GUID(0x0501)
-DEFINE_GUIDSTRUCT("DFF21EE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PHONE_LINE);
-#define KSNODETYPE_PHONE_LINE DEFINE_GUIDNAMED(KSNODETYPE_PHONE_LINE)
-
-#define STATIC_KSNODETYPE_TELEPHONE					\
-	DEFINE_USB_TERMINAL_GUID(0x0502)
-DEFINE_GUIDSTRUCT("DFF21EE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_TELEPHONE);
-#define KSNODETYPE_TELEPHONE DEFINE_GUIDNAMED(KSNODETYPE_TELEPHONE)
-
-#define STATIC_KSNODETYPE_DOWN_LINE_PHONE				\
-	DEFINE_USB_TERMINAL_GUID(0x0503)
-DEFINE_GUIDSTRUCT("DFF21EE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DOWN_LINE_PHONE);
-#define KSNODETYPE_DOWN_LINE_PHONE DEFINE_GUIDNAMED(KSNODETYPE_DOWN_LINE_PHONE)
-
-#define STATIC_KSNODETYPE_ANALOG_CONNECTOR				\
-	DEFINE_USB_TERMINAL_GUID(0x601)
-DEFINE_GUIDSTRUCT("DFF21FE1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ANALOG_CONNECTOR);
-#define KSNODETYPE_ANALOG_CONNECTOR DEFINE_GUIDNAMED(KSNODETYPE_ANALOG_CONNECTOR)
-
-#define STATIC_KSNODETYPE_DIGITAL_AUDIO_INTERFACE			\
-	DEFINE_USB_TERMINAL_GUID(0x0602)
-DEFINE_GUIDSTRUCT("DFF21FE2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DIGITAL_AUDIO_INTERFACE);
-#define KSNODETYPE_DIGITAL_AUDIO_INTERFACE DEFINE_GUIDNAMED(KSNODETYPE_DIGITAL_AUDIO_INTERFACE)
-
-#define STATIC_KSNODETYPE_LINE_CONNECTOR				\
-	DEFINE_USB_TERMINAL_GUID(0x0603)
-DEFINE_GUIDSTRUCT("DFF21FE3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LINE_CONNECTOR);
-#define KSNODETYPE_LINE_CONNECTOR DEFINE_GUIDNAMED(KSNODETYPE_LINE_CONNECTOR)
-
-#define STATIC_KSNODETYPE_LEGACY_AUDIO_CONNECTOR			\
-	DEFINE_USB_TERMINAL_GUID(0x0604)
-DEFINE_GUIDSTRUCT("DFF21FE4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LEGACY_AUDIO_CONNECTOR);
-#define KSNODETYPE_LEGACY_AUDIO_CONNECTOR DEFINE_GUIDNAMED(KSNODETYPE_LEGACY_AUDIO_CONNECTOR)
-
-#define STATIC_KSNODETYPE_SPDIF_INTERFACE				\
-	DEFINE_USB_TERMINAL_GUID(0x0605)
-DEFINE_GUIDSTRUCT("DFF21FE5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SPDIF_INTERFACE);
-#define KSNODETYPE_SPDIF_INTERFACE DEFINE_GUIDNAMED(KSNODETYPE_SPDIF_INTERFACE)
-
-#define STATIC_KSNODETYPE_1394_DA_STREAM				\
-	DEFINE_USB_TERMINAL_GUID(0x0606)
-DEFINE_GUIDSTRUCT("DFF21FE6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_1394_DA_STREAM);
-#define KSNODETYPE_1394_DA_STREAM DEFINE_GUIDNAMED(KSNODETYPE_1394_DA_STREAM)
-
-#define STATIC_KSNODETYPE_1394_DV_STREAM_SOUNDTRACK			\
-	DEFINE_USB_TERMINAL_GUID(0x0607)
-DEFINE_GUIDSTRUCT("DFF21FE7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_1394_DV_STREAM_SOUNDTRACK);
-#define KSNODETYPE_1394_DV_STREAM_SOUNDTRACK DEFINE_GUIDNAMED(KSNODETYPE_1394_DV_STREAM_SOUNDTRACK)
-
-#define STATIC_KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE		\
-	DEFINE_USB_TERMINAL_GUID(0x0701)
-DEFINE_GUIDSTRUCT("DFF220E1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE);
-#define KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE DEFINE_GUIDNAMED(KSNODETYPE_LEVEL_CALIBRATION_NOISE_SOURCE)
-
-#define STATIC_KSNODETYPE_EQUALIZATION_NOISE				\
-	DEFINE_USB_TERMINAL_GUID(0x0702)
-DEFINE_GUIDSTRUCT("DFF220E2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_EQUALIZATION_NOISE);
-#define KSNODETYPE_EQUALIZATION_NOISE DEFINE_GUIDNAMED(KSNODETYPE_EQUALIZATION_NOISE)
-
-#define STATIC_KSNODETYPE_CD_PLAYER					\
-	DEFINE_USB_TERMINAL_GUID(0x0703)
-DEFINE_GUIDSTRUCT("DFF220E3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_CD_PLAYER);
-#define KSNODETYPE_CD_PLAYER DEFINE_GUIDNAMED(KSNODETYPE_CD_PLAYER)
-
-#define STATIC_KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE			\
-	DEFINE_USB_TERMINAL_GUID(0x0704)
-DEFINE_GUIDSTRUCT("DFF220E4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE);
-#define KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE DEFINE_GUIDNAMED(KSNODETYPE_DAT_IO_DIGITAL_AUDIO_TAPE)
-
-#define STATIC_KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE		\
-	DEFINE_USB_TERMINAL_GUID(0x0705)
-DEFINE_GUIDSTRUCT("DFF220E5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE);
-#define KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE DEFINE_GUIDNAMED(KSNODETYPE_DCC_IO_DIGITAL_COMPACT_CASSETTE)
-
-#define STATIC_KSNODETYPE_MINIDISK					\
-	DEFINE_USB_TERMINAL_GUID(0x0706)
-DEFINE_GUIDSTRUCT("DFF220E6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MINIDISK);
-#define KSNODETYPE_MINIDISK DEFINE_GUIDNAMED(KSNODETYPE_MINIDISK)
-
-#define STATIC_KSNODETYPE_ANALOG_TAPE					\
-	DEFINE_USB_TERMINAL_GUID(0x0707)
-DEFINE_GUIDSTRUCT("DFF220E7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_ANALOG_TAPE);
-#define KSNODETYPE_ANALOG_TAPE DEFINE_GUIDNAMED(KSNODETYPE_ANALOG_TAPE)
-
-#define STATIC_KSNODETYPE_PHONOGRAPH					\
-	DEFINE_USB_TERMINAL_GUID(0x0708)
-DEFINE_GUIDSTRUCT("DFF220E8-F70F-11D0-B917-00A0C9223196",KSNODETYPE_PHONOGRAPH);
-#define KSNODETYPE_PHONOGRAPH DEFINE_GUIDNAMED(KSNODETYPE_PHONOGRAPH)
-
-#define STATIC_KSNODETYPE_VCR_AUDIO					\
-	DEFINE_USB_TERMINAL_GUID(0x0708)
-DEFINE_GUIDSTRUCT("DFF220E9-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VCR_AUDIO);
-#define KSNODETYPE_VCR_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_VCR_AUDIO)
-
-#define STATIC_KSNODETYPE_VIDEO_DISC_AUDIO				\
-	DEFINE_USB_TERMINAL_GUID(0x070A)
-DEFINE_GUIDSTRUCT("DFF220EA-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_DISC_AUDIO);
-#define KSNODETYPE_VIDEO_DISC_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_DISC_AUDIO)
-
-#define STATIC_KSNODETYPE_DVD_AUDIO					\
-	DEFINE_USB_TERMINAL_GUID(0x070B)
-DEFINE_GUIDSTRUCT("DFF220EB-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DVD_AUDIO);
-#define KSNODETYPE_DVD_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_DVD_AUDIO)
-
-#define STATIC_KSNODETYPE_TV_TUNER_AUDIO				\
-	DEFINE_USB_TERMINAL_GUID(0x070C)
-DEFINE_GUIDSTRUCT("DFF220EC-F70F-11D0-B917-00A0C9223196",KSNODETYPE_TV_TUNER_AUDIO);
-#define KSNODETYPE_TV_TUNER_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_TV_TUNER_AUDIO)
-
-#define STATIC_KSNODETYPE_SATELLITE_RECEIVER_AUDIO			\
-	DEFINE_USB_TERMINAL_GUID(0x070D)
-DEFINE_GUIDSTRUCT("DFF220ED-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SATELLITE_RECEIVER_AUDIO);
-#define KSNODETYPE_SATELLITE_RECEIVER_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_SATELLITE_RECEIVER_AUDIO)
-
-#define STATIC_KSNODETYPE_CABLE_TUNER_AUDIO				\
-	DEFINE_USB_TERMINAL_GUID(0x070E)
-DEFINE_GUIDSTRUCT("DFF220EE-F70F-11D0-B917-00A0C9223196",KSNODETYPE_CABLE_TUNER_AUDIO);
-#define KSNODETYPE_CABLE_TUNER_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_CABLE_TUNER_AUDIO)
-
-#define STATIC_KSNODETYPE_DSS_AUDIO					\
-	DEFINE_USB_TERMINAL_GUID(0x070F)
-DEFINE_GUIDSTRUCT("DFF220EF-F70F-11D0-B917-00A0C9223196",KSNODETYPE_DSS_AUDIO);
-#define KSNODETYPE_DSS_AUDIO DEFINE_GUIDNAMED(KSNODETYPE_DSS_AUDIO)
-
-#define STATIC_KSNODETYPE_RADIO_RECEIVER				\
-	DEFINE_USB_TERMINAL_GUID(0x0710)
-DEFINE_GUIDSTRUCT("DFF220F0-F70F-11D0-B917-00A0C9223196",KSNODETYPE_RADIO_RECEIVER);
-#define KSNODETYPE_RADIO_RECEIVER DEFINE_GUIDNAMED(KSNODETYPE_RADIO_RECEIVER)
-
-#define STATIC_KSNODETYPE_RADIO_TRANSMITTER				\
-	DEFINE_USB_TERMINAL_GUID(0x0711)
-DEFINE_GUIDSTRUCT("DFF220F1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_RADIO_TRANSMITTER);
-#define KSNODETYPE_RADIO_TRANSMITTER DEFINE_GUIDNAMED(KSNODETYPE_RADIO_TRANSMITTER)
-
-#define STATIC_KSNODETYPE_MULTITRACK_RECORDER				\
-	DEFINE_USB_TERMINAL_GUID(0x0712)
-DEFINE_GUIDSTRUCT("DFF220F2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_MULTITRACK_RECORDER);
-#define KSNODETYPE_MULTITRACK_RECORDER DEFINE_GUIDNAMED(KSNODETYPE_MULTITRACK_RECORDER)
-
-#define STATIC_KSNODETYPE_SYNTHESIZER					\
-	DEFINE_USB_TERMINAL_GUID(0x0713)
-DEFINE_GUIDSTRUCT("DFF220F3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_SYNTHESIZER);
-#define KSNODETYPE_SYNTHESIZER DEFINE_GUIDNAMED(KSNODETYPE_SYNTHESIZER)
-
-#define STATIC_KSNODETYPE_SWSYNTH					\
-	0x423274A0L,0x8B81,0x11D1,0xA0,0x50,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("423274A0-8B81-11D1-A050-0000F8004788",KSNODETYPE_SWSYNTH);
-#define KSNODETYPE_SWSYNTH DEFINE_GUIDNAMED(KSNODETYPE_SWSYNTH)
-
-#define STATIC_KSNODETYPE_SWMIDI					\
-	0xCB9BEFA0L,0xA251,0x11D1,0xA0,0x50,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("CB9BEFA0-A251-11D1-A050-0000F8004788",KSNODETYPE_SWMIDI);
-#define KSNODETYPE_SWMIDI DEFINE_GUIDNAMED(KSNODETYPE_SWMIDI)
-
-#define STATIC_KSNODETYPE_DRM_DESCRAMBLE				\
-	0xFFBB6E3FL,0xCCFE,0x4D84,0x90,0xD9,0x42,0x14,0x18,0xB0,0x3A,0x8E
-DEFINE_GUIDSTRUCT("FFBB6E3F-CCFE-4D84-90D9-421418B03A8E",KSNODETYPE_DRM_DESCRAMBLE);
-#define KSNODETYPE_DRM_DESCRAMBLE DEFINE_GUIDNAMED(KSNODETYPE_DRM_DESCRAMBLE)
-
-#define STATIC_KSCATEGORY_AUDIO						\
-	0x6994AD04L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("6994AD04-93EF-11D0-A3CC-00A0C9223196",KSCATEGORY_AUDIO);
-#define KSCATEGORY_AUDIO DEFINE_GUIDNAMED(KSCATEGORY_AUDIO)
-
-#define STATIC_KSCATEGORY_VIDEO						\
-	0x6994AD05L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("6994AD05-93EF-11D0-A3CC-00A0C9223196",KSCATEGORY_VIDEO);
-#define KSCATEGORY_VIDEO DEFINE_GUIDNAMED(KSCATEGORY_VIDEO)
-
-#define STATIC_KSCATEGORY_TEXT						\
-	0x6994AD06L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("6994AD06-93EF-11D0-A3CC-00A0C9223196",KSCATEGORY_TEXT);
-#define KSCATEGORY_TEXT DEFINE_GUIDNAMED(KSCATEGORY_TEXT)
-
-#define STATIC_KSCATEGORY_NETWORK					\
-	0x67C9CC3CL,0x69C4,0x11D2,0x87,0x59,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("67C9CC3C-69C4-11D2-8759-00A0C9223196",KSCATEGORY_NETWORK);
-#define KSCATEGORY_NETWORK DEFINE_GUIDNAMED(KSCATEGORY_NETWORK)
-
-#define STATIC_KSCATEGORY_TOPOLOGY					\
-	0xDDA54A40L,0x1E4C,0x11D1,0xA0,0x50,0x40,0x57,0x05,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("DDA54A40-1E4C-11D1-A050-405705C10000",KSCATEGORY_TOPOLOGY);
-#define KSCATEGORY_TOPOLOGY DEFINE_GUIDNAMED(KSCATEGORY_TOPOLOGY)
-
-#define STATIC_KSCATEGORY_VIRTUAL					\
-	0x3503EAC4L,0x1F26,0x11D1,0x8A,0xB0,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("3503EAC4-1F26-11D1-8AB0-00A0C9223196",KSCATEGORY_VIRTUAL);
-#define KSCATEGORY_VIRTUAL DEFINE_GUIDNAMED(KSCATEGORY_VIRTUAL)
-
-#define STATIC_KSCATEGORY_ACOUSTIC_ECHO_CANCEL				\
-	0xBF963D80L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("BF963D80-C559-11D0-8A2B-00A0C9255AC1",KSCATEGORY_ACOUSTIC_ECHO_CANCEL);
-#define KSCATEGORY_ACOUSTIC_ECHO_CANCEL DEFINE_GUIDNAMED(KSCATEGORY_ACOUSTIC_ECHO_CANCEL)
-
-#define STATIC_KSCATEGORY_SYSAUDIO					\
-	0xA7C7A5B1L,0x5AF3,0x11D1,0x9C,0xED,0x00,0xA0,0x24,0xBF,0x04,0x07
-DEFINE_GUIDSTRUCT("A7C7A5B1-5AF3-11D1-9CED-00A024BF0407",KSCATEGORY_SYSAUDIO);
-#define KSCATEGORY_SYSAUDIO DEFINE_GUIDNAMED(KSCATEGORY_SYSAUDIO)
-
-#define STATIC_KSCATEGORY_WDMAUD					\
-	0x3E227E76L,0x690D,0x11D2,0x81,0x61,0x00,0x00,0xF8,0x77,0x5B,0xF1
-DEFINE_GUIDSTRUCT("3E227E76-690D-11D2-8161-0000F8775BF1",KSCATEGORY_WDMAUD);
-#define KSCATEGORY_WDMAUD DEFINE_GUIDNAMED(KSCATEGORY_WDMAUD)
-
-#define STATIC_KSCATEGORY_AUDIO_GFX					\
-	0x9BAF9572L,0x340C,0x11D3,0xAB,0xDC,0x00,0xA0,0xC9,0x0A,0xB1,0x6F
-DEFINE_GUIDSTRUCT("9BAF9572-340C-11D3-ABDC-00A0C90AB16F",KSCATEGORY_AUDIO_GFX);
-#define KSCATEGORY_AUDIO_GFX DEFINE_GUIDNAMED(KSCATEGORY_AUDIO_GFX)
-
-#define STATIC_KSCATEGORY_AUDIO_SPLITTER				\
-	0x9EA331FAL,0xB91B,0x45F8,0x92,0x85,0xBD,0x2B,0xC7,0x7A,0xFC,0xDE
-DEFINE_GUIDSTRUCT("9EA331FA-B91B-45F8-9285-BD2BC77AFCDE",KSCATEGORY_AUDIO_SPLITTER);
-#define KSCATEGORY_AUDIO_SPLITTER DEFINE_GUIDNAMED(KSCATEGORY_AUDIO_SPLITTER)
-
-#define STATIC_KSCATEGORY_SYNTHESIZER		STATIC_KSNODETYPE_SYNTHESIZER
-#define KSCATEGORY_SYNTHESIZER			KSNODETYPE_SYNTHESIZER
-
-#define STATIC_KSCATEGORY_DRM_DESCRAMBLE	STATIC_KSNODETYPE_DRM_DESCRAMBLE
-#define KSCATEGORY_DRM_DESCRAMBLE		KSNODETYPE_DRM_DESCRAMBLE
-
-#define STATIC_KSCATEGORY_AUDIO_DEVICE					\
-	0xFBF6F530L,0x07B9,0x11D2,0xA7,0x1E,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("FBF6F530-07B9-11D2-A71E-0000F8004788",KSCATEGORY_AUDIO_DEVICE);
-#define KSCATEGORY_AUDIO_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_AUDIO_DEVICE)
-
-#define STATIC_KSCATEGORY_PREFERRED_WAVEOUT_DEVICE			\
-	0xD6C5066EL,0x72C1,0x11D2,0x97,0x55,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("D6C5066E-72C1-11D2-9755-0000F8004788",KSCATEGORY_PREFERRED_WAVEOUT_DEVICE);
-#define KSCATEGORY_PREFERRED_WAVEOUT_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_PREFERRED_WAVEOUT_DEVICE)
-
-#define STATIC_KSCATEGORY_PREFERRED_WAVEIN_DEVICE			\
-	0xD6C50671L,0x72C1,0x11D2,0x97,0x55,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("D6C50671-72C1-11D2-9755-0000F8004788",KSCATEGORY_PREFERRED_WAVEIN_DEVICE);
-#define KSCATEGORY_PREFERRED_WAVEIN_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_PREFERRED_WAVEIN_DEVICE)
-
-#define STATIC_KSCATEGORY_PREFERRED_MIDIOUT_DEVICE			\
-	0xD6C50674L,0x72C1,0x11D2,0x97,0x55,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("D6C50674-72C1-11D2-9755-0000F8004788",KSCATEGORY_PREFERRED_MIDIOUT_DEVICE);
-#define KSCATEGORY_PREFERRED_MIDIOUT_DEVICE DEFINE_GUIDNAMED(KSCATEGORY_PREFERRED_MIDIOUT_DEVICE)
-
-#define STATIC_KSCATEGORY_WDMAUD_USE_PIN_NAME				\
-	0x47A4FA20L,0xA251,0x11D1,0xA0,0x50,0x00,0x00,0xF8,0x00,0x47,0x88
-DEFINE_GUIDSTRUCT("47A4FA20-A251-11D1-A050-0000F8004788",KSCATEGORY_WDMAUD_USE_PIN_NAME);
-#define KSCATEGORY_WDMAUD_USE_PIN_NAME DEFINE_GUIDNAMED(KSCATEGORY_WDMAUD_USE_PIN_NAME)
-
-#define STATIC_KSCATEGORY_ESCALANTE_PLATFORM_DRIVER			\
-	0x74f3aea8L,0x9768,0x11d1,0x8e,0x07,0x00,0xa0,0xc9,0x5e,0xc2,0x2e
-DEFINE_GUIDSTRUCT("74f3aea8-9768-11d1-8e07-00a0c95ec22e",KSCATEGORY_ESCALANTE_PLATFORM_DRIVER);
-#define KSCATEGORY_ESCALANTE_PLATFORM_DRIVER DEFINE_GUIDNAMED(KSCATEGORY_ESCALANTE_PLATFORM_DRIVER)
-
-#define STATIC_KSDATAFORMAT_TYPE_VIDEO					\
-	0x73646976L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-DEFINE_GUIDSTRUCT("73646976-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_VIDEO);
-#define KSDATAFORMAT_TYPE_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_VIDEO)
-
-#define STATIC_KSDATAFORMAT_TYPE_AUDIO					\
-	0x73647561L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-DEFINE_GUIDSTRUCT("73647561-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_AUDIO);
-#define KSDATAFORMAT_TYPE_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_AUDIO)
-
-#define STATIC_KSDATAFORMAT_TYPE_TEXT					\
-	0x73747874L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-DEFINE_GUIDSTRUCT("73747874-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_TEXT);
-#define KSDATAFORMAT_TYPE_TEXT DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_TEXT)
-
-#if !defined(DEFINE_WAVEFORMATEX_GUID)
-#define DEFINE_WAVEFORMATEX_GUID(x)					\
-	(USHORT)(x),0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-#endif
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX			\
-	0x00000000L,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-DEFINE_GUIDSTRUCT("00000000-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_WAVEFORMATEX);
-#define KSDATAFORMAT_SUBTYPE_WAVEFORMATEX DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_WAVEFORMATEX)
-
-#define INIT_WAVEFORMATEX_GUID(Guid,x)					\
-{									\
-	*(Guid) = KSDATAFORMAT_SUBTYPE_WAVEFORMATEX;			\
-	(Guid)->Data1 = (USHORT)(x);					\
-}
-
-#define EXTRACT_WAVEFORMATEX_ID(Guid)					\
-	(USHORT)((Guid)->Data1)
-
-#define IS_VALID_WAVEFORMATEX_GUID(Guid)				\
-	(!memcmp(((PUSHORT)&KSDATAFORMAT_SUBTYPE_WAVEFORMATEX) + 1, ((PUSHORT)(Guid)) + 1,sizeof(GUID) - sizeof(USHORT)))
-
-#ifndef INIT_MMREG_MID
-#define INIT_MMREG_MID(guid,id)						\
-{									\
-	(guid)->Data1 = 0xd5a47fa7 + (USHORT)(id);			\
-	(guid)->Data2 = 0x6d98;						\
-	(guid)->Data3 = 0x11d1;						\
-	(guid)->Data4[0] = 0xa2;					\
-	(guid)->Data4[1] = 0x1a;					\
-	(guid)->Data4[2] = 0x00;					\
-	(guid)->Data4[3] = 0xa0;					\
-	(guid)->Data4[4] = 0xc9;					\
-	(guid)->Data4[5] = 0x22;					\
-	(guid)->Data4[6] = 0x31;					\
-	(guid)->Data4[7] = 0x96;					\
-}
-#define EXTRACT_MMREG_MID(guid)						\
-	(USHORT)((guid)->Data1 - 0xd5a47fa7)
-#define DEFINE_MMREG_MID_GUID(id)					\
-	0xd5a47fa7+(USHORT)(id),0x6d98,0x11d1,0xa2,0x1a,0x00,0xa0,0xc9,0x22,0x31,0x96
-
-#define IS_COMPATIBLE_MMREG_MID(guid)					\
-	(((guid)->Data1 >= 0xd5a47fa7) &&				\
-	 ((guid)->Data1 < 0xd5a47fa7 + 0xffff) &&			\
-	 ((guid)->Data2 == 0x6d98) &&					\
-	 ((guid)->Data3 == 0x11d1) &&					\
-	 ((guid)->Data4[0] == 0xa2) &&					\
-	 ((guid)->Data4[1] == 0x1a) &&					\
-	 ((guid)->Data4[2] == 0x00) &&					\
-	 ((guid)->Data4[3] == 0xa0) &&					\
-	 ((guid)->Data4[4] == 0xc9) &&					\
-	 ((guid)->Data4[5] == 0x22) &&					\
-	 ((guid)->Data4[6] == 0x31) &&					\
-	 ((guid)->Data4[7] == 0x96) )
-#endif /* INIT_MMREG_MID */
-
-#ifndef INIT_MMREG_PID
-#define INIT_MMREG_PID(guid,id)						\
-{									\
-	(guid)->Data1 = 0xe36dc2ac + (USHORT)(id);			\
-	(guid)->Data2 = 0x6d9a;						\
-	(guid)->Data3 = 0x11d1;						\
-	(guid)->Data4[0] = 0xa2;					\
-	(guid)->Data4[1] = 0x1a;					\
-	(guid)->Data4[2] = 0x00;					\
-	(guid)->Data4[3] = 0xa0;					\
-	(guid)->Data4[4] = 0xc9;					\
-	(guid)->Data4[5] = 0x22;					\
-	(guid)->Data4[6] = 0x31;					\
-	(guid)->Data4[7] = 0x96;					\
-}
-#define EXTRACT_MMREG_PID(guid)						\
-	(USHORT)((guid)->Data1 - 0xe36dc2ac)
-#define DEFINE_MMREG_PID_GUID(id)					\
-	0xe36dc2ac+(USHORT)(id),0x6d9a,0x11d1,0xa2,0x1a,0x00,0xa0,0xc9,0x22,0x31,0x96
-
-#define IS_COMPATIBLE_MMREG_PID(guid)					\
-	(((guid)->Data1 >= 0xe36dc2ac) &&				\
-	 ((guid)->Data1 < 0xe36dc2ac + 0xffff) &&			\
-	 ((guid)->Data2 == 0x6d9a) &&					\
-	 ((guid)->Data3 == 0x11d1) &&					\
-	 ((guid)->Data4[0] == 0xa2) &&					\
-	 ((guid)->Data4[1] == 0x1a) &&					\
-	 ((guid)->Data4[2] == 0x00) &&					\
-	 ((guid)->Data4[3] == 0xa0) &&					\
-	 ((guid)->Data4[4] == 0xc9) &&					\
-	 ((guid)->Data4[5] == 0x22) &&					\
-	 ((guid)->Data4[6] == 0x31) &&					\
-	 ((guid)->Data4[7] == 0x96) )
-#endif /* INIT_MMREG_PID */
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_ANALOG				\
-	0x6dba3190L,0x67bd,0x11cf,0xa0,0xf7,0x00,0x20,0xaf,0xd1,0x56,0xe4
-DEFINE_GUIDSTRUCT("6dba3190-67bd-11cf-a0f7-0020afd156e4",KSDATAFORMAT_SUBTYPE_ANALOG);
-#define KSDATAFORMAT_SUBTYPE_ANALOG DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_ANALOG)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_PCM					\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_PCM)
-DEFINE_GUIDSTRUCT("00000001-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_PCM);
-#define KSDATAFORMAT_SUBTYPE_PCM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_PCM)
-
-#ifdef _INC_MMREG
-#define STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT				\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_IEEE_FLOAT)
-DEFINE_GUIDSTRUCT("00000003-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_IEEE_FLOAT);
-#define KSDATAFORMAT_SUBTYPE_IEEE_FLOAT DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_DRM					\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_DRM)
-DEFINE_GUIDSTRUCT("00000009-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_DRM);
-#define KSDATAFORMAT_SUBTYPE_DRM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DRM)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_ALAW				\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_ALAW)
-DEFINE_GUIDSTRUCT("00000006-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_ALAW);
-#define KSDATAFORMAT_SUBTYPE_ALAW DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_ALAW)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MULAW				\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_MULAW)
-DEFINE_GUIDSTRUCT("00000007-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_MULAW);
-#define KSDATAFORMAT_SUBTYPE_MULAW DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MULAW)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_ADPCM				\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_ADPCM)
-DEFINE_GUIDSTRUCT("00000002-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_ADPCM);
-#define KSDATAFORMAT_SUBTYPE_ADPCM DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_ADPCM)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG				\
-	DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_MPEG)
-DEFINE_GUIDSTRUCT("00000050-0000-0010-8000-00aa00389b71",KSDATAFORMAT_SUBTYPE_MPEG);
-#define KSDATAFORMAT_SUBTYPE_MPEG DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG)
-#endif /* _INC_MMREG */
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_VC_ID				\
-	0xAD98D184L,0xAAC3,0x11D0,0xA4,0x1C,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("AD98D184-AAC3-11D0-A41C-00A0C9223196",KSDATAFORMAT_SPECIFIER_VC_ID);
-#define KSDATAFORMAT_SPECIFIER_VC_ID DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VC_ID)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_WAVEFORMATEX			\
-	0x05589f81L,0xc356,0x11ce,0xbf,0x01,0x00,0xaa,0x00,0x55,0x59,0x5a
-DEFINE_GUIDSTRUCT("05589f81-c356-11ce-bf01-00aa0055595a",KSDATAFORMAT_SPECIFIER_WAVEFORMATEX);
-#define KSDATAFORMAT_SPECIFIER_WAVEFORMATEX DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_DSOUND				\
-	0x518590a2L,0xa184,0x11d0,0x85,0x22,0x00,0xc0,0x4f,0xd9,0xba,0xf3
-DEFINE_GUIDSTRUCT("518590a2-a184-11d0-8522-00c04fd9baf3",KSDATAFORMAT_SPECIFIER_DSOUND);
-#define KSDATAFORMAT_SPECIFIER_DSOUND DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DSOUND)
-
-#if defined(_INC_MMSYSTEM) || defined(_INC_MMREG)
-#if !defined(PACK_PRAGMAS_NOT_SUPPORTED)
-#include <pshpack1.h>
-#endif
-typedef struct {
-  KSDATAFORMAT DataFormat;
-  WAVEFORMATEX WaveFormatEx;
-} KSDATAFORMAT_WAVEFORMATEX,*PKSDATAFORMAT_WAVEFORMATEX;
-
-#ifndef _WAVEFORMATEXTENSIBLE_
-#define _WAVEFORMATEXTENSIBLE_
-typedef struct {
-  WAVEFORMATEX Format;
-  union {
-    WORD wValidBitsPerSample;
-    WORD wSamplesPerBlock;
-    WORD wReserved;
-  } Samples;
-  DWORD dwChannelMask;
-
-  GUID SubFormat;
-} WAVEFORMATEXTENSIBLE,*PWAVEFORMATEXTENSIBLE;
-#endif /* _WAVEFORMATEXTENSIBLE_ */
-
-#if !defined(WAVE_FORMAT_EXTENSIBLE)
-#define WAVE_FORMAT_EXTENSIBLE			0xFFFE
-#endif
-
-typedef struct {
-  ULONG Flags;
-  ULONG Control;
-  WAVEFORMATEX WaveFormatEx;
-} KSDSOUND_BUFFERDESC,*PKSDSOUND_BUFFERDESC;
-
-typedef struct {
-  KSDATAFORMAT DataFormat;
-  KSDSOUND_BUFFERDESC BufferDesc;
-} KSDATAFORMAT_DSOUND,*PKSDATAFORMAT_DSOUND;
-
-#if !defined(PACK_PRAGMAS_NOT_SUPPORTED)
-#include <poppack.h>
-#endif
-#endif /* defined(_INC_MMSYSTEM) || defined(_INC_MMREG) */
-
-#define KSDSOUND_BUFFER_PRIMARY			0x00000001
-#define KSDSOUND_BUFFER_STATIC			0x00000002
-#define KSDSOUND_BUFFER_LOCHARDWARE		0x00000004
-#define KSDSOUND_BUFFER_LOCSOFTWARE		0x00000008
-
-#define KSDSOUND_BUFFER_CTRL_3D			0x00000001
-#define KSDSOUND_BUFFER_CTRL_FREQUENCY		0x00000002
-#define KSDSOUND_BUFFER_CTRL_PAN		0x00000004
-#define KSDSOUND_BUFFER_CTRL_VOLUME		0x00000008
-#define KSDSOUND_BUFFER_CTRL_POSITIONNOTIFY	0x00000010
-
-typedef struct {
-  DWORDLONG PlayOffset;
-  DWORDLONG WriteOffset;
-} KSAUDIO_POSITION,*PKSAUDIO_POSITION;
-
-typedef struct _DS3DVECTOR {
-  __MINGW_EXTENSION union {
-    FLOAT x;
-    FLOAT dvX;
-  };
-  __MINGW_EXTENSION union {
-    FLOAT y;
-    FLOAT dvY;
-  };
-  __MINGW_EXTENSION union {
-    FLOAT z;
-    FLOAT dvZ;
-  };
-} DS3DVECTOR,*PDS3DVECTOR;
-
-#define STATIC_KSPROPSETID_DirectSound3DListener			\
-	0x437b3414L,0xd060,0x11d0,0x85,0x83,0x00,0xc0,0x4f,0xd9,0xba,0xf3
-DEFINE_GUIDSTRUCT("437b3414-d060-11d0-8583-00c04fd9baf3",KSPROPSETID_DirectSound3DListener);
-#define KSPROPSETID_DirectSound3DListener DEFINE_GUIDNAMED(KSPROPSETID_DirectSound3DListener)
-
-typedef enum {
-  KSPROPERTY_DIRECTSOUND3DLISTENER_ALL,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_POSITION,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_VELOCITY,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_ORIENTATION,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_DISTANCEFACTOR,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_ROLLOFFFACTOR,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_DOPPLERFACTOR,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_BATCH,
-  KSPROPERTY_DIRECTSOUND3DLISTENER_ALLOCATION
-} KSPROPERTY_DIRECTSOUND3DLISTENER;
-
-typedef struct {
-  DS3DVECTOR Position;
-  DS3DVECTOR Velocity;
-  DS3DVECTOR OrientFront;
-  DS3DVECTOR OrientTop;
-  FLOAT DistanceFactor;
-  FLOAT RolloffFactor;
-  FLOAT DopplerFactor;
-} KSDS3D_LISTENER_ALL,*PKSDS3D_LISTENER_ALL;
-
-typedef struct {
-  DS3DVECTOR Front;
-  DS3DVECTOR Top;
-} KSDS3D_LISTENER_ORIENTATION,*PKSDS3D_LISTENER_ORIENTATION;
-
-#define STATIC_KSPROPSETID_DirectSound3DBuffer				\
-	0x437b3411L,0xd060,0x11d0,0x85,0x83,0x00,0xc0,0x4f,0xd9,0xba,0xf3
-DEFINE_GUIDSTRUCT("437b3411-d060-11d0-8583-00c04fd9baf3",KSPROPSETID_DirectSound3DBuffer);
-#define KSPROPSETID_DirectSound3DBuffer DEFINE_GUIDNAMED(KSPROPSETID_DirectSound3DBuffer)
-
-typedef enum {
-  KSPROPERTY_DIRECTSOUND3DBUFFER_ALL,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_POSITION,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_VELOCITY,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_CONEANGLES,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_CONEORIENTATION,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_CONEOUTSIDEVOLUME,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_MINDISTANCE,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_MAXDISTANCE,
-  KSPROPERTY_DIRECTSOUND3DBUFFER_MODE
-} KSPROPERTY_DIRECTSOUND3DBUFFER;
-
-typedef struct {
-  DS3DVECTOR Position;
-  DS3DVECTOR Velocity;
-  ULONG InsideConeAngle;
-  ULONG OutsideConeAngle;
-  DS3DVECTOR ConeOrientation;
-  LONG ConeOutsideVolume;
-  FLOAT MinDistance;
-  FLOAT MaxDistance;
-  ULONG Mode;
-} KSDS3D_BUFFER_ALL,*PKSDS3D_BUFFER_ALL;
-
-typedef struct {
-  ULONG InsideConeAngle;
-  ULONG OutsideConeAngle;
-} KSDS3D_BUFFER_CONE_ANGLES,*PKSDS3D_BUFFER_CONE_ANGLES;
-
-#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_HEADPHONE	(-1)
-#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_MIN		5
-#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_NARROW		10
-#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_WIDE		20
-#define KSAUDIO_STEREO_SPEAKER_GEOMETRY_MAX		180
-
-#define KSDSOUND_3D_MODE_NORMAL			0x00000000
-#define KSDSOUND_3D_MODE_HEADRELATIVE		0x00000001
-#define KSDSOUND_3D_MODE_DISABLE		0x00000002
-
-#define KSDSOUND_BUFFER_CTRL_HRTF_3D		0x40000000
-
-typedef struct {
-  ULONG Size;
-  ULONG Enabled;
-  WINBOOL SwapChannels;
-  WINBOOL ZeroAzimuth;
-  WINBOOL CrossFadeOutput;
-  ULONG FilterSize;
-} KSDS3D_HRTF_PARAMS_MSG,*PKSDS3D_HRTF_PARAMS_MSG;
-
-typedef enum {
-  FULL_FILTER,
-  LIGHT_FILTER,
-  KSDS3D_FILTER_QUALITY_COUNT
-} KSDS3D_HRTF_FILTER_QUALITY;
-
-typedef struct {
-  ULONG Size;
-  KSDS3D_HRTF_FILTER_QUALITY Quality;
-  FLOAT SampleRate;
-  ULONG MaxFilterSize;
-  ULONG FilterTransientMuteLength;
-  ULONG FilterOverlapBufferLength;
-  ULONG OutputOverlapBufferLength;
-  ULONG Reserved;
-} KSDS3D_HRTF_INIT_MSG,*PKSDS3D_HRTF_INIT_MSG;
-
-typedef enum {
-  FLOAT_COEFF,
-  SHORT_COEFF,
-  KSDS3D_COEFF_COUNT
-} KSDS3D_HRTF_COEFF_FORMAT;
-
-typedef enum {
-  DIRECT_FORM,
-  CASCADE_FORM,
-  KSDS3D_FILTER_METHOD_COUNT
-} KSDS3D_HRTF_FILTER_METHOD;
-
-typedef enum {
-  DS3D_HRTF_VERSION_1
-} KSDS3D_HRTF_FILTER_VERSION;
-
-typedef struct {
-  KSDS3D_HRTF_FILTER_METHOD FilterMethod;
-  KSDS3D_HRTF_COEFF_FORMAT CoeffFormat;
-  KSDS3D_HRTF_FILTER_VERSION Version;
-  ULONG Reserved;
-} KSDS3D_HRTF_FILTER_FORMAT_MSG,*PKSDS3D_HRTF_FILTER_FORMAT_MSG;
-
-#define STATIC_KSPROPSETID_Hrtf3d					\
-	0xb66decb0L,0xa083,0x11d0,0x85,0x1e,0x00,0xc0,0x4f,0xd9,0xba,0xf3
-DEFINE_GUIDSTRUCT("b66decb0-a083-11d0-851e-00c04fd9baf3",KSPROPSETID_Hrtf3d);
-#define KSPROPSETID_Hrtf3d DEFINE_GUIDNAMED(KSPROPSETID_Hrtf3d)
-
-typedef enum {
-  KSPROPERTY_HRTF3D_PARAMS = 0,
-  KSPROPERTY_HRTF3D_INITIALIZE,
-  KSPROPERTY_HRTF3D_FILTER_FORMAT
-} KSPROPERTY_HRTF3D;
-
-typedef struct {
-  LONG Channel;
-  FLOAT VolSmoothScale;
-  FLOAT TotalDryAttenuation;
-  FLOAT TotalWetAttenuation;
-  LONG SmoothFrequency;
-  LONG Delay;
-} KSDS3D_ITD_PARAMS,*PKSDS3D_ITD_PARAMS;
-
-typedef struct {
-  ULONG Enabled;
-  KSDS3D_ITD_PARAMS LeftParams;
-  KSDS3D_ITD_PARAMS RightParams;
-  ULONG Reserved;
-} KSDS3D_ITD_PARAMS_MSG,*PKSDS3D_ITD_PARAMS_MSG;
-
-#define STATIC_KSPROPSETID_Itd3d					\
-	0x6429f090L,0x9fd9,0x11d0,0xa7,0x5b,0x00,0xa0,0xc9,0x03,0x65,0xe3
-DEFINE_GUIDSTRUCT("6429f090-9fd9-11d0-a75b-00a0c90365e3",KSPROPSETID_Itd3d);
-#define KSPROPSETID_Itd3d DEFINE_GUIDNAMED(KSPROPSETID_Itd3d)
-
-typedef enum {
-  KSPROPERTY_ITD3D_PARAMS = 0
-} KSPROPERTY_ITD3D;
-
-typedef struct {
-  KSDATARANGE DataRange;
-  ULONG MaximumChannels;
-  ULONG MinimumBitsPerSample;
-  ULONG MaximumBitsPerSample;
-  ULONG MinimumSampleFrequency;
-  ULONG MaximumSampleFrequency;
-} KSDATARANGE_AUDIO,*PKSDATARANGE_AUDIO;
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_RIFF				\
-	0x4995DAEEL,0x9EE6,0x11D0,0xA4,0x0E,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("4995DAEE-9EE6-11D0-A40E-00A0C9223196",KSDATAFORMAT_SUBTYPE_RIFF);
-#define KSDATAFORMAT_SUBTYPE_RIFF DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RIFF)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_RIFFWAVE				\
-	0xe436eb8bL,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
-DEFINE_GUIDSTRUCT("e436eb8b-524f-11ce-9f53-0020af0ba770",KSDATAFORMAT_SUBTYPE_RIFFWAVE);
-#define KSDATAFORMAT_SUBTYPE_RIFFWAVE DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RIFFWAVE)
-
-#define STATIC_KSPROPSETID_Bibliographic				\
-	0x07BA150EL,0xE2B1,0x11D0,0xAC,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("07BA150E-E2B1-11D0-AC17-00A0C9223196",KSPROPSETID_Bibliographic);
-#define KSPROPSETID_Bibliographic DEFINE_GUIDNAMED(KSPROPSETID_Bibliographic)
-
-typedef enum {
-  KSPROPERTY_BIBLIOGRAPHIC_LEADER = 'RDL ',
-  KSPROPERTY_BIBLIOGRAPHIC_LCCN = '010 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ISBN = '020 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ISSN = '220 ',
-  KSPROPERTY_BIBLIOGRAPHIC_CATALOGINGSOURCE = '040 ',
-  KSPROPERTY_BIBLIOGRAPHIC_MAINPERSONALNAME = '001 ',
-  KSPROPERTY_BIBLIOGRAPHIC_MAINCORPORATEBODY = '011 ',
-  KSPROPERTY_BIBLIOGRAPHIC_MAINMEETINGNAME = '111 ',
-  KSPROPERTY_BIBLIOGRAPHIC_MAINUNIFORMTITLE = '031 ',
-  KSPROPERTY_BIBLIOGRAPHIC_UNIFORMTITLE = '042 ',
-  KSPROPERTY_BIBLIOGRAPHIC_TITLESTATEMENT = '542 ',
-  KSPROPERTY_BIBLIOGRAPHIC_VARYINGFORMTITLE = '642 ',
-  KSPROPERTY_BIBLIOGRAPHIC_PUBLICATION = '062 ',
-  KSPROPERTY_BIBLIOGRAPHIC_PHYSICALDESCRIPTION = '003 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYTITLE = '044 ',
-  KSPROPERTY_BIBLIOGRAPHIC_SERIESSTATEMENT = '094 ',
-  KSPROPERTY_BIBLIOGRAPHIC_GENERALNOTE = '005 ',
-  KSPROPERTY_BIBLIOGRAPHIC_BIBLIOGRAPHYNOTE = '405 ',
-  KSPROPERTY_BIBLIOGRAPHIC_CONTENTSNOTE = '505 ',
-  KSPROPERTY_BIBLIOGRAPHIC_CREATIONCREDIT = '805 ',
-  KSPROPERTY_BIBLIOGRAPHIC_CITATION = '015 ',
-  KSPROPERTY_BIBLIOGRAPHIC_PARTICIPANT = '115 ',
-  KSPROPERTY_BIBLIOGRAPHIC_SUMMARY = '025 ',
-  KSPROPERTY_BIBLIOGRAPHIC_TARGETAUDIENCE = '125 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDFORMAVAILABLE = '035 ',
-  KSPROPERTY_BIBLIOGRAPHIC_SYSTEMDETAILS = '835 ',
-  KSPROPERTY_BIBLIOGRAPHIC_AWARDS = '685 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYPERSONALNAME = '006 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYTOPICALTERM = '056 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYGEOGRAPHIC = '156 ',
-  KSPROPERTY_BIBLIOGRAPHIC_INDEXTERMGENRE = '556 ',
-  KSPROPERTY_BIBLIOGRAPHIC_INDEXTERMCURRICULUM = '856 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYUNIFORMTITLE = '037 ',
-  KSPROPERTY_BIBLIOGRAPHIC_ADDEDENTRYRELATED = '047 ',
-  KSPROPERTY_BIBLIOGRAPHIC_SERIESSTATEMENTPERSONALNAME = '008 ',
-  KSPROPERTY_BIBLIOGRAPHIC_SERIESSTATEMENTUNIFORMTITLE = '038 '
-} KSPROPERTY_BIBLIOGRAPHIC;
-
-#define STATIC_KSPROPSETID_TopologyNode					\
-	0x45FFAAA1L,0x6E1B,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00
-DEFINE_GUIDSTRUCT("45FFAAA1-6E1B-11D0-BCF2-444553540000",KSPROPSETID_TopologyNode);
-#define KSPROPSETID_TopologyNode DEFINE_GUIDNAMED(KSPROPSETID_TopologyNode)
-
-typedef enum {
-  KSPROPERTY_TOPOLOGYNODE_ENABLE = 1,
-  KSPROPERTY_TOPOLOGYNODE_RESET
-} KSPROPERTY_TOPOLOGYNODE;
-
-#define STATIC_KSPROPSETID_RtAudio					\
-	0xa855a48c,0x2f78,0x4729,0x90,0x51,0x19,0x68,0x74,0x6b,0x9e,0xef
-DEFINE_GUIDSTRUCT("A855A48C-2F78-4729-9051-1968746B9EEF",KSPROPSETID_RtAudio);
-#define KSPROPSETID_RtAudio DEFINE_GUIDNAMED(KSPROPSETID_RtAudio)
-
-typedef enum {
-  KSPROPERTY_RTAUDIO_GETPOSITIONFUNCTION
-} KSPROPERTY_RTAUDIO;
-
-#define STATIC_KSPROPSETID_DrmAudioStream				\
-	0x2f2c8ddd,0x4198,0x4fac,0xba,0x29,0x61,0xbb,0x5,0xb7,0xde,0x6
-DEFINE_GUIDSTRUCT("2F2C8DDD-4198-4fac-BA29-61BB05B7DE06",KSPROPSETID_DrmAudioStream);
-#define KSPROPSETID_DrmAudioStream DEFINE_GUIDNAMED(KSPROPSETID_DrmAudioStream)
-
-typedef enum {
-  KSPROPERTY_DRMAUDIOSTREAM_CONTENTID
-} KSPROPERTY_DRMAUDIOSTREAM;
-
-#define STATIC_KSPROPSETID_Audio					\
-	0x45FFAAA0L,0x6E1B,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00
-DEFINE_GUIDSTRUCT("45FFAAA0-6E1B-11D0-BCF2-444553540000",KSPROPSETID_Audio);
-#define KSPROPSETID_Audio DEFINE_GUIDNAMED(KSPROPSETID_Audio)
-
-typedef enum {
-  KSPROPERTY_AUDIO_LATENCY = 1,
-  KSPROPERTY_AUDIO_COPY_PROTECTION,
-  KSPROPERTY_AUDIO_CHANNEL_CONFIG,
-  KSPROPERTY_AUDIO_VOLUMELEVEL,
-  KSPROPERTY_AUDIO_POSITION,
-  KSPROPERTY_AUDIO_DYNAMIC_RANGE,
-  KSPROPERTY_AUDIO_QUALITY,
-  KSPROPERTY_AUDIO_SAMPLING_RATE,
-  KSPROPERTY_AUDIO_DYNAMIC_SAMPLING_RATE,
-  KSPROPERTY_AUDIO_MIX_LEVEL_TABLE,
-  KSPROPERTY_AUDIO_MIX_LEVEL_CAPS,
-  KSPROPERTY_AUDIO_MUX_SOURCE,
-  KSPROPERTY_AUDIO_MUTE,
-  KSPROPERTY_AUDIO_BASS,
-  KSPROPERTY_AUDIO_MID,
-  KSPROPERTY_AUDIO_TREBLE,
-  KSPROPERTY_AUDIO_BASS_BOOST,
-  KSPROPERTY_AUDIO_EQ_LEVEL,
-  KSPROPERTY_AUDIO_NUM_EQ_BANDS,
-  KSPROPERTY_AUDIO_EQ_BANDS,
-  KSPROPERTY_AUDIO_AGC,
-  KSPROPERTY_AUDIO_DELAY,
-  KSPROPERTY_AUDIO_LOUDNESS,
-  KSPROPERTY_AUDIO_WIDE_MODE,
-  KSPROPERTY_AUDIO_WIDENESS,
-  KSPROPERTY_AUDIO_REVERB_LEVEL,
-  KSPROPERTY_AUDIO_CHORUS_LEVEL,
-  KSPROPERTY_AUDIO_DEV_SPECIFIC,
-  KSPROPERTY_AUDIO_DEMUX_DEST,
-  KSPROPERTY_AUDIO_STEREO_ENHANCE,
-  KSPROPERTY_AUDIO_MANUFACTURE_GUID,
-  KSPROPERTY_AUDIO_PRODUCT_GUID,
-  KSPROPERTY_AUDIO_CPU_RESOURCES,
-  KSPROPERTY_AUDIO_STEREO_SPEAKER_GEOMETRY,
-  KSPROPERTY_AUDIO_SURROUND_ENCODE,
-  KSPROPERTY_AUDIO_3D_INTERFACE,
-  KSPROPERTY_AUDIO_PEAKMETER,
-  KSPROPERTY_AUDIO_ALGORITHM_INSTANCE,
-  KSPROPERTY_AUDIO_FILTER_STATE,
-  KSPROPERTY_AUDIO_PREFERRED_STATUS
-} KSPROPERTY_AUDIO;
-
-#define KSAUDIO_QUALITY_WORST			0x0
-#define KSAUDIO_QUALITY_PC			0x1
-#define KSAUDIO_QUALITY_BASIC			0x2
-#define KSAUDIO_QUALITY_ADVANCED		0x3
-
-#define KSAUDIO_CPU_RESOURCES_NOT_HOST_CPU	0x00000000
-#define KSAUDIO_CPU_RESOURCES_HOST_CPU		0x7FFFFFFF
-
-typedef struct {
-  WINBOOL fCopyrighted;
-  WINBOOL fOriginal;
-} KSAUDIO_COPY_PROTECTION,*PKSAUDIO_COPY_PROTECTION;
-
-typedef struct {
-  LONG ActiveSpeakerPositions;
-} KSAUDIO_CHANNEL_CONFIG,*PKSAUDIO_CHANNEL_CONFIG;
-
-#define SPEAKER_FRONT_LEFT		0x1
-#define SPEAKER_FRONT_RIGHT		0x2
-#define SPEAKER_FRONT_CENTER		0x4
-#define SPEAKER_LOW_FREQUENCY		0x8
-#define SPEAKER_BACK_LEFT		0x10
-#define SPEAKER_BACK_RIGHT		0x20
-#define SPEAKER_FRONT_LEFT_OF_CENTER	0x40
-#define SPEAKER_FRONT_RIGHT_OF_CENTER	0x80
-#define SPEAKER_BACK_CENTER		0x100
-#define SPEAKER_SIDE_LEFT		0x200
-#define SPEAKER_SIDE_RIGHT		0x400
-#define SPEAKER_TOP_CENTER		0x800
-#define SPEAKER_TOP_FRONT_LEFT		0x1000
-#define SPEAKER_TOP_FRONT_CENTER	0x2000
-#define SPEAKER_TOP_FRONT_RIGHT		0x4000
-#define SPEAKER_TOP_BACK_LEFT		0x8000
-#define SPEAKER_TOP_BACK_CENTER		0x10000
-#define SPEAKER_TOP_BACK_RIGHT		0x20000
-
-#define SPEAKER_RESERVED		0x7FFC0000
-
-#define SPEAKER_ALL			0x80000000
-
-#define KSAUDIO_SPEAKER_DIRECTOUT	0
-#define KSAUDIO_SPEAKER_MONO		(SPEAKER_FRONT_CENTER)
-#define KSAUDIO_SPEAKER_STEREO		(SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT)
-#define KSAUDIO_SPEAKER_QUAD		(SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |		\
-					 SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT)
-#define KSAUDIO_SPEAKER_SURROUND	(SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |		\
-					 SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER)
-#define KSAUDIO_SPEAKER_5POINT1		(SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |		\
-					 SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |		\
-					 SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT)
-#define KSAUDIO_SPEAKER_7POINT1		(SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |		\
-					 SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |		\
-					 SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |		\
-					 SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER)
-#define KSAUDIO_SPEAKER_5POINT1_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |		\
-					  SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |	\
-					  SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT)
-#define KSAUDIO_SPEAKER_7POINT1_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |		\
-					  SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |	\
-					  SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |		\
-					  SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT)
-
-#define KSAUDIO_SPEAKER_5POINT1_BACK	KSAUDIO_SPEAKER_5POINT1
-#define KSAUDIO_SPEAKER_7POINT1_WIDE	KSAUDIO_SPEAKER_7POINT1
-
-#define KSAUDIO_SPEAKER_GROUND_FRONT_LEFT	SPEAKER_FRONT_LEFT
-#define KSAUDIO_SPEAKER_GROUND_FRONT_CENTER	SPEAKER_FRONT_CENTER
-#define KSAUDIO_SPEAKER_GROUND_FRONT_RIGHT	SPEAKER_FRONT_RIGHT
-#define KSAUDIO_SPEAKER_GROUND_REAR_LEFT	SPEAKER_BACK_LEFT
-#define KSAUDIO_SPEAKER_GROUND_REAR_RIGHT	SPEAKER_BACK_RIGHT
-#define KSAUDIO_SPEAKER_TOP_MIDDLE		SPEAKER_TOP_CENTER
-#define KSAUDIO_SPEAKER_SUPER_WOOFER		SPEAKER_LOW_FREQUENCY
-
-typedef struct {
-  ULONG QuietCompression;
-  ULONG LoudCompression;
-} KSAUDIO_DYNAMIC_RANGE,*PKSAUDIO_DYNAMIC_RANGE;
-
-typedef struct {
-  WINBOOL Mute;
-  LONG Level;
-} KSAUDIO_MIXLEVEL,*PKSAUDIO_MIXLEVEL;
-
-typedef struct {
-  WINBOOL Mute;
-  LONG Minimum;
-  LONG Maximum;
-  LONG Reset;
-} KSAUDIO_MIX_CAPS,*PKSAUDIO_MIX_CAPS;
-
-typedef struct {
-  ULONG InputChannels;
-  ULONG OutputChannels;
-  KSAUDIO_MIX_CAPS Capabilities[1];
-} KSAUDIO_MIXCAP_TABLE,*PKSAUDIO_MIXCAP_TABLE;
-
-typedef enum {
-  SE_TECH_NONE,
-  SE_TECH_ANALOG_DEVICES_PHAT,
-  SE_TECH_CREATIVE,
-  SE_TECH_NATIONAL_SEMI,
-  SE_TECH_YAMAHA_YMERSION,
-  SE_TECH_BBE,
-  SE_TECH_CRYSTAL_SEMI,
-  SE_TECH_QSOUND_QXPANDER,
-  SE_TECH_SPATIALIZER,
-  SE_TECH_SRS,
-  SE_TECH_PLATFORM_TECH,
-  SE_TECH_AKM,
-  SE_TECH_AUREAL,
-  SE_TECH_AZTECH,
-  SE_TECH_BINAURA,
-  SE_TECH_ESS_TECH,
-  SE_TECH_HARMAN_VMAX,
-  SE_TECH_NVIDEA,
-  SE_TECH_PHILIPS_INCREDIBLE,
-  SE_TECH_TEXAS_INST,
-  SE_TECH_VLSI_TECH
-} SE_TECHNIQUE;
-
-typedef struct {
-  SE_TECHNIQUE Technique;
-  ULONG Center;
-  ULONG Depth;
-  ULONG Reserved;
-} KSAUDIO_STEREO_ENHANCE,*PKSAUDIO_STEREO_ENHANCE;
-
-typedef enum {
-  KSPROPERTY_SYSAUDIO_NORMAL_DEFAULT = 0,
-  KSPROPERTY_SYSAUDIO_PLAYBACK_DEFAULT,
-  KSPROPERTY_SYSAUDIO_RECORD_DEFAULT,
-  KSPROPERTY_SYSAUDIO_MIDI_DEFAULT,
-  KSPROPERTY_SYSAUDIO_MIXER_DEFAULT
-} KSPROPERTY_SYSAUDIO_DEFAULT_TYPE;
-
-typedef struct {
-  WINBOOL Enable;
-  KSPROPERTY_SYSAUDIO_DEFAULT_TYPE DeviceType;
-  ULONG Flags;
-  ULONG Reserved;
-} KSAUDIO_PREFERRED_STATUS,*PKSAUDIO_PREFERRED_STATUS;
-
-#define STATIC_KSNODETYPE_DAC						\
-	0x507AE360L,0xC554,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("507AE360-C554-11D0-8A2B-00A0C9255AC1",KSNODETYPE_DAC);
-#define KSNODETYPE_DAC DEFINE_GUIDNAMED(KSNODETYPE_DAC)
-
-#define STATIC_KSNODETYPE_ADC						\
-	0x4D837FE0L,0xC555,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("4D837FE0-C555-11D0-8A2B-00A0C9255AC1",KSNODETYPE_ADC);
-#define KSNODETYPE_ADC DEFINE_GUIDNAMED(KSNODETYPE_ADC)
-
-#define STATIC_KSNODETYPE_SRC						\
-	0x9DB7B9E0L,0xC555,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("9DB7B9E0-C555-11D0-8A2B-00A0C9255AC1",KSNODETYPE_SRC);
-#define KSNODETYPE_SRC DEFINE_GUIDNAMED(KSNODETYPE_SRC)
-
-#define STATIC_KSNODETYPE_SUPERMIX					\
-	0xE573ADC0L,0xC555,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("E573ADC0-C555-11D0-8A2B-00A0C9255AC1",KSNODETYPE_SUPERMIX);
-#define KSNODETYPE_SUPERMIX DEFINE_GUIDNAMED(KSNODETYPE_SUPERMIX)
-
-#define STATIC_KSNODETYPE_MUX						\
-	0x2CEAF780L,0xC556,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("2CEAF780-C556-11D0-8A2B-00A0C9255AC1",KSNODETYPE_MUX);
-#define KSNODETYPE_MUX DEFINE_GUIDNAMED(KSNODETYPE_MUX)
-
-#define STATIC_KSNODETYPE_DEMUX						\
-	0xC0EB67D4L,0xE807,0x11D0,0x95,0x8A,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("C0EB67D4-E807-11D0-958A-00C04FB925D3",KSNODETYPE_DEMUX);
-#define KSNODETYPE_DEMUX DEFINE_GUIDNAMED(KSNODETYPE_DEMUX)
-
-#define STATIC_KSNODETYPE_SUM						\
-	0xDA441A60L,0xC556,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("DA441A60-C556-11D0-8A2B-00A0C9255AC1",KSNODETYPE_SUM);
-#define KSNODETYPE_SUM DEFINE_GUIDNAMED(KSNODETYPE_SUM)
-
-#define STATIC_KSNODETYPE_MUTE						\
-	0x02B223C0L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("02B223C0-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_MUTE);
-#define KSNODETYPE_MUTE DEFINE_GUIDNAMED(KSNODETYPE_MUTE)
-
-#define STATIC_KSNODETYPE_VOLUME					\
-	0x3A5ACC00L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("3A5ACC00-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_VOLUME);
-#define KSNODETYPE_VOLUME DEFINE_GUIDNAMED(KSNODETYPE_VOLUME)
-
-#define STATIC_KSNODETYPE_TONE						\
-	0x7607E580L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("7607E580-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_TONE);
-#define KSNODETYPE_TONE DEFINE_GUIDNAMED(KSNODETYPE_TONE)
-
-#define STATIC_KSNODETYPE_EQUALIZER					\
-	0x9D41B4A0L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("9D41B4A0-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_EQUALIZER);
-#define KSNODETYPE_EQUALIZER DEFINE_GUIDNAMED(KSNODETYPE_EQUALIZER)
-
-#define STATIC_KSNODETYPE_AGC						\
-	0xE88C9BA0L,0xC557,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("E88C9BA0-C557-11D0-8A2B-00A0C9255AC1",KSNODETYPE_AGC);
-#define KSNODETYPE_AGC DEFINE_GUIDNAMED(KSNODETYPE_AGC)
-
-#define STATIC_KSNODETYPE_NOISE_SUPPRESS				\
-	0xe07f903f,0x62fd,0x4e60,0x8c,0xdd,0xde,0xa7,0x23,0x66,0x65,0xb5
-DEFINE_GUIDSTRUCT("E07F903F-62FD-4e60-8CDD-DEA7236665B5",KSNODETYPE_NOISE_SUPPRESS);
-#define KSNODETYPE_NOISE_SUPPRESS DEFINE_GUIDNAMED(KSNODETYPE_NOISE_SUPPRESS)
-
-#define STATIC_KSNODETYPE_DELAY						\
-	0x144981E0L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("144981E0-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_DELAY);
-#define KSNODETYPE_DELAY DEFINE_GUIDNAMED(KSNODETYPE_DELAY)
-
-#define STATIC_KSNODETYPE_LOUDNESS					\
-	0x41887440L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("41887440-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_LOUDNESS);
-#define KSNODETYPE_LOUDNESS DEFINE_GUIDNAMED(KSNODETYPE_LOUDNESS)
-
-#define STATIC_KSNODETYPE_PROLOGIC_DECODER				\
-	0x831C2C80L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("831C2C80-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_PROLOGIC_DECODER);
-#define KSNODETYPE_PROLOGIC_DECODER DEFINE_GUIDNAMED(KSNODETYPE_PROLOGIC_DECODER)
-
-#define STATIC_KSNODETYPE_STEREO_WIDE					\
-	0xA9E69800L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("A9E69800-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_STEREO_WIDE);
-#define KSNODETYPE_STEREO_WIDE DEFINE_GUIDNAMED(KSNODETYPE_STEREO_WIDE)
-
-#define STATIC_KSNODETYPE_STEREO_ENHANCE				\
-	0xAF6878ACL,0xE83F,0x11D0,0x95,0x8A,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("AF6878AC-E83F-11D0-958A-00C04FB925D3",KSNODETYPE_STEREO_ENHANCE);
-#define KSNODETYPE_STEREO_ENHANCE DEFINE_GUIDNAMED(KSNODETYPE_STEREO_ENHANCE)
-
-#define STATIC_KSNODETYPE_REVERB					\
-	0xEF0328E0L,0xC558,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("EF0328E0-C558-11D0-8A2B-00A0C9255AC1",KSNODETYPE_REVERB);
-#define KSNODETYPE_REVERB DEFINE_GUIDNAMED(KSNODETYPE_REVERB)
-
-#define STATIC_KSNODETYPE_CHORUS					\
-	0x20173F20L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("20173F20-C559-11D0-8A2B-00A0C9255AC1",KSNODETYPE_CHORUS);
-#define KSNODETYPE_CHORUS DEFINE_GUIDNAMED(KSNODETYPE_CHORUS)
-
-#define STATIC_KSNODETYPE_3D_EFFECTS					\
-	0x55515860L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("55515860-C559-11D0-8A2B-00A0C9255AC1",KSNODETYPE_3D_EFFECTS);
-#define KSNODETYPE_3D_EFFECTS DEFINE_GUIDNAMED(KSNODETYPE_3D_EFFECTS)
-
-#define STATIC_KSNODETYPE_ACOUSTIC_ECHO_CANCEL STATIC_KSCATEGORY_ACOUSTIC_ECHO_CANCEL
-#define KSNODETYPE_ACOUSTIC_ECHO_CANCEL KSCATEGORY_ACOUSTIC_ECHO_CANCEL
-
-#define STATIC_KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL		\
-	0x1c22c56dL,0x9879,0x4f5b,0xa3,0x89,0x27,0x99,0x6d,0xdc,0x28,0x10
-DEFINE_GUIDSTRUCT("1C22C56D-9879-4f5b-A389-27996DDC2810",KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL);
-#define KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_ACOUSTIC_ECHO_CANCEL)
-
-#define STATIC_KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS		\
-	0x5ab0882eL,0x7274,0x4516,0x87,0x7d,0x4e,0xee,0x99,0xba,0x4f,0xd0
-DEFINE_GUIDSTRUCT("5AB0882E-7274-4516-877D-4EEE99BA4FD0",KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS);
-#define KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_NOISE_SUPPRESS)
-
-#define STATIC_KSALGORITHMINSTANCE_SYSTEM_AGC				\
-	0x950e55b9L,0x877c,0x4c67,0xbe,0x8,0xe4,0x7b,0x56,0x11,0x13,0xa
-DEFINE_GUIDSTRUCT("950E55B9-877C-4c67-BE08-E47B5611130A",KSALGORITHMINSTANCE_SYSTEM_AGC);
-#define KSALGORITHMINSTANCE_SYSTEM_AGC DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_AGC)
-
-#define STATIC_KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR	\
-	0xB6F5A0A0L,0x9E61,0x4F8C,0x91,0xE3,0x76,0xCF,0xF,0x3C,0x47,0x1F
-DEFINE_GUIDSTRUCT("B6F5A0A0-9E61-4f8c-91E3-76CF0F3C471F",KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR);
-#define KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR DEFINE_GUIDNAMED(KSALGORITHMINSTANCE_SYSTEM_MICROPHONE_ARRAY_PROCESSOR)
-
-#define STATIC_KSNODETYPE_MICROPHONE_ARRAY_PROCESSOR STATIC_KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR
-#define KSNODETYPE_MICROPHONE_ARRAY_PROCESSOR KSCATEGORY_MICROPHONE_ARRAY_PROCESSOR
-
-#define STATIC_KSNODETYPE_DEV_SPECIFIC					\
-	0x941C7AC0L,0xC559,0x11D0,0x8A,0x2B,0x00,0xA0,0xC9,0x25,0x5A,0xC1
-DEFINE_GUIDSTRUCT("941C7AC0-C559-11D0-8A2B-00A0C9255AC1",KSNODETYPE_DEV_SPECIFIC);
-#define KSNODETYPE_DEV_SPECIFIC DEFINE_GUIDNAMED(KSNODETYPE_DEV_SPECIFIC)
-
-#define STATIC_KSNODETYPE_PROLOGIC_ENCODER				\
-	0x8074C5B2L,0x3C66,0x11D2,0xB4,0x5A,0x30,0x78,0x30,0x2C,0x20,0x30
-DEFINE_GUIDSTRUCT("8074C5B2-3C66-11D2-B45A-3078302C2030",KSNODETYPE_PROLOGIC_ENCODER);
-#define KSNODETYPE_PROLOGIC_ENCODER DEFINE_GUIDNAMED(KSNODETYPE_PROLOGIC_ENCODER)
-#define KSNODETYPE_SURROUND_ENCODER KSNODETYPE_PROLOGIC_ENCODER
-
-#define STATIC_KSNODETYPE_PEAKMETER					\
-	0xa085651eL,0x5f0d,0x4b36,0xa8,0x69,0xd1,0x95,0xd6,0xab,0x4b,0x9e
-DEFINE_GUIDSTRUCT("A085651E-5F0D-4b36-A869-D195D6AB4B9E",KSNODETYPE_PEAKMETER);
-#define KSNODETYPE_PEAKMETER DEFINE_GUIDNAMED(KSNODETYPE_PEAKMETER)
-
-#define STATIC_KSAUDFNAME_BASS						\
-	0x185FEDE0L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE0-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_BASS);
-#define KSAUDFNAME_BASS DEFINE_GUIDNAMED(KSAUDFNAME_BASS)
-
-#define STATIC_KSAUDFNAME_TREBLE					\
-	0x185FEDE1L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE1-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_TREBLE);
-#define KSAUDFNAME_TREBLE DEFINE_GUIDNAMED(KSAUDFNAME_TREBLE)
-
-#define STATIC_KSAUDFNAME_3D_STEREO					\
-	0x185FEDE2L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE2-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_3D_STEREO);
-#define KSAUDFNAME_3D_STEREO DEFINE_GUIDNAMED(KSAUDFNAME_3D_STEREO)
-
-#define STATIC_KSAUDFNAME_MASTER_VOLUME					\
-	0x185FEDE3L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE3-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MASTER_VOLUME);
-#define KSAUDFNAME_MASTER_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MASTER_VOLUME)
-
-#define STATIC_KSAUDFNAME_MASTER_MUTE					\
-	0x185FEDE4L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE4-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MASTER_MUTE);
-#define KSAUDFNAME_MASTER_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MASTER_MUTE)
-
-#define STATIC_KSAUDFNAME_WAVE_VOLUME					\
-	0x185FEDE5L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE5-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_VOLUME);
-#define KSAUDFNAME_WAVE_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_VOLUME)
-
-#define STATIC_KSAUDFNAME_WAVE_MUTE					\
-	0x185FEDE6L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE6-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_MUTE);
-#define KSAUDFNAME_WAVE_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_MUTE)
-
-#define STATIC_KSAUDFNAME_MIDI_VOLUME					\
-	0x185FEDE7L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE7-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI_VOLUME);
-#define KSAUDFNAME_MIDI_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIDI_VOLUME)
-
-#define STATIC_KSAUDFNAME_MIDI_MUTE					\
-	0x185FEDE8L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE8-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI_MUTE);
-#define KSAUDFNAME_MIDI_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MIDI_MUTE)
-
-#define STATIC_KSAUDFNAME_CD_VOLUME					\
-	0x185FEDE9L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDE9-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_VOLUME);
-#define KSAUDFNAME_CD_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_CD_VOLUME)
-
-#define STATIC_KSAUDFNAME_CD_MUTE					\
-	0x185FEDEAL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDEA-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_MUTE);
-#define KSAUDFNAME_CD_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_CD_MUTE)
-
-#define STATIC_KSAUDFNAME_LINE_VOLUME					\
-	0x185FEDEBL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDEB-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_VOLUME);
-#define KSAUDFNAME_LINE_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_LINE_VOLUME)
-
-#define STATIC_KSAUDFNAME_LINE_MUTE					\
-	0x185FEDECL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDEC-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_MUTE);
-#define KSAUDFNAME_LINE_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_LINE_MUTE)
-
-#define STATIC_KSAUDFNAME_MIC_VOLUME					\
-	0x185FEDEDL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDED-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIC_VOLUME);
-#define KSAUDFNAME_MIC_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIC_VOLUME)
-
-#define STATIC_KSAUDFNAME_MIC_MUTE					\
-	0x185FEDEEL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDEE-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIC_MUTE);
-#define KSAUDFNAME_MIC_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MIC_MUTE)
-
-#define STATIC_KSAUDFNAME_RECORDING_SOURCE				\
-	0x185FEDEFL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDEF-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_RECORDING_SOURCE);
-#define KSAUDFNAME_RECORDING_SOURCE DEFINE_GUIDNAMED(KSAUDFNAME_RECORDING_SOURCE)
-
-#define STATIC_KSAUDFNAME_PC_SPEAKER_VOLUME				\
-	0x185FEDF0L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF0-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_PC_SPEAKER_VOLUME);
-#define KSAUDFNAME_PC_SPEAKER_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_PC_SPEAKER_VOLUME)
-
-#define STATIC_KSAUDFNAME_PC_SPEAKER_MUTE				\
-	0x185FEDF1L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF1-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_PC_SPEAKER_MUTE);
-#define KSAUDFNAME_PC_SPEAKER_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_PC_SPEAKER_MUTE)
-
-#define STATIC_KSAUDFNAME_MIDI_IN_VOLUME				\
-	0x185FEDF2L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF2-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI_IN_VOLUME);
-#define KSAUDFNAME_MIDI_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIDI_IN_VOLUME)
-
-#define STATIC_KSAUDFNAME_CD_IN_VOLUME					\
-	0x185FEDF3L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF3-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_IN_VOLUME);
-#define KSAUDFNAME_CD_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_CD_IN_VOLUME)
-
-#define STATIC_KSAUDFNAME_LINE_IN_VOLUME				\
-	0x185FEDF4L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF4-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_IN_VOLUME);
-#define KSAUDFNAME_LINE_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_LINE_IN_VOLUME)
-
-#define STATIC_KSAUDFNAME_MIC_IN_VOLUME					\
-	0x185FEDF5L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF5-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIC_IN_VOLUME);
-#define KSAUDFNAME_MIC_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MIC_IN_VOLUME)
-
-#define STATIC_KSAUDFNAME_WAVE_IN_VOLUME				\
-	0x185FEDF6L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF6-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_IN_VOLUME);
-#define KSAUDFNAME_WAVE_IN_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_IN_VOLUME)
-
-#define STATIC_KSAUDFNAME_VOLUME_CONTROL				\
-	0x185FEDF7L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF7-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_VOLUME_CONTROL);
-#define KSAUDFNAME_VOLUME_CONTROL DEFINE_GUIDNAMED(KSAUDFNAME_VOLUME_CONTROL)
-
-#define STATIC_KSAUDFNAME_MIDI						\
-	0x185FEDF8L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF8-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_MIDI);
-#define KSAUDFNAME_MIDI DEFINE_GUIDNAMED(KSAUDFNAME_MIDI)
-
-#define STATIC_KSAUDFNAME_LINE_IN					\
-	0x185FEDF9L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDF9-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_LINE_IN);
-#define KSAUDFNAME_LINE_IN DEFINE_GUIDNAMED(KSAUDFNAME_LINE_IN)
-
-#define STATIC_KSAUDFNAME_RECORDING_CONTROL				\
-	0x185FEDFAL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDFA-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_RECORDING_CONTROL);
-#define KSAUDFNAME_RECORDING_CONTROL DEFINE_GUIDNAMED(KSAUDFNAME_RECORDING_CONTROL)
-
-#define STATIC_KSAUDFNAME_CD_AUDIO					\
-	0x185FEDFBL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDFB-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_CD_AUDIO);
-#define KSAUDFNAME_CD_AUDIO DEFINE_GUIDNAMED(KSAUDFNAME_CD_AUDIO)
-
-#define STATIC_KSAUDFNAME_AUX_VOLUME					\
-	0x185FEDFCL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDFC-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_AUX_VOLUME);
-#define KSAUDFNAME_AUX_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_AUX_VOLUME)
-
-#define STATIC_KSAUDFNAME_AUX_MUTE					\
-	0x185FEDFDL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDFD-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_AUX_MUTE);
-#define KSAUDFNAME_AUX_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_AUX_MUTE)
-
-#define STATIC_KSAUDFNAME_AUX						\
-	0x185FEDFEL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDFE-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_AUX);
-#define KSAUDFNAME_AUX DEFINE_GUIDNAMED(KSAUDFNAME_AUX)
-
-#define STATIC_KSAUDFNAME_PC_SPEAKER					\
-	0x185FEDFFL,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEDFF-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_PC_SPEAKER);
-#define KSAUDFNAME_PC_SPEAKER DEFINE_GUIDNAMED(KSAUDFNAME_PC_SPEAKER)
-
-#define STATIC_KSAUDFNAME_WAVE_OUT_MIX					\
-	0x185FEE00L,0x9905,0x11D1,0x95,0xA9,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("185FEE00-9905-11D1-95A9-00C04FB925D3",KSAUDFNAME_WAVE_OUT_MIX);
-#define KSAUDFNAME_WAVE_OUT_MIX DEFINE_GUIDNAMED(KSAUDFNAME_WAVE_OUT_MIX)
-
-#define STATIC_KSAUDFNAME_MONO_OUT					\
-	0xf9b41dc3L,0x96e2,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("F9B41DC3-96E2-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_OUT);
-#define KSAUDFNAME_MONO_OUT DEFINE_GUIDNAMED(KSAUDFNAME_MONO_OUT)
-
-#define STATIC_KSAUDFNAME_STEREO_MIX					\
-	0xdff077L,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("00DFF077-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_STEREO_MIX);
-#define KSAUDFNAME_STEREO_MIX DEFINE_GUIDNAMED(KSAUDFNAME_STEREO_MIX)
-
-#define STATIC_KSAUDFNAME_MONO_MIX					\
-	0xdff078L,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("00DFF078-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_MIX);
-#define KSAUDFNAME_MONO_MIX DEFINE_GUIDNAMED(KSAUDFNAME_MONO_MIX)
-
-#define STATIC_KSAUDFNAME_MONO_OUT_VOLUME				\
-	0x1ad247ebL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("1AD247EB-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_OUT_VOLUME);
-#define KSAUDFNAME_MONO_OUT_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MONO_OUT_VOLUME)
-
-#define STATIC_KSAUDFNAME_MONO_OUT_MUTE					\
-	0x1ad247ecL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("1AD247EC-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_OUT_MUTE);
-#define KSAUDFNAME_MONO_OUT_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MONO_OUT_MUTE)
-
-#define STATIC_KSAUDFNAME_STEREO_MIX_VOLUME				\
-	0x1ad247edL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("1AD247ED-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_STEREO_MIX_VOLUME);
-#define KSAUDFNAME_STEREO_MIX_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_STEREO_MIX_VOLUME)
-
-#define STATIC_KSAUDFNAME_STEREO_MIX_MUTE				\
-	0x22b0eafdL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("22B0EAFD-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_STEREO_MIX_MUTE);
-#define KSAUDFNAME_STEREO_MIX_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_STEREO_MIX_MUTE)
-
-#define STATIC_KSAUDFNAME_MONO_MIX_VOLUME				\
-	0x22b0eafeL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("22B0EAFE-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_MIX_VOLUME);
-#define KSAUDFNAME_MONO_MIX_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_MONO_MIX_VOLUME)
-
-#define STATIC_KSAUDFNAME_MONO_MIX_MUTE					\
-	0x2bc31d69L,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("2BC31D69-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MONO_MIX_MUTE);
-#define KSAUDFNAME_MONO_MIX_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_MONO_MIX_MUTE)
-
-#define STATIC_KSAUDFNAME_MICROPHONE_BOOST				\
-	0x2bc31d6aL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("2BC31D6A-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_MICROPHONE_BOOST);
-#define KSAUDFNAME_MICROPHONE_BOOST DEFINE_GUIDNAMED(KSAUDFNAME_MICROPHONE_BOOST)
-
-#define STATIC_KSAUDFNAME_ALTERNATE_MICROPHONE				\
-	0x2bc31d6bL,0x96e3,0x11d2,0xac,0x4c,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("2BC31D6B-96E3-11d2-AC4C-00C04F8EFB68",KSAUDFNAME_ALTERNATE_MICROPHONE);
-#define KSAUDFNAME_ALTERNATE_MICROPHONE DEFINE_GUIDNAMED(KSAUDFNAME_ALTERNATE_MICROPHONE)
-
-#define STATIC_KSAUDFNAME_3D_DEPTH					\
-	0x63ff5747L,0x991f,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("63FF5747-991F-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_3D_DEPTH);
-#define KSAUDFNAME_3D_DEPTH DEFINE_GUIDNAMED(KSAUDFNAME_3D_DEPTH)
-
-#define STATIC_KSAUDFNAME_3D_CENTER					\
-	0x9f0670b4L,0x991f,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("9F0670B4-991F-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_3D_CENTER);
-#define KSAUDFNAME_3D_CENTER DEFINE_GUIDNAMED(KSAUDFNAME_3D_CENTER)
-
-#define STATIC_KSAUDFNAME_VIDEO_VOLUME					\
-	0x9b46e708L,0x992a,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("9B46E708-992A-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_VIDEO_VOLUME);
-#define KSAUDFNAME_VIDEO_VOLUME DEFINE_GUIDNAMED(KSAUDFNAME_VIDEO_VOLUME)
-
-#define STATIC_KSAUDFNAME_VIDEO_MUTE					\
-	0x9b46e709L,0x992a,0x11d2,0xac,0x4d,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("9B46E709-992A-11d2-AC4D-00C04F8EFB68",KSAUDFNAME_VIDEO_MUTE);
-#define KSAUDFNAME_VIDEO_MUTE DEFINE_GUIDNAMED(KSAUDFNAME_VIDEO_MUTE)
-
-#define STATIC_KSAUDFNAME_VIDEO						\
-	0x915daec4L,0xa434,0x11d2,0xac,0x52,0x0,0xc0,0x4f,0x8e,0xfb,0x68
-DEFINE_GUIDSTRUCT("915DAEC4-A434-11d2-AC52-00C04F8EFB68",KSAUDFNAME_VIDEO);
-#define KSAUDFNAME_VIDEO DEFINE_GUIDNAMED(KSAUDFNAME_VIDEO)
-
-#define STATIC_KSAUDFNAME_PEAKMETER					\
-	0x57e24340L,0xfc5b,0x4612,0xa5,0x62,0x72,0xb1,0x1a,0x29,0xdf,0xae
-DEFINE_GUIDSTRUCT("57E24340-FC5B-4612-A562-72B11A29DFAE",KSAUDFNAME_PEAKMETER);
-#define KSAUDFNAME_PEAKMETER DEFINE_GUIDNAMED(KSAUDFNAME_PEAKMETER)
-
-#define KSNODEPIN_STANDARD_IN		1
-#define KSNODEPIN_STANDARD_OUT		0
-
-#define KSNODEPIN_SUM_MUX_IN		1
-#define KSNODEPIN_SUM_MUX_OUT		0
-
-#define KSNODEPIN_DEMUX_IN		0
-#define KSNODEPIN_DEMUX_OUT		1
-
-#define KSNODEPIN_AEC_RENDER_IN		1
-#define KSNODEPIN_AEC_RENDER_OUT	0
-#define KSNODEPIN_AEC_CAPTURE_IN	2
-#define KSNODEPIN_AEC_CAPTURE_OUT	3
-
-#define STATIC_KSMETHODSETID_Wavetable					\
-	0xDCEF31EBL,0xD907,0x11D0,0x95,0x83,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("DCEF31EB-D907-11D0-9583-00C04FB925D3",KSMETHODSETID_Wavetable);
-#define KSMETHODSETID_Wavetable DEFINE_GUIDNAMED(KSMETHODSETID_Wavetable)
-
-typedef enum {
-  KSMETHOD_WAVETABLE_WAVE_ALLOC,
-  KSMETHOD_WAVETABLE_WAVE_FREE,
-  KSMETHOD_WAVETABLE_WAVE_FIND,
-  KSMETHOD_WAVETABLE_WAVE_WRITE
-} KSMETHOD_WAVETABLE;
-
-typedef struct {
-  KSIDENTIFIER Identifier;
-  ULONG Size;
-  WINBOOL Looped;
-  ULONG LoopPoint;
-  WINBOOL InROM;
-  KSDATAFORMAT Format;
-} KSWAVETABLE_WAVE_DESC,*PKSWAVETABLE_WAVE_DESC;
-
-#define STATIC_KSPROPSETID_Acoustic_Echo_Cancel				\
-	0xd7a4af8bL,0x3dc1,0x4902,0x91,0xea,0x8a,0x15,0xc9,0x0e,0x05,0xb2
-DEFINE_GUIDSTRUCT("D7A4AF8B-3DC1-4902-91EA-8A15C90E05B2",KSPROPSETID_Acoustic_Echo_Cancel);
-#define KSPROPSETID_Acoustic_Echo_Cancel DEFINE_GUIDNAMED(KSPROPSETID_Acoustic_Echo_Cancel)
-
-typedef enum {
-  KSPROPERTY_AEC_NOISE_FILL_ENABLE = 0,
-  KSPROPERTY_AEC_STATUS,
-  KSPROPERTY_AEC_MODE
-} KSPROPERTY_AEC;
-
-#define AEC_STATUS_FD_HISTORY_UNINITIALIZED		0x0
-#define AEC_STATUS_FD_HISTORY_CONTINUOUSLY_CONVERGED	0x1
-#define AEC_STATUS_FD_HISTORY_PREVIOUSLY_DIVERGED	0x2
-#define AEC_STATUS_FD_CURRENTLY_CONVERGED		0x8
-
-#define AEC_MODE_PASS_THROUGH				0x0
-#define AEC_MODE_HALF_DUPLEX				0x1
-#define AEC_MODE_FULL_DUPLEX				0x2
-
-#define STATIC_KSPROPSETID_Wave						\
-	0x924e54b0L,0x630f,0x11cf,0xad,0xa7,0x08,0x00,0x3e,0x30,0x49,0x4a
-DEFINE_GUIDSTRUCT("924e54b0-630f-11cf-ada7-08003e30494a",KSPROPSETID_Wave);
-#define KSPROPSETID_Wave DEFINE_GUIDNAMED(KSPROPSETID_Wave)
-
-typedef enum {
-  KSPROPERTY_WAVE_COMPATIBLE_CAPABILITIES,
-  KSPROPERTY_WAVE_INPUT_CAPABILITIES,
-  KSPROPERTY_WAVE_OUTPUT_CAPABILITIES,
-  KSPROPERTY_WAVE_BUFFER,
-  KSPROPERTY_WAVE_FREQUENCY,
-  KSPROPERTY_WAVE_VOLUME,
-  KSPROPERTY_WAVE_PAN
-} KSPROPERTY_WAVE;
-
-typedef struct {
-  ULONG ulDeviceType;
-} KSWAVE_COMPATCAPS,*PKSWAVE_COMPATCAPS;
-
-#define KSWAVE_COMPATCAPS_INPUT		0x00000000
-#define KSWAVE_COMPATCAPS_OUTPUT	0x00000001
-
-typedef struct {
-  ULONG MaximumChannelsPerConnection;
-  ULONG MinimumBitsPerSample;
-  ULONG MaximumBitsPerSample;
-  ULONG MinimumSampleFrequency;
-  ULONG MaximumSampleFrequency;
-  ULONG TotalConnections;
-  ULONG ActiveConnections;
-} KSWAVE_INPUT_CAPABILITIES,*PKSWAVE_INPUT_CAPABILITIES;
-
-typedef struct {
-  ULONG MaximumChannelsPerConnection;
-  ULONG MinimumBitsPerSample;
-  ULONG MaximumBitsPerSample;
-  ULONG MinimumSampleFrequency;
-  ULONG MaximumSampleFrequency;
-  ULONG TotalConnections;
-  ULONG StaticConnections;
-  ULONG StreamingConnections;
-  ULONG ActiveConnections;
-  ULONG ActiveStaticConnections;
-  ULONG ActiveStreamingConnections;
-  ULONG Total3DConnections;
-  ULONG Static3DConnections;
-  ULONG Streaming3DConnections;
-  ULONG Active3DConnections;
-  ULONG ActiveStatic3DConnections;
-  ULONG ActiveStreaming3DConnections;
-  ULONG TotalSampleMemory;
-  ULONG FreeSampleMemory;
-  ULONG LargestFreeContiguousSampleMemory;
-} KSWAVE_OUTPUT_CAPABILITIES,*PKSWAVE_OUTPUT_CAPABILITIES;
-
-typedef struct {
-  LONG LeftAttenuation;
-  LONG RightAttenuation;
-} KSWAVE_VOLUME,*PKSWAVE_VOLUME;
-
-#define KSWAVE_BUFFER_ATTRIBUTEF_LOOPING	0x00000001
-#define KSWAVE_BUFFER_ATTRIBUTEF_STATIC		0x00000002
-
-typedef struct {
-  ULONG Attributes;
-  ULONG BufferSize;
-  PVOID BufferAddress;
-} KSWAVE_BUFFER,*PKSWAVE_BUFFER;
-
-#define STATIC_KSMUSIC_TECHNOLOGY_PORT					\
-	0x86C92E60L,0x62E8,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("86C92E60-62E8-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_PORT);
-#define KSMUSIC_TECHNOLOGY_PORT DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_PORT)
-
-#define STATIC_KSMUSIC_TECHNOLOGY_SQSYNTH				\
-	0x0ECF4380L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("0ECF4380-62E9-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_SQSYNTH);
-#define KSMUSIC_TECHNOLOGY_SQSYNTH DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_SQSYNTH)
-
-#define STATIC_KSMUSIC_TECHNOLOGY_FMSYNTH				\
-	0x252C5C80L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("252C5C80-62E9-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_FMSYNTH);
-#define KSMUSIC_TECHNOLOGY_FMSYNTH DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_FMSYNTH)
-
-#define STATIC_KSMUSIC_TECHNOLOGY_WAVETABLE				\
-	0x394EC7C0L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("394EC7C0-62E9-11CF-A5D6-28DB04C10000",KSMUSIC_TECHNOLOGY_WAVETABLE);
-#define KSMUSIC_TECHNOLOGY_WAVETABLE DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_WAVETABLE)
-
-#define STATIC_KSMUSIC_TECHNOLOGY_SWSYNTH				\
-	0x37407736L,0x3620,0x11D1,0x85,0xD3,0x00,0x00,0xF8,0x75,0x43,0x80
-DEFINE_GUIDSTRUCT("37407736-3620-11D1-85D3-0000F8754380",KSMUSIC_TECHNOLOGY_SWSYNTH);
-#define KSMUSIC_TECHNOLOGY_SWSYNTH DEFINE_GUIDNAMED(KSMUSIC_TECHNOLOGY_SWSYNTH)
-
-#define STATIC_KSPROPSETID_WaveTable					\
-	0x8539E660L,0x62E9,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("8539E660-62E9-11CF-A5D6-28DB04C10000",KSPROPSETID_WaveTable);
-#define KSPROPSETID_WaveTable DEFINE_GUIDNAMED(KSPROPSETID_WaveTable)
-
-typedef enum {
-  KSPROPERTY_WAVETABLE_LOAD_SAMPLE,
-  KSPROPERTY_WAVETABLE_UNLOAD_SAMPLE,
-  KSPROPERTY_WAVETABLE_MEMORY,
-  KSPROPERTY_WAVETABLE_VERSION
-} KSPROPERTY_WAVETABLE;
-
-typedef struct {
-  KSDATARANGE DataRange;
-  GUID Technology;
-  ULONG Channels;
-  ULONG Notes;
-  ULONG ChannelMask;
-} KSDATARANGE_MUSIC,*PKSDATARANGE_MUSIC;
-
-#define STATIC_KSEVENTSETID_Cyclic					\
-	0x142C1AC0L,0x072A,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("142C1AC0-072A-11D0-A5D6-28DB04C10000",KSEVENTSETID_Cyclic);
-#define KSEVENTSETID_Cyclic DEFINE_GUIDNAMED(KSEVENTSETID_Cyclic)
-
-typedef enum {
-  KSEVENT_CYCLIC_TIME_INTERVAL
-} KSEVENT_CYCLIC_TIME;
-
-#define STATIC_KSPROPSETID_Cyclic					\
-	0x3FFEAEA0L,0x2BEE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("3FFEAEA0-2BEE-11CF-A5D6-28DB04C10000",KSPROPSETID_Cyclic);
-#define KSPROPSETID_Cyclic DEFINE_GUIDNAMED(KSPROPSETID_Cyclic)
-
-typedef enum {
-  KSPROPERTY_CYCLIC_POSITION
-} KSPROPERTY_CYCLIC;
-
-#define STATIC_KSEVENTSETID_AudioControlChange				\
-	0xE85E9698L,0xFA2F,0x11D1,0x95,0xBD,0x00,0xC0,0x4F,0xB9,0x25,0xD3
-DEFINE_GUIDSTRUCT("E85E9698-FA2F-11D1-95BD-00C04FB925D3",KSEVENTSETID_AudioControlChange);
-#define KSEVENTSETID_AudioControlChange DEFINE_GUIDNAMED(KSEVENTSETID_AudioControlChange)
-
-typedef enum {
-  KSEVENT_CONTROL_CHANGE
-} KSEVENT_AUDIO_CONTROL_CHANGE;
-
-#define STATIC_KSEVENTSETID_LoopedStreaming				\
-	0x4682B940L,0xC6EF,0x11D0,0x96,0xD8,0x00,0xAA,0x00,0x51,0xE5,0x1D
-DEFINE_GUIDSTRUCT("4682B940-C6EF-11D0-96D8-00AA0051E51D",KSEVENTSETID_LoopedStreaming);
-#define KSEVENTSETID_LoopedStreaming DEFINE_GUIDNAMED(KSEVENTSETID_LoopedStreaming)
-
-typedef enum {
-  KSEVENT_LOOPEDSTREAMING_POSITION
-} KSEVENT_LOOPEDSTREAMING;
-
-typedef struct {
-  KSEVENTDATA KsEventData;
-  DWORDLONG Position;
-} LOOPEDSTREAMING_POSITION_EVENT_DATA,*PLOOPEDSTREAMING_POSITION_EVENT_DATA;
-
-#define STATIC_KSPROPSETID_Sysaudio					\
-	0xCBE3FAA0L,0xCC75,0x11D0,0xB4,0x65,0x00,0x00,0x1A,0x18,0x18,0xE6
-DEFINE_GUIDSTRUCT("CBE3FAA0-CC75-11D0-B465-00001A1818E6",KSPROPSETID_Sysaudio);
-#define KSPROPSETID_Sysaudio DEFINE_GUIDNAMED(KSPROPSETID_Sysaudio)
-
-typedef enum {
-  KSPROPERTY_SYSAUDIO_DEVICE_COUNT = 1,
-  KSPROPERTY_SYSAUDIO_DEVICE_FRIENDLY_NAME = 2,
-  KSPROPERTY_SYSAUDIO_DEVICE_INSTANCE = 3,
-  KSPROPERTY_SYSAUDIO_DEVICE_INTERFACE_NAME = 4,
-  KSPROPERTY_SYSAUDIO_SELECT_GRAPH = 5,
-  KSPROPERTY_SYSAUDIO_CREATE_VIRTUAL_SOURCE = 6,
-  KSPROPERTY_SYSAUDIO_DEVICE_DEFAULT = 7,
-  KSPROPERTY_SYSAUDIO_INSTANCE_INFO = 14,
-  KSPROPERTY_SYSAUDIO_COMPONENT_ID = 16
-} KSPROPERTY_SYSAUDIO;
-
-typedef struct {
-  KSPROPERTY Property;
-  GUID PinCategory;
-  GUID PinName;
-} SYSAUDIO_CREATE_VIRTUAL_SOURCE,*PSYSAUDIO_CREATE_VIRTUAL_SOURCE;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG PinId;
-  ULONG NodeId;
-  ULONG Flags;
-  ULONG Reserved;
-} SYSAUDIO_SELECT_GRAPH,*PSYSAUDIO_SELECT_GRAPH;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Flags;
-  ULONG DeviceNumber;
-} SYSAUDIO_INSTANCE_INFO,*PSYSAUDIO_INSTANCE_INFO;
-
-#define SYSAUDIO_FLAGS_DONT_COMBINE_PINS	0x00000001
-
-#define STATIC_KSPROPSETID_Sysaudio_Pin					\
-	0xA3A53220L,0xC6E4,0x11D0,0xB4,0x65,0x00,0x00,0x1A,0x18,0x18,0xE6
-DEFINE_GUIDSTRUCT("A3A53220-C6E4-11D0-B465-00001A1818E6",KSPROPSETID_Sysaudio_Pin);
-#define KSPROPSETID_Sysaudio_Pin DEFINE_GUIDNAMED(KSPROPSETID_Sysaudio_Pin)
-
-typedef enum {
-  KSPROPERTY_SYSAUDIO_ATTACH_VIRTUAL_SOURCE = 1
-} KSPROPERTY_SYSAUDIO_PIN;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG MixerPinId;
-  ULONG Reserved;
-} SYSAUDIO_ATTACH_VIRTUAL_SOURCE,*PSYSAUDIO_ATTACH_VIRTUAL_SOURCE;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG NodeId;
-  ULONG Reserved;
-} KSNODEPROPERTY,*PKSNODEPROPERTY;
-
-typedef struct {
-  KSNODEPROPERTY NodeProperty;
-  LONG Channel;
-  ULONG Reserved;
-} KSNODEPROPERTY_AUDIO_CHANNEL,*PKSNODEPROPERTY_AUDIO_CHANNEL;
-
-typedef struct {
-  KSNODEPROPERTY NodeProperty;
-  ULONG DevSpecificId;
-  ULONG DeviceInfo;
-  ULONG Length;
-} KSNODEPROPERTY_AUDIO_DEV_SPECIFIC,*PKSNODEPROPERTY_AUDIO_DEV_SPECIFIC;
-
-typedef struct {
-  KSNODEPROPERTY NodeProperty;
-  PVOID ListenerId;
-#ifndef _WIN64
-  ULONG Reserved;
-#endif
-} KSNODEPROPERTY_AUDIO_3D_LISTENER,*PKSNODEPROPERTY_AUDIO_3D_LISTENER;
-
-typedef struct {
-  KSNODEPROPERTY NodeProperty;
-  PVOID AppContext;
-  ULONG Length;
-#ifndef _WIN64
-  ULONG Reserved;
-#endif
-} KSNODEPROPERTY_AUDIO_PROPERTY,*PKSNODEPROPERTY_AUDIO_PROPERTY;
-
-#define STATIC_KSPROPSETID_AudioGfx					\
-	0x79a9312eL,0x59ae,0x43b0,0xa3,0x50,0x8b,0x5,0x28,0x4c,0xab,0x24
-DEFINE_GUIDSTRUCT("79A9312E-59AE-43b0-A350-8B05284CAB24",KSPROPSETID_AudioGfx);
-#define KSPROPSETID_AudioGfx DEFINE_GUIDNAMED(KSPROPSETID_AudioGfx)
-
-typedef enum {
-  KSPROPERTY_AUDIOGFX_RENDERTARGETDEVICEID,
-  KSPROPERTY_AUDIOGFX_CAPTURETARGETDEVICEID
-} KSPROPERTY_AUDIOGFX;
-
-#define STATIC_KSPROPSETID_Linear					\
-	0x5A2FFE80L,0x16B9,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("5A2FFE80-16B9-11D0-A5D6-28DB04C10000",KSPROPSETID_Linear);
-#define KSPROPSETID_Linear DEFINE_GUIDNAMED(KSPROPSETID_Linear)
-
-typedef enum {
-  KSPROPERTY_LINEAR_POSITION
-} KSPROPERTY_LINEAR;
-
-#define STATIC_KSDATAFORMAT_TYPE_MUSIC					\
-	0xE725D360L,0x62CC,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("E725D360-62CC-11CF-A5D6-28DB04C10000",KSDATAFORMAT_TYPE_MUSIC);
-#define KSDATAFORMAT_TYPE_MUSIC DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MUSIC)
-
-#define STATIC_KSDATAFORMAT_TYPE_MIDI					\
-	0x7364696DL,0x0000,0x0010,0x80,0x00,0x00,0xaa,0x00,0x38,0x9b,0x71
-DEFINE_GUIDSTRUCT("7364696D-0000-0010-8000-00aa00389b71",KSDATAFORMAT_TYPE_MIDI);
-#define KSDATAFORMAT_TYPE_MIDI DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MIDI)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MIDI				\
-	0x1D262760L,0xE957,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("1D262760-E957-11CF-A5D6-28DB04C10000",KSDATAFORMAT_SUBTYPE_MIDI);
-#define KSDATAFORMAT_SUBTYPE_MIDI DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MIDI)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MIDI_BUS				\
-	0x2CA15FA0L,0x6CFE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00
-DEFINE_GUIDSTRUCT("2CA15FA0-6CFE-11CF-A5D6-28DB04C10000",KSDATAFORMAT_SUBTYPE_MIDI_BUS);
-#define KSDATAFORMAT_SUBTYPE_MIDI_BUS DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MIDI_BUS)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_RIFFMIDI				\
-	0x4995DAF0L,0x9EE6,0x11D0,0xA4,0x0E,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("4995DAF0-9EE6-11D0-A40E-00A0C9223196",KSDATAFORMAT_SUBTYPE_RIFFMIDI);
-#define KSDATAFORMAT_SUBTYPE_RIFFMIDI DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RIFFMIDI)
-
-typedef struct {
-  ULONG TimeDeltaMs;
-
-  ULONG ByteCount;
-} KSMUSICFORMAT,*PKSMUSICFORMAT;
-
-#define STATIC_KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM		\
-	0x36523b11L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B11-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM);
-#define KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STANDARD_ELEMENTARY_STREAM)
-
-#define STATIC_KSDATAFORMAT_TYPE_STANDARD_PES_PACKET			\
-	0x36523b12L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B12-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_TYPE_STANDARD_PES_PACKET);
-#define KSDATAFORMAT_TYPE_STANDARD_PES_PACKET DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STANDARD_PES_PACKET)
-
-#define STATIC_KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER			\
-	0x36523b13L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B13-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER);
-#define KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_STANDARD_PACK_HEADER)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO		\
-	0x36523b21L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B21-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO);
-#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_VIDEO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO		\
-	0x36523b22L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B22-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG1_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO		\
-	0x36523b23L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B23-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO);
-#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_VIDEO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO		\
-	0x36523b24L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B24-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_MPEG2_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO			\
-	0x36523b25L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B25-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_STANDARD_AC3_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO		\
-	0x36523b31L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B31-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO);
-#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_VIDEO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO		\
-	0x36523b32L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B32-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO);
-#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG1_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO		\
-	0x36523b33L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B33-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO);
-#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_VIDEO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO		\
-	0x36523b34L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B34-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO);
-#define KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_MPEG2_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO			\
-	0x36523b35L,0x8ee5,0x11d1,0x8c,0xa3,0x00,0x60,0xb0,0x57,0x66,0x4a
-DEFINE_GUIDSTRUCT("36523B35-8EE5-11d1-8CA3-0060B057664A",KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO);
-#define KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_DIALECT_AC3_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_DSS_VIDEO				\
-	0xa0af4f81L,0xe163,0x11d0,0xba,0xd9,0x00,0x60,0x97,0x44,0x11,0x1a
-DEFINE_GUIDSTRUCT("a0af4f81-e163-11d0-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_DSS_VIDEO);
-#define KSDATAFORMAT_SUBTYPE_DSS_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DSS_VIDEO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_DSS_AUDIO				\
-		0xa0af4f82L,0xe163,0x11d0,0xba,0xd9,0x00,0x60,0x97,0x44,0x11,0x1a
-DEFINE_GUIDSTRUCT("a0af4f82-e163-11d0-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_DSS_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_DSS_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DSS_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG1Packet				\
-	0xe436eb80,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
-DEFINE_GUIDSTRUCT("e436eb80-524f-11ce-9F53-0020af0ba770",KSDATAFORMAT_SUBTYPE_MPEG1Packet);
-#define KSDATAFORMAT_SUBTYPE_MPEG1Packet DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG1Packet)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG1Payload			\
-	0xe436eb81,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
-DEFINE_GUIDSTRUCT("e436eb81-524f-11ce-9F53-0020af0ba770",KSDATAFORMAT_SUBTYPE_MPEG1Payload);
-#define KSDATAFORMAT_SUBTYPE_MPEG1Payload DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG1Payload)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG1Video				\
-	0xe436eb86,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
-DEFINE_GUIDSTRUCT("e436eb86-524f-11ce-9f53-0020af0ba770",KSDATAFORMAT_SUBTYPE_MPEG1Video);
-#define KSDATAFORMAT_SUBTYPE_MPEG1Video DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG1Video)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO			\
-	0x05589f82L,0xc356,0x11ce,0xbf,0x01,0x00,0xaa,0x00,0x55,0x59,0x5a
-DEFINE_GUIDSTRUCT("05589f82-c356-11ce-bf01-00aa0055595a",KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO);
-#define KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_MPEG1_VIDEO)
-
-#define STATIC_KSDATAFORMAT_TYPE_MPEG2_PES				\
-	0xe06d8020L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8020-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_TYPE_MPEG2_PES);
-#define KSDATAFORMAT_TYPE_MPEG2_PES DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MPEG2_PES)
-
-#define STATIC_KSDATAFORMAT_TYPE_MPEG2_PROGRAM				\
-	0xe06d8022L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8022-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_TYPE_MPEG2_PROGRAM);
-#define KSDATAFORMAT_TYPE_MPEG2_PROGRAM DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MPEG2_PROGRAM)
-
-#define STATIC_KSDATAFORMAT_TYPE_MPEG2_TRANSPORT			\
-	0xe06d8023L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8023-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_TYPE_MPEG2_TRANSPORT);
-#define KSDATAFORMAT_TYPE_MPEG2_TRANSPORT DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_MPEG2_TRANSPORT)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO				\
-	0xe06d8026L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8026-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO);
-#define KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO			\
-	0xe06d80e3L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d80e3-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO);
-#define KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO)
-
-#define STATIC_KSPROPSETID_Mpeg2Vid					\
-	0xC8E11B60L,0x0CC9,0x11D0,0xBD,0x69,0x00,0x35,0x05,0xC1,0x03,0xA9
-DEFINE_GUIDSTRUCT("C8E11B60-0CC9-11D0-BD69-003505C103A9",KSPROPSETID_Mpeg2Vid);
-#define KSPROPSETID_Mpeg2Vid DEFINE_GUIDNAMED(KSPROPSETID_Mpeg2Vid)
-
-typedef enum {
-  KSPROPERTY_MPEG2VID_MODES,
-  KSPROPERTY_MPEG2VID_CUR_MODE,
-  KSPROPERTY_MPEG2VID_4_3_RECT,
-  KSPROPERTY_MPEG2VID_16_9_RECT,
-  KSPROPERTY_MPEG2VID_16_9_PANSCAN
-} KSPROPERTY_MPEG2VID;
-
-#define KSMPEGVIDMODE_PANSCAN	0x0001
-#define KSMPEGVIDMODE_LTRBOX	0x0002
-#define KSMPEGVIDMODE_SCALE	0x0004
-
-typedef struct _KSMPEGVID_RECT {
-  ULONG StartX;
-  ULONG StartY;
-  ULONG EndX;
-  ULONG EndY;
-} KSMPEGVID_RECT,*PKSMPEGVID_RECT;
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO				\
-	0xe06d802bL,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d802b-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO			\
-	0xe06d80e5L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d80e5-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO);
-#define KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_MPEG2_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_LPCM_AUDIO				\
-	0xe06d8032L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8032-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_LPCM_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_LPCM_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_LPCM_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_LPCM_AUDIO			\
-	0xe06d80e6L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d80e6-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_LPCM_AUDIO);
-#define KSDATAFORMAT_SPECIFIER_LPCM_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_LPCM_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_AC3_AUDIO				\
-	0xe06d802cL,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d802c-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_AC3_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_AC3_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_AC3_AUDIO				\
-	0xe06d80e4L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d80e4-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SPECIFIER_AC3_AUDIO);
-#define KSDATAFORMAT_SPECIFIER_AC3_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_AC3_AUDIO)
-
-#define STATIC_KSPROPSETID_AC3						\
-	0xBFABE720L,0x6E1F,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00
-DEFINE_GUIDSTRUCT("BFABE720-6E1F-11D0-BCF2-444553540000",KSPROPSETID_AC3);
-#define KSPROPSETID_AC3 DEFINE_GUIDNAMED(KSPROPSETID_AC3)
-
-typedef enum {
-  KSPROPERTY_AC3_ERROR_CONCEALMENT = 1,
-  KSPROPERTY_AC3_ALTERNATE_AUDIO,
-  KSPROPERTY_AC3_DOWNMIX,
-  KSPROPERTY_AC3_BIT_STREAM_MODE,
-  KSPROPERTY_AC3_DIALOGUE_LEVEL,
-  KSPROPERTY_AC3_LANGUAGE_CODE,
-  KSPROPERTY_AC3_ROOM_TYPE
-} KSPROPERTY_AC3;
-
-typedef struct {
-  WINBOOL fRepeatPreviousBlock;
-  WINBOOL fErrorInCurrentBlock;
-} KSAC3_ERROR_CONCEALMENT,*PKSAC3_ERROR_CONCEALMENT;
-
-typedef struct {
-  WINBOOL fStereo;
-  ULONG DualMode;
-} KSAC3_ALTERNATE_AUDIO,*PKSAC3_ALTERNATE_AUDIO;
-
-#define KSAC3_ALTERNATE_AUDIO_1		1
-#define KSAC3_ALTERNATE_AUDIO_2		2
-#define KSAC3_ALTERNATE_AUDIO_BOTH	3
-
-typedef struct {
-  WINBOOL fDownMix;
-  WINBOOL fDolbySurround;
-} KSAC3_DOWNMIX,*PKSAC3_DOWNMIX;
-
-typedef struct {
-  LONG BitStreamMode;
-} KSAC3_BIT_STREAM_MODE,*PKSAC3_BIT_STREAM_MODE;
-
-#define KSAC3_SERVICE_MAIN_AUDIO	0
-#define KSAC3_SERVICE_NO_DIALOG		1
-#define KSAC3_SERVICE_VISUALLY_IMPAIRED	2
-#define KSAC3_SERVICE_HEARING_IMPAIRED	3
-#define KSAC3_SERVICE_DIALOG_ONLY	4
-#define KSAC3_SERVICE_COMMENTARY	5
-#define KSAC3_SERVICE_EMERGENCY_FLASH	6
-#define KSAC3_SERVICE_VOICE_OVER	7
-
-typedef struct {
-  ULONG DialogueLevel;
-} KSAC3_DIALOGUE_LEVEL,*PKSAC3_DIALOGUE_LEVEL;
-
-typedef struct {
-  WINBOOL fLargeRoom;
-} KSAC3_ROOM_TYPE,*PKSAC3_ROOM_TYPE;
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_DTS_AUDIO				\
-	0xe06d8033L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8033-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_DTS_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_DTS_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DTS_AUDIO)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_SDDS_AUDIO				\
-	0xe06d8034L,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d8034-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_SDDS_AUDIO);
-#define KSDATAFORMAT_SUBTYPE_SDDS_AUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_SDDS_AUDIO)
-
-#define STATIC_KSPROPSETID_AudioDecoderOut				\
-	0x6ca6e020L,0x43bd,0x11d0,0xbd,0x6a,0x00,0x35,0x05,0xc1,0x03,0xa9
-DEFINE_GUIDSTRUCT("6ca6e020-43bd-11d0-bd6a-003505c103a9",KSPROPSETID_AudioDecoderOut);
-#define KSPROPSETID_AudioDecoderOut DEFINE_GUIDNAMED(KSPROPSETID_AudioDecoderOut)
-
-typedef enum {
-  KSPROPERTY_AUDDECOUT_MODES,
-  KSPROPERTY_AUDDECOUT_CUR_MODE
-} KSPROPERTY_AUDDECOUT;
-
-#define KSAUDDECOUTMODE_STEREO_ANALOG	0x0001
-#define KSAUDDECOUTMODE_PCM_51		0x0002
-#define KSAUDDECOUTMODE_SPDIFF		0x0004
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_SUBPICTURE				\
-	0xe06d802dL,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea
-DEFINE_GUIDSTRUCT("e06d802d-db46-11cf-b4d1-00805f6cbbea",KSDATAFORMAT_SUBTYPE_SUBPICTURE);
-#define KSDATAFORMAT_SUBTYPE_SUBPICTURE DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_SUBPICTURE)
-
-#define STATIC_KSPROPSETID_DvdSubPic					\
-	0xac390460L,0x43af,0x11d0,0xbd,0x6a,0x00,0x35,0x05,0xc1,0x03,0xa9
-DEFINE_GUIDSTRUCT("ac390460-43af-11d0-bd6a-003505c103a9",KSPROPSETID_DvdSubPic);
-#define KSPROPSETID_DvdSubPic DEFINE_GUIDNAMED(KSPROPSETID_DvdSubPic)
-
-typedef enum {
-  KSPROPERTY_DVDSUBPIC_PALETTE,
-  KSPROPERTY_DVDSUBPIC_HLI,
-  KSPROPERTY_DVDSUBPIC_COMPOSIT_ON
-} KSPROPERTY_DVDSUBPIC;
-
-typedef struct _KS_DVD_YCrCb {
-  UCHAR Reserved;
-  UCHAR Y;
-  UCHAR Cr;
-  UCHAR Cb;
-} KS_DVD_YCrCb,*PKS_DVD_YCrCb;
-
-typedef struct _KS_DVD_YUV {
-  UCHAR Reserved;
-  UCHAR Y;
-  UCHAR V;
-  UCHAR U;
-} KS_DVD_YUV,*PKS_DVD_YUV;
-
-typedef struct _KSPROPERTY_SPPAL {
-  KS_DVD_YUV sppal[16];
-} KSPROPERTY_SPPAL,*PKSPROPERTY_SPPAL;
-
-typedef struct _KS_COLCON {
-  UCHAR emph1col:4;
-  UCHAR emph2col:4;
-  UCHAR backcol:4;
-  UCHAR patcol:4;
-  UCHAR emph1con:4;
-  UCHAR emph2con:4;
-  UCHAR backcon:4;
-  UCHAR patcon:4;
-} KS_COLCON,*PKS_COLCON;
-
-typedef struct _KSPROPERTY_SPHLI {
-  USHORT HLISS;
-  USHORT Reserved;
-  ULONG StartPTM;
-  ULONG EndPTM;
-  USHORT StartX;
-  USHORT StartY;
-  USHORT StopX;
-  USHORT StopY;
-  KS_COLCON ColCon;
-} KSPROPERTY_SPHLI,*PKSPROPERTY_SPHLI;
-
-typedef WINBOOL KSPROPERTY_COMPOSIT_ON,*PKSPROPERTY_COMPOSIT_ON;
-
-#define STATIC_KSPROPSETID_CopyProt					\
-	0x0E8A0A40L,0x6AEF,0x11D0,0x9E,0xD0,0x00,0xA0,0x24,0xCA,0x19,0xB3
-DEFINE_GUIDSTRUCT("0E8A0A40-6AEF-11D0-9ED0-00A024CA19B3",KSPROPSETID_CopyProt);
-#define KSPROPSETID_CopyProt DEFINE_GUIDNAMED(KSPROPSETID_CopyProt)
-
-typedef enum {
-  KSPROPERTY_DVDCOPY_CHLG_KEY = 0x01,
-  KSPROPERTY_DVDCOPY_DVD_KEY1,
-  KSPROPERTY_DVDCOPY_DEC_KEY2,
-  KSPROPERTY_DVDCOPY_TITLE_KEY,
-  KSPROPERTY_COPY_MACROVISION,
-  KSPROPERTY_DVDCOPY_REGION,
-  KSPROPERTY_DVDCOPY_SET_COPY_STATE,
-  KSPROPERTY_DVDCOPY_DISC_KEY = 0x80
-} KSPROPERTY_COPYPROT;
-
-typedef struct _KS_DVDCOPY_CHLGKEY {
-  BYTE ChlgKey[10];
-  BYTE Reserved[2];
-} KS_DVDCOPY_CHLGKEY,*PKS_DVDCOPY_CHLGKEY;
-
-typedef struct _KS_DVDCOPY_BUSKEY {
-  BYTE BusKey[5];
-  BYTE Reserved[1];
-} KS_DVDCOPY_BUSKEY,*PKS_DVDCOPY_BUSKEY;
-
-typedef struct _KS_DVDCOPY_DISCKEY {
-  BYTE DiscKey[2048];
-} KS_DVDCOPY_DISCKEY,*PKS_DVDCOPY_DISCKEY;
-
-typedef struct _KS_DVDCOPY_REGION {
-  UCHAR Reserved;
-  UCHAR RegionData;
-  UCHAR Reserved2[2];
-} KS_DVDCOPY_REGION,*PKS_DVDCOPY_REGION;
-
-typedef struct _KS_DVDCOPY_TITLEKEY {
-  ULONG KeyFlags;
-  ULONG ReservedNT[2];
-  UCHAR TitleKey[6];
-  UCHAR Reserved[2];
-} KS_DVDCOPY_TITLEKEY,*PKS_DVDCOPY_TITLEKEY;
-
-typedef struct _KS_COPY_MACROVISION {
-  ULONG MACROVISIONLevel;
-} KS_COPY_MACROVISION,*PKS_COPY_MACROVISION;
-
-typedef struct _KS_DVDCOPY_SET_COPY_STATE {
-  ULONG DVDCopyState;
-} KS_DVDCOPY_SET_COPY_STATE,*PKS_DVDCOPY_SET_COPY_STATE;
-
-typedef enum {
-  KS_DVDCOPYSTATE_INITIALIZE,
-  KS_DVDCOPYSTATE_INITIALIZE_TITLE,
-  KS_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED,
-  KS_DVDCOPYSTATE_AUTHENTICATION_REQUIRED,
-  KS_DVDCOPYSTATE_DONE
-} KS_DVDCOPYSTATE;
-
-typedef enum {
-  KS_MACROVISION_DISABLED,
-  KS_MACROVISION_LEVEL1,
-  KS_MACROVISION_LEVEL2,
-  KS_MACROVISION_LEVEL3
-} KS_COPY_MACROVISION_LEVEL,*PKS_COPY_MACROVISION_LEVEL;
-
-#define KS_DVD_CGMS_RESERVED_MASK	0x00000078
-
-#define KS_DVD_CGMS_COPY_PROTECT_MASK	0x00000018
-#define KS_DVD_CGMS_COPY_PERMITTED	0x00000000
-#define KS_DVD_CGMS_COPY_ONCE		0x00000010
-#define KS_DVD_CGMS_NO_COPY		0x00000018
-
-#define KS_DVD_COPYRIGHT_MASK		0x00000040
-#define KS_DVD_NOT_COPYRIGHTED		0x00000000
-#define KS_DVD_COPYRIGHTED		0x00000040
-
-#define KS_DVD_SECTOR_PROTECT_MASK	0x00000020
-#define KS_DVD_SECTOR_NOT_PROTECTED	0x00000000
-#define KS_DVD_SECTOR_PROTECTED		0x00000020
-
-#define STATIC_KSCATEGORY_TVTUNER					\
-	0xa799a800L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
-DEFINE_GUIDSTRUCT("a799a800-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_TVTUNER);
-#define KSCATEGORY_TVTUNER DEFINE_GUIDNAMED(KSCATEGORY_TVTUNER)
-
-#define STATIC_KSCATEGORY_CROSSBAR					\
-	0xa799a801L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
-DEFINE_GUIDSTRUCT("a799a801-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_CROSSBAR);
-#define KSCATEGORY_CROSSBAR DEFINE_GUIDNAMED(KSCATEGORY_CROSSBAR)
-
-#define STATIC_KSCATEGORY_TVAUDIO					\
-	0xa799a802L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
-DEFINE_GUIDSTRUCT("a799a802-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_TVAUDIO);
-#define KSCATEGORY_TVAUDIO DEFINE_GUIDNAMED(KSCATEGORY_TVAUDIO)
-
-#define STATIC_KSCATEGORY_VPMUX						\
-	0xa799a803L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4
-DEFINE_GUIDSTRUCT("a799a803-a46d-11d0-a18c-00a02401dcd4",KSCATEGORY_VPMUX);
-#define KSCATEGORY_VPMUX DEFINE_GUIDNAMED(KSCATEGORY_VPMUX)
-
-#define STATIC_KSCATEGORY_VBICODEC					\
-	0x07dad660L,0x22f1,0x11d1,0xa9,0xf4,0x00,0xc0,0x4f,0xbb,0xde,0x8f
-DEFINE_GUIDSTRUCT("07dad660-22f1-11d1-a9f4-00c04fbbde8f",KSCATEGORY_VBICODEC);
-#define KSCATEGORY_VBICODEC DEFINE_GUIDNAMED(KSCATEGORY_VBICODEC)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_VPVideo				\
-	0x5a9b6a40L,0x1a22,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
-DEFINE_GUIDSTRUCT("5a9b6a40-1a22-11d1-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_VPVideo);
-#define KSDATAFORMAT_SUBTYPE_VPVideo DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_VPVideo)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_VPVBI				\
-	0x5a9b6a41L,0x1a22,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
-DEFINE_GUIDSTRUCT("5a9b6a41-1a22-11d1-bad9-00609744111a",KSDATAFORMAT_SUBTYPE_VPVBI);
-#define KSDATAFORMAT_SUBTYPE_VPVBI DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_VPVBI)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_VIDEOINFO				\
-	0x05589f80L,0xc356,0x11ce,0xbf,0x01,0x00,0xaa,0x00,0x55,0x59,0x5a
-DEFINE_GUIDSTRUCT("05589f80-c356-11ce-bf01-00aa0055595a",KSDATAFORMAT_SPECIFIER_VIDEOINFO);
-#define KSDATAFORMAT_SPECIFIER_VIDEOINFO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VIDEOINFO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_VIDEOINFO2			\
-	0xf72a76A0L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("f72a76A0-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SPECIFIER_VIDEOINFO2);
-#define KSDATAFORMAT_SPECIFIER_VIDEOINFO2 DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VIDEOINFO2)
-
-#define STATIC_KSDATAFORMAT_TYPE_ANALOGVIDEO				\
-	0x0482dde1L,0x7817,0x11cf,0x8a,0x03,0x00,0xaa,0x00,0x6e,0xcb,0x65
-DEFINE_GUIDSTRUCT("0482dde1-7817-11cf-8a03-00aa006ecb65",KSDATAFORMAT_TYPE_ANALOGVIDEO);
-#define KSDATAFORMAT_TYPE_ANALOGVIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_ANALOGVIDEO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_ANALOGVIDEO			\
-	0x0482dde0L,0x7817,0x11cf,0x8a,0x03,0x00,0xaa,0x00,0x6e,0xcb,0x65
-DEFINE_GUIDSTRUCT("0482dde0-7817-11cf-8a03-00aa006ecb65",KSDATAFORMAT_SPECIFIER_ANALOGVIDEO);
-#define KSDATAFORMAT_SPECIFIER_ANALOGVIDEO DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_ANALOGVIDEO)
-
-#define STATIC_KSDATAFORMAT_TYPE_ANALOGAUDIO				\
-	0x0482dee1L,0x7817,0x11cf,0x8a,0x03,0x00,0xaa,0x00,0x6e,0xcb,0x65
-DEFINE_GUIDSTRUCT("0482DEE1-7817-11cf-8a03-00aa006ecb65",KSDATAFORMAT_TYPE_ANALOGAUDIO);
-#define KSDATAFORMAT_TYPE_ANALOGAUDIO DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_ANALOGAUDIO)
-
-#define STATIC_KSDATAFORMAT_SPECIFIER_VBI				\
-	0xf72a76e0L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("f72a76e0-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SPECIFIER_VBI);
-#define KSDATAFORMAT_SPECIFIER_VBI DEFINE_GUIDNAMED(KSDATAFORMAT_SPECIFIER_VBI)
-
-#define STATIC_KSDATAFORMAT_TYPE_VBI					\
-	0xf72a76e1L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("f72a76e1-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_TYPE_VBI);
-#define KSDATAFORMAT_TYPE_VBI DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_VBI)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_RAW8				\
-	0xca20d9a0,0x3e3e,0x11d1,0x9b,0xf9,0x0,0xc0,0x4f,0xbb,0xde,0xbf
-DEFINE_GUIDSTRUCT("ca20d9a0-3e3e-11d1-9bf9-00c04fbbdebf",KSDATAFORMAT_SUBTYPE_RAW8);
-#define KSDATAFORMAT_SUBTYPE_RAW8 DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_RAW8)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_CC					\
-	0x33214cc1,0x11f,0x11d2,0xb4,0xb1,0x0,0xa0,0xd1,0x2,0xcf,0xbe
-DEFINE_GUIDSTRUCT("33214CC1-011F-11D2-B4B1-00A0D102CFBE",KSDATAFORMAT_SUBTYPE_CC);
-#define KSDATAFORMAT_SUBTYPE_CC DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_CC)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_NABTS				\
-	0xf72a76e2L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("f72a76e2-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SUBTYPE_NABTS);
-#define KSDATAFORMAT_SUBTYPE_NABTS DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_NABTS)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_TELETEXT				\
-	0xf72a76e3L,0xeb0a,0x11d0,0xac,0xe4,0x00,0x00,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("f72a76e3-eb0a-11d0-ace4-0000c0cc16ba",KSDATAFORMAT_SUBTYPE_TELETEXT);
-#define KSDATAFORMAT_SUBTYPE_TELETEXT DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_TELETEXT)
-
-#define KS_BI_RGB		0L
-#define KS_BI_RLE8		1L
-#define KS_BI_RLE4		2L
-#define KS_BI_BITFIELDS		3L
-
-typedef struct tagKS_RGBQUAD {
-  BYTE rgbBlue;
-  BYTE rgbGreen;
-  BYTE rgbRed;
-  BYTE rgbReserved;
-} KS_RGBQUAD,*PKS_RGBQUAD;
-
-#define KS_iPALETTE_COLORS	256
-#define KS_iEGA_COLORS		16
-#define KS_iMASK_COLORS		3
-#define KS_iTRUECOLOR		16
-#define KS_iRED			0
-#define KS_iGREEN		1
-#define KS_iBLUE		2
-#define KS_iPALETTE		8
-#define KS_iMAXBITS		8
-#define KS_SIZE_EGA_PALETTE	(KS_iEGA_COLORS *sizeof(KS_RGBQUAD))
-#define KS_SIZE_PALETTE		(KS_iPALETTE_COLORS *sizeof(KS_RGBQUAD))
-
-typedef struct tagKS_BITMAPINFOHEADER {
-  DWORD biSize;
-  LONG biWidth;
-  LONG biHeight;
-  WORD biPlanes;
-  WORD biBitCount;
-  DWORD biCompression;
-  DWORD biSizeImage;
-  LONG biXPelsPerMeter;
-  LONG biYPelsPerMeter;
-  DWORD biClrUsed;
-  DWORD biClrImportant;
-} KS_BITMAPINFOHEADER,*PKS_BITMAPINFOHEADER;
-
-typedef struct tag_KS_TRUECOLORINFO {
-  DWORD dwBitMasks[KS_iMASK_COLORS];
-  KS_RGBQUAD bmiColors[KS_iPALETTE_COLORS];
-} KS_TRUECOLORINFO,*PKS_TRUECOLORINFO;
-
-#define KS_WIDTHBYTES(bits)	((DWORD)(((bits)+31) & (~31)) / 8)
-#define KS_DIBWIDTHBYTES(bi)	(DWORD)KS_WIDTHBYTES((DWORD)(bi).biWidth *(DWORD)(bi).biBitCount)
-#define KS__DIBSIZE(bi)		(KS_DIBWIDTHBYTES(bi) *(DWORD)(bi).biHeight)
-#define KS_DIBSIZE(bi)		((bi).biHeight < 0 ? (-1)*(KS__DIBSIZE(bi)) : KS__DIBSIZE(bi))
-
-typedef LONGLONG REFERENCE_TIME;
-
-typedef struct tagKS_VIDEOINFOHEADER {
-  RECT rcSource;
-  RECT rcTarget;
-  DWORD dwBitRate;
-  DWORD dwBitErrorRate;
-  REFERENCE_TIME AvgTimePerFrame;
-  KS_BITMAPINFOHEADER bmiHeader;
-} KS_VIDEOINFOHEADER,*PKS_VIDEOINFOHEADER;
-
-typedef struct tagKS_VIDEOINFO {
-  RECT rcSource;
-  RECT rcTarget;
-  DWORD dwBitRate;
-  DWORD dwBitErrorRate;
-  REFERENCE_TIME AvgTimePerFrame;
-  KS_BITMAPINFOHEADER bmiHeader;
-  __MINGW_EXTENSION union {
-    KS_RGBQUAD bmiColors[KS_iPALETTE_COLORS];
-    DWORD dwBitMasks[KS_iMASK_COLORS];
-    KS_TRUECOLORINFO TrueColorInfo;
-  };
-} KS_VIDEOINFO,*PKS_VIDEOINFO;
-
-#define KS_SIZE_MASKS			(KS_iMASK_COLORS *sizeof(DWORD))
-#define KS_SIZE_PREHEADER		(FIELD_OFFSET(KS_VIDEOINFOHEADER,bmiHeader))
-
-#define KS_SIZE_VIDEOHEADER(pbmi)	((pbmi)->bmiHeader.biSize + KS_SIZE_PREHEADER)
-
-typedef struct tagKS_VBIINFOHEADER {
-  ULONG StartLine;
-  ULONG EndLine;
-  ULONG SamplingFrequency;
-  ULONG MinLineStartTime;
-  ULONG MaxLineStartTime;
-  ULONG ActualLineStartTime;
-  ULONG ActualLineEndTime;
-  ULONG VideoStandard;
-  ULONG SamplesPerLine;
-  ULONG StrideInBytes;
-  ULONG BufferSize;
-} KS_VBIINFOHEADER,*PKS_VBIINFOHEADER;
-
-#define KS_VBIDATARATE_NABTS		(5727272L)
-#define KS_VBIDATARATE_CC		(503493L)
-#define KS_VBISAMPLINGRATE_4X_NABTS	((long)(4*KS_VBIDATARATE_NABTS))
-#define KS_VBISAMPLINGRATE_47X_NABTS	((long)(27000000))
-#define KS_VBISAMPLINGRATE_5X_NABTS	((long)(5*KS_VBIDATARATE_NABTS))
-
-#define KS_47NABTS_SCALER		(KS_VBISAMPLINGRATE_47X_NABTS/(double)KS_VBIDATARATE_NABTS)
-
-typedef struct tagKS_AnalogVideoInfo {
-  RECT rcSource;
-  RECT rcTarget;
-  DWORD dwActiveWidth;
-  DWORD dwActiveHeight;
-  REFERENCE_TIME AvgTimePerFrame;
-} KS_ANALOGVIDEOINFO,*PKS_ANALOGVIDEOINFO;
-
-#define KS_TVTUNER_CHANGE_BEGIN_TUNE	0x0001L
-#define KS_TVTUNER_CHANGE_END_TUNE	0x0002L
-
-typedef struct tagKS_TVTUNER_CHANGE_INFO {
-  DWORD dwFlags;
-  DWORD dwCountryCode;
-  DWORD dwAnalogVideoStandard;
-  DWORD dwChannel;
-} KS_TVTUNER_CHANGE_INFO,*PKS_TVTUNER_CHANGE_INFO;
-
-typedef enum {
-  KS_MPEG2Level_Low,
-  KS_MPEG2Level_Main,
-  KS_MPEG2Level_High1440,
-  KS_MPEG2Level_High
-} KS_MPEG2Level;
-
-typedef enum {
-  KS_MPEG2Profile_Simple,
-  KS_MPEG2Profile_Main,
-  KS_MPEG2Profile_SNRScalable,
-  KS_MPEG2Profile_SpatiallyScalable,
-  KS_MPEG2Profile_High
-} KS_MPEG2Profile;
-
-#define KS_INTERLACE_IsInterlaced		0x00000001
-#define KS_INTERLACE_1FieldPerSample		0x00000002
-#define KS_INTERLACE_Field1First		0x00000004
-#define KS_INTERLACE_UNUSED			0x00000008
-#define KS_INTERLACE_FieldPatternMask		0x00000030
-#define KS_INTERLACE_FieldPatField1Only		0x00000000
-#define KS_INTERLACE_FieldPatField2Only		0x00000010
-#define KS_INTERLACE_FieldPatBothRegular	0x00000020
-#define KS_INTERLACE_FieldPatBothIrregular	0x00000030
-#define KS_INTERLACE_DisplayModeMask		0x000000c0
-#define KS_INTERLACE_DisplayModeBobOnly		0x00000000
-#define KS_INTERLACE_DisplayModeWeaveOnly	0x00000040
-#define KS_INTERLACE_DisplayModeBobOrWeave	0x00000080
-
-#define KS_MPEG2_DoPanScan			0x00000001
-#define KS_MPEG2_DVDLine21Field1		0x00000002
-#define KS_MPEG2_DVDLine21Field2		0x00000004
-#define KS_MPEG2_SourceIsLetterboxed		0x00000008
-#define KS_MPEG2_FilmCameraMode			0x00000010
-#define KS_MPEG2_LetterboxAnalogOut		0x00000020
-#define KS_MPEG2_DSS_UserData			0x00000040
-#define KS_MPEG2_DVB_UserData			0x00000080
-#define KS_MPEG2_27MhzTimebase			0x00000100
-
-typedef struct tagKS_VIDEOINFOHEADER2 {
-  RECT rcSource;
-  RECT rcTarget;
-  DWORD dwBitRate;
-  DWORD dwBitErrorRate;
-  REFERENCE_TIME AvgTimePerFrame;
-  DWORD dwInterlaceFlags;
-  DWORD dwCopyProtectFlags;
-  DWORD dwPictAspectRatioX;
-  DWORD dwPictAspectRatioY;
-  DWORD dwReserved1;
-  DWORD dwReserved2;
-  KS_BITMAPINFOHEADER bmiHeader;
-} KS_VIDEOINFOHEADER2,*PKS_VIDEOINFOHEADER2;
-
-typedef struct tagKS_MPEG1VIDEOINFO {
-  KS_VIDEOINFOHEADER hdr;
-  DWORD dwStartTimeCode;
-  DWORD cbSequenceHeader;
-  BYTE bSequenceHeader[1];
-} KS_MPEG1VIDEOINFO,*PKS_MPEG1VIDEOINFO;
-
-#define KS_MAX_SIZE_MPEG1_SEQUENCE_INFO	140
-#define KS_SIZE_MPEG1VIDEOINFO(pv)	(FIELD_OFFSET(KS_MPEG1VIDEOINFO,bSequenceHeader[0]) + (pv)->cbSequenceHeader)
-#define KS_MPEG1_SEQUENCE_INFO(pv)	((const BYTE *)(pv)->bSequenceHeader)
-
-typedef struct tagKS_MPEGVIDEOINFO2 {
-  KS_VIDEOINFOHEADER2 hdr;
-  DWORD dwStartTimeCode;
-  DWORD cbSequenceHeader;
-  DWORD dwProfile;
-  DWORD dwLevel;
-  DWORD dwFlags;
-  DWORD bSequenceHeader[1];
-} KS_MPEGVIDEOINFO2,*PKS_MPEGVIDEOINFO2;
-
-#define KS_SIZE_MPEGVIDEOINFO2(pv)	(FIELD_OFFSET(KS_MPEGVIDEOINFO2,bSequenceHeader[0]) + (pv)->cbSequenceHeader)
-#define KS_MPEG1_SEQUENCE_INFO(pv)	((const BYTE *)(pv)->bSequenceHeader)
-
-#define KS_MPEGAUDIOINFO_27MhzTimebase	0x00000001
-
-typedef struct tagKS_MPEAUDIOINFO {
-  DWORD dwFlags;
-  DWORD dwReserved1;
-  DWORD dwReserved2;
-  DWORD dwReserved3;
-} KS_MPEGAUDIOINFO,*PKS_MPEGAUDIOINFO;
-
-typedef struct tagKS_DATAFORMAT_VIDEOINFOHEADER {
-  KSDATAFORMAT DataFormat;
-  KS_VIDEOINFOHEADER VideoInfoHeader;
-} KS_DATAFORMAT_VIDEOINFOHEADER,*PKS_DATAFORMAT_VIDEOINFOHEADER;
-
-typedef struct tagKS_DATAFORMAT_VIDEOINFOHEADER2 {
-  KSDATAFORMAT DataFormat;
-  KS_VIDEOINFOHEADER2 VideoInfoHeader2;
-} KS_DATAFORMAT_VIDEOINFOHEADER2,*PKS_DATAFORMAT_VIDEOINFOHEADER2;
-
-typedef struct tagKS_DATAFORMAT_VIDEOINFO_PALETTE {
-  KSDATAFORMAT DataFormat;
-  KS_VIDEOINFO VideoInfo;
-} KS_DATAFORMAT_VIDEOINFO_PALETTE,*PKS_DATAFORMAT_VIDEOINFO_PALETTE;
-
-typedef struct tagKS_DATAFORMAT_VBIINFOHEADER {
-  KSDATAFORMAT DataFormat;
-  KS_VBIINFOHEADER VBIInfoHeader;
-} KS_DATAFORMAT_VBIINFOHEADER,*PKS_DATAFORMAT_VBIINFOHEADER;
-
-typedef struct _KS_VIDEO_STREAM_CONFIG_CAPS {
-  GUID guid;
-  ULONG VideoStandard;
-  SIZE InputSize;
-  SIZE MinCroppingSize;
-  SIZE MaxCroppingSize;
-  int CropGranularityX;
-  int CropGranularityY;
-  int CropAlignX;
-  int CropAlignY;
-  SIZE MinOutputSize;
-  SIZE MaxOutputSize;
-  int OutputGranularityX;
-  int OutputGranularityY;
-  int StretchTapsX;
-  int StretchTapsY;
-  int ShrinkTapsX;
-  int ShrinkTapsY;
-  LONGLONG MinFrameInterval;
-  LONGLONG MaxFrameInterval;
-  LONG MinBitsPerSecond;
-  LONG MaxBitsPerSecond;
-} KS_VIDEO_STREAM_CONFIG_CAPS,*PKS_VIDEO_STREAM_CONFIG_CAPS;
-
-typedef struct tagKS_DATARANGE_VIDEO {
-  KSDATARANGE DataRange;
-  WINBOOL bFixedSizeSamples;
-  WINBOOL bTemporalCompression;
-  DWORD StreamDescriptionFlags;
-  DWORD MemoryAllocationFlags;
-  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
-  KS_VIDEOINFOHEADER VideoInfoHeader;
-} KS_DATARANGE_VIDEO,*PKS_DATARANGE_VIDEO;
-
-typedef struct tagKS_DATARANGE_VIDEO2 {
-  KSDATARANGE DataRange;
-  WINBOOL bFixedSizeSamples;
-  WINBOOL bTemporalCompression;
-  DWORD StreamDescriptionFlags;
-  DWORD MemoryAllocationFlags;
-  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
-  KS_VIDEOINFOHEADER2 VideoInfoHeader;
-} KS_DATARANGE_VIDEO2,*PKS_DATARANGE_VIDEO2;
-
-typedef struct tagKS_DATARANGE_MPEG1_VIDEO {
-  KSDATARANGE DataRange;
-  WINBOOL bFixedSizeSamples;
-  WINBOOL bTemporalCompression;
-  DWORD StreamDescriptionFlags;
-  DWORD MemoryAllocationFlags;
-  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
-  KS_MPEG1VIDEOINFO VideoInfoHeader;
-} KS_DATARANGE_MPEG1_VIDEO,*PKS_DATARANGE_MPEG1_VIDEO;
-
-typedef struct tagKS_DATARANGE_MPEG2_VIDEO {
-  KSDATARANGE DataRange;
-  WINBOOL bFixedSizeSamples;
-  WINBOOL bTemporalCompression;
-  DWORD StreamDescriptionFlags;
-  DWORD MemoryAllocationFlags;
-  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
-  KS_MPEGVIDEOINFO2 VideoInfoHeader;
-} KS_DATARANGE_MPEG2_VIDEO,*PKS_DATARANGE_MPEG2_VIDEO;
-
-typedef struct tagKS_DATARANGE_VIDEO_PALETTE {
-  KSDATARANGE DataRange;
-  WINBOOL bFixedSizeSamples;
-  WINBOOL bTemporalCompression;
-  DWORD StreamDescriptionFlags;
-  DWORD MemoryAllocationFlags;
-  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
-  KS_VIDEOINFO VideoInfo;
-} KS_DATARANGE_VIDEO_PALETTE,*PKS_DATARANGE_VIDEO_PALETTE;
-
-typedef struct tagKS_DATARANGE_VIDEO_VBI {
-  KSDATARANGE DataRange;
-  WINBOOL bFixedSizeSamples;
-  WINBOOL bTemporalCompression;
-  DWORD StreamDescriptionFlags;
-  DWORD MemoryAllocationFlags;
-  KS_VIDEO_STREAM_CONFIG_CAPS ConfigCaps;
-  KS_VBIINFOHEADER VBIInfoHeader;
-} KS_DATARANGE_VIDEO_VBI,*PKS_DATARANGE_VIDEO_VBI;
-
-typedef struct tagKS_DATARANGE_ANALOGVIDEO {
-  KSDATARANGE DataRange;
-  KS_ANALOGVIDEOINFO AnalogVideoInfo;
-} KS_DATARANGE_ANALOGVIDEO,*PKS_DATARANGE_ANALOGVIDEO;
-
-#define KS_VIDEOSTREAM_PREVIEW		0x0001
-#define KS_VIDEOSTREAM_CAPTURE		0x0002
-#define KS_VIDEOSTREAM_VBI		0x0010
-#define KS_VIDEOSTREAM_NABTS		0x0020
-#define KS_VIDEOSTREAM_CC		0x0100
-#define KS_VIDEOSTREAM_EDS		0x0200
-#define KS_VIDEOSTREAM_TELETEXT		0x0400
-#define KS_VIDEOSTREAM_STILL		0x1000
-#define KS_VIDEOSTREAM_IS_VPE		0x8000
-
-#define KS_VIDEO_ALLOC_VPE_SYSTEM	0x0001
-#define KS_VIDEO_ALLOC_VPE_DISPLAY	0x0002
-#define KS_VIDEO_ALLOC_VPE_AGP		0x0004
-
-#define STATIC_KSPROPSETID_VBICAP_PROPERTIES				\
-	0xf162c607,0x7b35,0x496f,0xad,0x7f,0x2d,0xca,0x3b,0x46,0xb7,0x18
-DEFINE_GUIDSTRUCT("F162C607-7B35-496f-AD7F-2DCA3B46B718",KSPROPSETID_VBICAP_PROPERTIES);
-#define KSPROPSETID_VBICAP_PROPERTIES DEFINE_GUIDNAMED(KSPROPSETID_VBICAP_PROPERTIES)
-
-typedef enum {
-  KSPROPERTY_VBICAP_PROPERTIES_PROTECTION = 0x01
-} KSPROPERTY_VBICAP;
-
-typedef struct _VBICAP_PROPERTIES_PROTECTION_S {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  ULONG Status;
-} VBICAP_PROPERTIES_PROTECTION_S,*PVBICAP_PROPERTIES_PROTECTION_S;
-
-#define KS_VBICAP_PROTECTION_MV_PRESENT				0x0001L
-#define KS_VBICAP_PROTECTION_MV_HARDWARE			0x0002L
-#define KS_VBICAP_PROTECTION_MV_DETECTED			0x0004L
-
-#define KS_NABTS_GROUPID_ORIGINAL_CONTENT_BASE			0x800
-#define KS_NABTS_GROUPID_ORIGINAL_CONTENT_ADVERTISER_BASE	0x810
-
-#define KS_NABTS_GROUPID_PRODUCTION_COMPANY_CONTENT_BASE	0x820
-#define KS_NABTS_GROUPID_PRODUCTION_COMPANY_ADVERTISER_BASE	0x830
-
-#define KS_NABTS_GROUPID_SYNDICATED_SHOW_CONTENT_BASE		0x840
-#define KS_NABTS_GROUPID_SYNDICATED_SHOW_ADVERTISER_BASE	0x850
-
-#define KS_NABTS_GROUPID_NETWORK_WIDE_CONTENT_BASE		0x860
-#define KS_NABTS_GROUPID_NETWORK_WIDE_ADVERTISER_BASE		0x870
-
-#define KS_NABTS_GROUPID_TELEVISION_STATION_CONTENT_BASE	0x880
-#define KS_NABTS_GROUPID_TELEVISION_STATION_ADVERTISER_BASE	0x890
-
-#define KS_NABTS_GROUPID_LOCAL_CABLE_SYSTEM_CONTENT_BASE	0x8A0
-#define KS_NABTS_GROUPID_LOCAL_CABLE_SYSTEM_ADVERTISER_BASE	0x8B0
-
-#define KS_NABTS_GROUPID_MICROSOFT_RESERVED_TEST_DATA_BASE	0x8F0
-
-#define STATIC_KSDATAFORMAT_TYPE_NABTS					\
-	0xe757bca0,0x39ac,0x11d1,0xa9,0xf5,0x0,0xc0,0x4f,0xbb,0xde,0x8f
-DEFINE_GUIDSTRUCT("E757BCA0-39AC-11d1-A9F5-00C04FBBDE8F",KSDATAFORMAT_TYPE_NABTS);
-#define KSDATAFORMAT_TYPE_NABTS DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_NABTS)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_NABTS_FEC				\
-	0xe757bca1,0x39ac,0x11d1,0xa9,0xf5,0x0,0xc0,0x4f,0xbb,0xde,0x8f
-DEFINE_GUIDSTRUCT("E757BCA1-39AC-11d1-A9F5-00C04FBBDE8F",KSDATAFORMAT_SUBTYPE_NABTS_FEC);
-#define KSDATAFORMAT_SUBTYPE_NABTS_FEC DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_NABTS_FEC)
-
-#define MAX_NABTS_VBI_LINES_PER_FIELD	11
-#define NABTS_LINES_PER_BUNDLE		16
-#define NABTS_PAYLOAD_PER_LINE		28
-#define NABTS_BYTES_PER_LINE		36
-
-typedef struct _NABTSFEC_BUFFER {
-  ULONG dataSize;
-  USHORT groupID;
-  USHORT Reserved;
-  UCHAR data[NABTS_LINES_PER_BUNDLE *NABTS_PAYLOAD_PER_LINE];
-} NABTSFEC_BUFFER,*PNABTSFEC_BUFFER;
-
-#define STATIC_KSPROPSETID_VBICodecFiltering				\
-	0xcafeb0caL,0x8715,0x11d0,0xbd,0x6a,0x00,0x35,0xc0,0xed,0xba,0xbe
-DEFINE_GUIDSTRUCT("cafeb0ca-8715-11d0-bd6a-0035c0edbabe",KSPROPSETID_VBICodecFiltering);
-#define KSPROPSETID_VBICodecFiltering DEFINE_GUIDNAMED(KSPROPSETID_VBICodecFiltering)
-
-typedef enum {
-  KSPROPERTY_VBICODECFILTERING_SCANLINES_REQUESTED_BIT_ARRAY = 0x01,
-  KSPROPERTY_VBICODECFILTERING_SCANLINES_DISCOVERED_BIT_ARRAY,
-  KSPROPERTY_VBICODECFILTERING_SUBSTREAMS_REQUESTED_BIT_ARRAY,
-  KSPROPERTY_VBICODECFILTERING_SUBSTREAMS_DISCOVERED_BIT_ARRAY,
-  KSPROPERTY_VBICODECFILTERING_STATISTICS
-} KSPROPERTY_VBICODECFILTERING;
-
-typedef struct _VBICODECFILTERING_SCANLINES {
-  DWORD DwordBitArray[32];
-} VBICODECFILTERING_SCANLINES,*PVBICODECFILTERING_SCANLINES;
-
-typedef struct _VBICODECFILTERING_NABTS_SUBSTREAMS {
-  DWORD SubstreamMask[128];
-} VBICODECFILTERING_NABTS_SUBSTREAMS,*PVBICODECFILTERING_NABTS_SUBSTREAMS;
-
-typedef struct _VBICODECFILTERING_CC_SUBSTREAMS {
-  DWORD SubstreamMask;
-} VBICODECFILTERING_CC_SUBSTREAMS,*PVBICODECFILTERING_CC_SUBSTREAMS;
-
-#define KS_CC_SUBSTREAM_ODD		0x0001L
-#define KS_CC_SUBSTREAM_EVEN		0x0002L
-
-#define KS_CC_SUBSTREAM_FIELD1_MASK	0x00F0L
-#define KS_CC_SUBSTREAM_SERVICE_CC1	0x0010L
-#define KS_CC_SUBSTREAM_SERVICE_CC2	0x0020L
-#define KS_CC_SUBSTREAM_SERVICE_T1	0x0040L
-#define KS_CC_SUBSTREAM_SERVICE_T2	0x0080L
-
-#define KS_CC_SUBSTREAM_FIELD2_MASK	0x1F00L
-#define KS_CC_SUBSTREAM_SERVICE_CC3	0x0100L
-#define KS_CC_SUBSTREAM_SERVICE_CC4	0x0200L
-#define KS_CC_SUBSTREAM_SERVICE_T3	0x0400L
-#define KS_CC_SUBSTREAM_SERVICE_T4	0x0800L
-#define KS_CC_SUBSTREAM_SERVICE_XDS	0x1000L
-
-#define CC_MAX_HW_DECODE_LINES		12
-typedef struct _CC_BYTE_PAIR {
-  BYTE Decoded[2];
-  USHORT Reserved;
-} CC_BYTE_PAIR,*PCC_BYTE_PAIR;
-
-typedef struct _CC_HW_FIELD {
-  VBICODECFILTERING_SCANLINES ScanlinesRequested;
-  ULONG fieldFlags;
-  LONGLONG PictureNumber;
-  CC_BYTE_PAIR Lines[CC_MAX_HW_DECODE_LINES];
-} CC_HW_FIELD,*PCC_HW_FIELD;
-
-#ifndef PACK_PRAGMAS_NOT_SUPPORTED
-#include <pshpack1.h>
-#endif
-typedef struct _NABTS_BUFFER_LINE {
-  BYTE Confidence;
-  BYTE Bytes[NABTS_BYTES_PER_LINE];
-} NABTS_BUFFER_LINE,*PNABTS_BUFFER_LINE;
-
-#define NABTS_BUFFER_PICTURENUMBER_SUPPORT	1
-typedef struct _NABTS_BUFFER {
-  VBICODECFILTERING_SCANLINES ScanlinesRequested;
-  LONGLONG PictureNumber;
-  NABTS_BUFFER_LINE NabtsLines[MAX_NABTS_VBI_LINES_PER_FIELD];
-} NABTS_BUFFER,*PNABTS_BUFFER;
-#ifndef PACK_PRAGMAS_NOT_SUPPORTED
-#include <poppack.h>
-#endif
-
-#define WST_TVTUNER_CHANGE_BEGIN_TUNE	0x1000L
-#define WST_TVTUNER_CHANGE_END_TUNE	0x2000L
-
-#define MAX_WST_VBI_LINES_PER_FIELD	17
-#define WST_BYTES_PER_LINE		42
-
-typedef struct _WST_BUFFER_LINE {
-  BYTE Confidence;
-  BYTE Bytes[WST_BYTES_PER_LINE];
-} WST_BUFFER_LINE,*PWST_BUFFER_LINE;
-
-typedef struct _WST_BUFFER {
-  VBICODECFILTERING_SCANLINES ScanlinesRequested;
-  WST_BUFFER_LINE WstLines[MAX_WST_VBI_LINES_PER_FIELD];
-} WST_BUFFER,*PWST_BUFFER;
-
-typedef struct _VBICODECFILTERING_STATISTICS_COMMON {
-  DWORD InputSRBsProcessed;
-  DWORD OutputSRBsProcessed;
-  DWORD SRBsIgnored;
-  DWORD InputSRBsMissing;
-  DWORD OutputSRBsMissing;
-  DWORD OutputFailures;
-  DWORD InternalErrors;
-  DWORD ExternalErrors;
-  DWORD InputDiscontinuities;
-  DWORD DSPFailures;
-  DWORD TvTunerChanges;
-  DWORD VBIHeaderChanges;
-  DWORD LineConfidenceAvg;
-  DWORD BytesOutput;
-} VBICODECFILTERING_STATISTICS_COMMON,*PVBICODECFILTERING_STATISTICS_COMMON;
-
-typedef struct _VBICODECFILTERING_STATISTICS_COMMON_PIN {
-  DWORD SRBsProcessed;
-  DWORD SRBsIgnored;
-  DWORD SRBsMissing;
-  DWORD InternalErrors;
-  DWORD ExternalErrors;
-  DWORD Discontinuities;
-  DWORD LineConfidenceAvg;
-  DWORD BytesOutput;
-} VBICODECFILTERING_STATISTICS_COMMON_PIN,*PVBICODECFILTERING_STATISTICS_COMMON_PIN;
-
-typedef struct _VBICODECFILTERING_STATISTICS_NABTS {
-  VBICODECFILTERING_STATISTICS_COMMON Common;
-  DWORD FECBundleBadLines;
-  DWORD FECQueueOverflows;
-  DWORD FECCorrectedLines;
-  DWORD FECUncorrectableLines;
-  DWORD BundlesProcessed;
-  DWORD BundlesSent2IP;
-  DWORD FilteredLines;
-} VBICODECFILTERING_STATISTICS_NABTS,*PVBICODECFILTERING_STATISTICS_NABTS;
-
-typedef struct _VBICODECFILTERING_STATISTICS_NABTS_PIN {
-  VBICODECFILTERING_STATISTICS_COMMON_PIN Common;
-} VBICODECFILTERING_STATISTICS_NABTS_PIN,*PVBICODECFILTERING_STATISTICS_NABTS_PIN;
-
-typedef struct _VBICODECFILTERING_STATISTICS_CC {
-  VBICODECFILTERING_STATISTICS_COMMON Common;
-} VBICODECFILTERING_STATISTICS_CC,*PVBICODECFILTERING_STATISTICS_CC;
-
-typedef struct _VBICODECFILTERING_STATISTICS_CC_PIN {
-  VBICODECFILTERING_STATISTICS_COMMON_PIN Common;
-} VBICODECFILTERING_STATISTICS_CC_PIN,*PVBICODECFILTERING_STATISTICS_CC_PIN;
-
-typedef struct _VBICODECFILTERING_STATISTICS_TELETEXT {
-  VBICODECFILTERING_STATISTICS_COMMON Common;
-} VBICODECFILTERING_STATISTICS_TELETEXT,*PVBICODECFILTERING_STATISTICS_TELETEXT;
-
-typedef struct _VBICODECFILTERING_STATISTICS_TELETEXT_PIN {
-  VBICODECFILTERING_STATISTICS_COMMON_PIN Common;
-} VBICODECFILTERING_STATISTICS_TELETEXT_PIN,*PVBICODECFILTERING_STATISTICS_TELETEXT_PIN;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_SCANLINES Scanlines;
-} KSPROPERTY_VBICODECFILTERING_SCANLINES_S,*PKSPROPERTY_VBICODECFILTERING_SCANLINES_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_NABTS_SUBSTREAMS Substreams;
-} KSPROPERTY_VBICODECFILTERING_NABTS_SUBSTREAMS_S,*PKSPROPERTY_VBICODECFILTERING_NABTS_SUBSTREAMS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_CC_SUBSTREAMS Substreams;
-} KSPROPERTY_VBICODECFILTERING_CC_SUBSTREAMS_S,*PKSPROPERTY_VBICODECFILTERING_CC_SUBSTREAMS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_STATISTICS_COMMON Statistics;
-} KSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_STATISTICS_COMMON_PIN Statistics;
-} KSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_PIN_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_COMMON_PIN_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_STATISTICS_NABTS Statistics;
-} KSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_STATISTICS_NABTS_PIN Statistics;
-} KSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_PIN_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_NABTS_PIN_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_STATISTICS_CC Statistics;
-} KSPROPERTY_VBICODECFILTERING_STATISTICS_CC_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_CC_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  VBICODECFILTERING_STATISTICS_CC_PIN Statistics;
-} KSPROPERTY_VBICODECFILTERING_STATISTICS_CC_PIN_S,*PKSPROPERTY_VBICODECFILTERING_STATISTICS_CC_PIN_S;
-
-#define STATIC_PINNAME_VIDEO_CAPTURE					\
-	0xfb6c4281,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-#define STATIC_PINNAME_CAPTURE STATIC_PINNAME_VIDEO_CAPTURE
-DEFINE_GUIDSTRUCT("FB6C4281-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_CAPTURE);
-#define PINNAME_VIDEO_CAPTURE DEFINE_GUIDNAMED(PINNAME_VIDEO_CAPTURE)
-#define PINNAME_CAPTURE PINNAME_VIDEO_CAPTURE
-
-#define STATIC_PINNAME_VIDEO_CC_CAPTURE					\
-	0x1aad8061,0x12d,0x11d2,0xb4,0xb1,0x0,0xa0,0xd1,0x2,0xcf,0xbe
-#define STATIC_PINNAME_CC_CAPTURE STATIC_PINNAME_VIDEO_CC_CAPTURE
-DEFINE_GUIDSTRUCT("1AAD8061-012D-11d2-B4B1-00A0D102CFBE",PINNAME_VIDEO_CC_CAPTURE);
-#define PINNAME_VIDEO_CC_CAPTURE DEFINE_GUIDNAMED(PINNAME_VIDEO_CC_CAPTURE)
-
-#define STATIC_PINNAME_VIDEO_NABTS_CAPTURE				\
-	0x29703660,0x498a,0x11d2,0xb4,0xb1,0x0,0xa0,0xd1,0x2,0xcf,0xbe
-#define STATIC_PINNAME_NABTS_CAPTURE STATIC_PINNAME_VIDEO_NABTS_CAPTURE
-DEFINE_GUIDSTRUCT("29703660-498A-11d2-B4B1-00A0D102CFBE",PINNAME_VIDEO_NABTS_CAPTURE);
-#define PINNAME_VIDEO_NABTS_CAPTURE DEFINE_GUIDNAMED(PINNAME_VIDEO_NABTS_CAPTURE)
-
-#define STATIC_PINNAME_VIDEO_PREVIEW					\
-	0xfb6c4282,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-#define STATIC_PINNAME_PREVIEW STATIC_PINNAME_VIDEO_PREVIEW
-DEFINE_GUIDSTRUCT("FB6C4282-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_PREVIEW);
-#define PINNAME_VIDEO_PREVIEW DEFINE_GUIDNAMED(PINNAME_VIDEO_PREVIEW)
-#define PINNAME_PREVIEW PINNAME_VIDEO_PREVIEW
-
-#define STATIC_PINNAME_VIDEO_ANALOGVIDEOIN				\
-	0xfb6c4283,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4283-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_ANALOGVIDEOIN);
-#define PINNAME_VIDEO_ANALOGVIDEOIN DEFINE_GUIDNAMED(PINNAME_VIDEO_ANALOGVIDEOIN)
-
-#define STATIC_PINNAME_VIDEO_VBI					\
-	0xfb6c4284,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4284-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_VBI);
-#define PINNAME_VIDEO_VBI DEFINE_GUIDNAMED(PINNAME_VIDEO_VBI)
-
-#define STATIC_PINNAME_VIDEO_VIDEOPORT					\
-	0xfb6c4285,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4285-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_VIDEOPORT);
-#define PINNAME_VIDEO_VIDEOPORT DEFINE_GUIDNAMED(PINNAME_VIDEO_VIDEOPORT)
-
-#define STATIC_PINNAME_VIDEO_NABTS					\
-	0xfb6c4286,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4286-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_NABTS);
-#define PINNAME_VIDEO_NABTS DEFINE_GUIDNAMED(PINNAME_VIDEO_NABTS)
-
-#define STATIC_PINNAME_VIDEO_EDS					\
-	0xfb6c4287,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4287-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_EDS);
-#define PINNAME_VIDEO_EDS DEFINE_GUIDNAMED(PINNAME_VIDEO_EDS)
-
-#define STATIC_PINNAME_VIDEO_TELETEXT					\
-	0xfb6c4288,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4288-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_TELETEXT);
-#define PINNAME_VIDEO_TELETEXT DEFINE_GUIDNAMED(PINNAME_VIDEO_TELETEXT)
-
-#define STATIC_PINNAME_VIDEO_CC						\
-	0xfb6c4289,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C4289-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_CC);
-#define PINNAME_VIDEO_CC DEFINE_GUIDNAMED(PINNAME_VIDEO_CC)
-
-#define STATIC_PINNAME_VIDEO_STILL					\
-	0xfb6c428A,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C428A-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_STILL);
-#define PINNAME_VIDEO_STILL DEFINE_GUIDNAMED(PINNAME_VIDEO_STILL)
-
-#define STATIC_PINNAME_VIDEO_TIMECODE					\
-	0xfb6c428B,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C428B-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_TIMECODE);
-#define PINNAME_VIDEO_TIMECODE DEFINE_GUIDNAMED(PINNAME_VIDEO_TIMECODE)
-
-#define STATIC_PINNAME_VIDEO_VIDEOPORT_VBI				\
-	0xfb6c428C,0x353,0x11d1,0x90,0x5f,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("FB6C428C-0353-11d1-905F-0000C0CC16BA",PINNAME_VIDEO_VIDEOPORT_VBI);
-#define PINNAME_VIDEO_VIDEOPORT_VBI DEFINE_GUIDNAMED(PINNAME_VIDEO_VIDEOPORT_VBI)
-
-#define KS_VIDEO_FLAG_FRAME		0x0000L
-#define KS_VIDEO_FLAG_FIELD1		0x0001L
-#define KS_VIDEO_FLAG_FIELD2		0x0002L
-
-#define KS_VIDEO_FLAG_I_FRAME		0x0000L
-#define KS_VIDEO_FLAG_P_FRAME		0x0010L
-#define KS_VIDEO_FLAG_B_FRAME		0x0020L
-
-typedef struct tagKS_FRAME_INFO {
-  ULONG ExtendedHeaderSize;
-  DWORD dwFrameFlags;
-  LONGLONG PictureNumber;
-  LONGLONG DropCount;
-  HANDLE hDirectDraw;
-  HANDLE hSurfaceHandle;
-  RECT DirectDrawRect;
-
-  DWORD Reserved1;
-  DWORD Reserved2;
-  DWORD Reserved3;
-  DWORD Reserved4;
-} KS_FRAME_INFO,*PKS_FRAME_INFO;
-
-#define KS_VBI_FLAG_FIELD1		0x0001L
-#define KS_VBI_FLAG_FIELD2		0x0002L
-
-#define KS_VBI_FLAG_MV_PRESENT		0x0100L
-#define KS_VBI_FLAG_MV_HARDWARE		0x0200L
-#define KS_VBI_FLAG_MV_DETECTED		0x0400L
-
-#define KS_VBI_FLAG_TVTUNER_CHANGE	0x0010L
-#define KS_VBI_FLAG_VBIINFOHEADER_CHANGE 0x0020L
-
-typedef struct tagKS_VBI_FRAME_INFO {
-  ULONG ExtendedHeaderSize;
-  DWORD dwFrameFlags;
-  LONGLONG PictureNumber;
-  LONGLONG DropCount;
-  DWORD dwSamplingFrequency;
-  KS_TVTUNER_CHANGE_INFO TvTunerChangeInfo;
-  KS_VBIINFOHEADER VBIInfoHeader;
-} KS_VBI_FRAME_INFO,*PKS_VBI_FRAME_INFO;
-
-typedef enum
-{
-  KS_AnalogVideo_None = 0x00000000,
-  KS_AnalogVideo_NTSC_M = 0x00000001,
-  KS_AnalogVideo_NTSC_M_J = 0x00000002,
-  KS_AnalogVideo_NTSC_433 = 0x00000004,
-  KS_AnalogVideo_PAL_B = 0x00000010,
-  KS_AnalogVideo_PAL_D = 0x00000020,
-  KS_AnalogVideo_PAL_G = 0x00000040,
-  KS_AnalogVideo_PAL_H = 0x00000080,
-  KS_AnalogVideo_PAL_I = 0x00000100,
-  KS_AnalogVideo_PAL_M = 0x00000200,
-  KS_AnalogVideo_PAL_N = 0x00000400,
-  KS_AnalogVideo_PAL_60 = 0x00000800,
-  KS_AnalogVideo_SECAM_B = 0x00001000,
-  KS_AnalogVideo_SECAM_D = 0x00002000,
-  KS_AnalogVideo_SECAM_G = 0x00004000,
-  KS_AnalogVideo_SECAM_H = 0x00008000,
-  KS_AnalogVideo_SECAM_K = 0x00010000,
-  KS_AnalogVideo_SECAM_K1 = 0x00020000,
-  KS_AnalogVideo_SECAM_L = 0x00040000,
-  KS_AnalogVideo_SECAM_L1 = 0x00080000,
-  KS_AnalogVideo_PAL_N_COMBO = 0x00100000
-} KS_AnalogVideoStandard;
-
-#define KS_AnalogVideo_NTSC_Mask	0x00000007
-#define KS_AnalogVideo_PAL_Mask		0x00100FF0
-#define KS_AnalogVideo_SECAM_Mask	0x000FF000
-
-#define STATIC_PROPSETID_ALLOCATOR_CONTROL				\
-	0x53171960,0x148e,0x11d2,0x99,0x79,0x0,0x0,0xc0,0xcc,0x16,0xba
-DEFINE_GUIDSTRUCT("53171960-148E-11d2-9979-0000C0CC16BA",PROPSETID_ALLOCATOR_CONTROL);
-#define PROPSETID_ALLOCATOR_CONTROL DEFINE_GUIDNAMED(PROPSETID_ALLOCATOR_CONTROL)
-
-typedef enum {
-  KSPROPERTY_ALLOCATOR_CONTROL_HONOR_COUNT,
-  KSPROPERTY_ALLOCATOR_CONTROL_SURFACE_SIZE,
-  KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_CAPS,
-  KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_INTERLEAVE
-} KSPROPERTY_ALLOCATOR_CONTROL;
-
-typedef struct {
-  ULONG CX;
-  ULONG CY;
-} KSPROPERTY_ALLOCATOR_CONTROL_SURFACE_SIZE_S,*PKSPROPERTY_ALLOCATOR_CONTROL_SURFACE_SIZE_S;
-
-typedef struct {
-  ULONG InterleavedCapSupported;
-} KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_CAPS_S,*PKSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_CAPS_S;
-
-typedef struct {
-  ULONG InterleavedCapPossible;
-} KSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_INTERLEAVE_S,*PKSPROPERTY_ALLOCATOR_CONTROL_CAPTURE_INTERLEAVE_S;
-
-#define STATIC_PROPSETID_VIDCAP_VIDEOPROCAMP				\
-	0xC6E13360L,0x30AC,0x11d0,0xa1,0x8c,0x00,0xA0,0xC9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("C6E13360-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_VIDEOPROCAMP);
-#define PROPSETID_VIDCAP_VIDEOPROCAMP DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOPROCAMP)
-
-typedef enum {
-  KSPROPERTY_VIDEOPROCAMP_BRIGHTNESS,
-  KSPROPERTY_VIDEOPROCAMP_CONTRAST,
-  KSPROPERTY_VIDEOPROCAMP_HUE,
-  KSPROPERTY_VIDEOPROCAMP_SATURATION,
-  KSPROPERTY_VIDEOPROCAMP_SHARPNESS,
-  KSPROPERTY_VIDEOPROCAMP_GAMMA,
-  KSPROPERTY_VIDEOPROCAMP_COLORENABLE,
-  KSPROPERTY_VIDEOPROCAMP_WHITEBALANCE,
-  KSPROPERTY_VIDEOPROCAMP_BACKLIGHT_COMPENSATION,
-  KSPROPERTY_VIDEOPROCAMP_GAIN,
-  KSPROPERTY_VIDEOPROCAMP_DIGITAL_MULTIPLIER,
-  KSPROPERTY_VIDEOPROCAMP_DIGITAL_MULTIPLIER_LIMIT,
-  KSPROPERTY_VIDEOPROCAMP_WHITEBALANCE_COMPONENT,
-  KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY
-} KSPROPERTY_VIDCAP_VIDEOPROCAMP;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_VIDEOPROCAMP_S,*PKSPROPERTY_VIDEOPROCAMP_S;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_VIDEOPROCAMP_NODE_S,*PKSPROPERTY_VIDEOPROCAMP_NODE_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG Value1;
-  ULONG Flags;
-  ULONG Capabilities;
-  LONG Value2;
-} KSPROPERTY_VIDEOPROCAMP_S2,*PKSPROPERTY_VIDEOPROCAMP_S2;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  LONG Value1;
-  ULONG Flags;
-  ULONG Capabilities;
-  LONG Value2;
-} KSPROPERTY_VIDEOPROCAMP_NODE_S2,*PKSPROPERTY_VIDEOPROCAMP_NODE_S2;
-
-#define KSPROPERTY_VIDEOPROCAMP_FLAGS_AUTO	0X0001L
-#define KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL	0X0002L
-
-#define STATIC_PROPSETID_VIDCAP_SELECTOR				\
-	0x1ABDAECA,0x68B6,0x4F83,0x93,0x71,0xB4,0x13,0x90,0x7C,0x7B,0x9F
-DEFINE_GUIDSTRUCT("1ABDAECA-68B6-4F83-9371-B413907C7B9F",PROPSETID_VIDCAP_SELECTOR);
-#define PROPSETID_VIDCAP_SELECTOR DEFINE_GUIDNAMED(PROPSETID_VIDCAP_SELECTOR)
-
-typedef enum {
-  KSPROPERTY_SELECTOR_SOURCE_NODE_ID,
-  KSPROPERTY_SELECTOR_NUM_SOURCES
-} KSPROPERTY_VIDCAP_SELECTOR,*PKSPROPERTY_VIDCAP_SELECTOR;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_SELECTOR_S,*PKSPROPERTY_SELECTOR_S;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_SELECTOR_NODE_S,*PKSPROPERTY_SELECTOR_NODE_S;
-
-#define STATIC_PROPSETID_TUNER						\
-	0x6a2e0605L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0605-28e4-11d0-a18c-00a0c9118956",PROPSETID_TUNER);
-#define PROPSETID_TUNER DEFINE_GUIDNAMED(PROPSETID_TUNER)
-
-typedef enum {
-  KSPROPERTY_TUNER_CAPS,
-  KSPROPERTY_TUNER_MODE_CAPS,
-  KSPROPERTY_TUNER_MODE,
-  KSPROPERTY_TUNER_STANDARD,
-  KSPROPERTY_TUNER_FREQUENCY,
-  KSPROPERTY_TUNER_INPUT,
-  KSPROPERTY_TUNER_STATUS,
-  KSPROPERTY_TUNER_IF_MEDIUM
-} KSPROPERTY_TUNER;
-
-typedef enum {
-  KSPROPERTY_TUNER_MODE_TV = 0X0001,
-  KSPROPERTY_TUNER_MODE_FM_RADIO = 0X0002,
-  KSPROPERTY_TUNER_MODE_AM_RADIO = 0X0004,
-  KSPROPERTY_TUNER_MODE_DSS = 0X0008,
-  KSPROPERTY_TUNER_MODE_ATSC = 0X0010
-} KSPROPERTY_TUNER_MODES;
-
-typedef enum {
-  KS_TUNER_TUNING_EXACT = 1,
-  KS_TUNER_TUNING_FINE,
-  KS_TUNER_TUNING_COARSE
-} KS_TUNER_TUNING_FLAGS;
-
-typedef enum {
-  KS_TUNER_STRATEGY_PLL = 0X01,
-  KS_TUNER_STRATEGY_SIGNAL_STRENGTH = 0X02,
-  KS_TUNER_STRATEGY_DRIVER_TUNES = 0X04
-} KS_TUNER_STRATEGY;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG ModesSupported;
-  KSPIN_MEDIUM VideoMedium;
-  KSPIN_MEDIUM TVAudioMedium;
-  KSPIN_MEDIUM RadioAudioMedium;
-} KSPROPERTY_TUNER_CAPS_S,*PKSPROPERTY_TUNER_CAPS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  KSPIN_MEDIUM IFMedium;
-} KSPROPERTY_TUNER_IF_MEDIUM_S,*PKSPROPERTY_TUNER_IF_MEDIUM_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Mode;
-  ULONG StandardsSupported;
-  ULONG MinFrequency;
-  ULONG MaxFrequency;
-  ULONG TuningGranularity;
-  ULONG NumberOfInputs;
-  ULONG SettlingTime;
-  ULONG Strategy;
-} KSPROPERTY_TUNER_MODE_CAPS_S,*PKSPROPERTY_TUNER_MODE_CAPS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Mode;
-} KSPROPERTY_TUNER_MODE_S,*PKSPROPERTY_TUNER_MODE_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Frequency;
-  ULONG LastFrequency;
-  ULONG TuningFlags;
-  ULONG VideoSubChannel;
-  ULONG AudioSubChannel;
-  ULONG Channel;
-  ULONG Country;
-} KSPROPERTY_TUNER_FREQUENCY_S,*PKSPROPERTY_TUNER_FREQUENCY_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Standard;
-} KSPROPERTY_TUNER_STANDARD_S,*PKSPROPERTY_TUNER_STANDARD_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG InputIndex;
-} KSPROPERTY_TUNER_INPUT_S,*PKSPROPERTY_TUNER_INPUT_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG CurrentFrequency;
-  ULONG PLLOffset;
-  ULONG SignalStrength;
-  ULONG Busy;
-} KSPROPERTY_TUNER_STATUS_S,*PKSPROPERTY_TUNER_STATUS_S;
-
-#define STATIC_EVENTSETID_TUNER						\
-	0x6a2e0606L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0606-28e4-11d0-a18c-00a0c9118956",EVENTSETID_TUNER);
-#define EVENTSETID_TUNER DEFINE_GUIDNAMED(EVENTSETID_TUNER)
-
-typedef enum {
-  KSEVENT_TUNER_CHANGED
-} KSEVENT_TUNER;
-
-#define STATIC_KSNODETYPE_VIDEO_STREAMING				\
-	0xDFF229E1L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E1-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_STREAMING);
-#define KSNODETYPE_VIDEO_STREAMING DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_STREAMING)
-
-#define STATIC_KSNODETYPE_VIDEO_INPUT_TERMINAL				\
-	0xDFF229E2L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E2-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_INPUT_TERMINAL);
-#define KSNODETYPE_VIDEO_INPUT_TERMINAL DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_INPUT_TERMINAL)
-
-#define STATIC_KSNODETYPE_VIDEO_OUTPUT_TERMINAL				\
-	0xDFF229E3L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E3-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_OUTPUT_TERMINAL);
-#define KSNODETYPE_VIDEO_OUTPUT_TERMINAL DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_OUTPUT_TERMINAL)
-
-#define STATIC_KSNODETYPE_VIDEO_SELECTOR				\
-	0xDFF229E4L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E4-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_SELECTOR);
-#define KSNODETYPE_VIDEO_SELECTOR DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_SELECTOR)
-
-#define STATIC_KSNODETYPE_VIDEO_PROCESSING				\
-	0xDFF229E5L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E5-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_PROCESSING);
-#define KSNODETYPE_VIDEO_PROCESSING DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_PROCESSING)
-
-#define STATIC_KSNODETYPE_VIDEO_CAMERA_TERMINAL				\
-	0xDFF229E6L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E6-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_CAMERA_TERMINAL);
-#define KSNODETYPE_VIDEO_CAMERA_TERMINAL DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_CAMERA_TERMINAL)
-
-#define STATIC_KSNODETYPE_VIDEO_INPUT_MTT				\
-	0xDFF229E7L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E7-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_INPUT_MTT);
-#define KSNODETYPE_VIDEO_INPUT_MTT DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_INPUT_MTT)
-
-#define STATIC_KSNODETYPE_VIDEO_OUTPUT_MTT				\
-	0xDFF229E8L,0xF70F,0x11D0,0xB9,0x17,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("DFF229E8-F70F-11D0-B917-00A0C9223196",KSNODETYPE_VIDEO_OUTPUT_MTT);
-#define KSNODETYPE_VIDEO_OUTPUT_MTT DEFINE_GUIDNAMED(KSNODETYPE_VIDEO_OUTPUT_MTT)
-
-#define STATIC_PROPSETID_VIDCAP_VIDEOENCODER				\
-	0x6a2e0610L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0610-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_VIDEOENCODER);
-#define PROPSETID_VIDCAP_VIDEOENCODER DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOENCODER)
-
-typedef enum {
-  KSPROPERTY_VIDEOENCODER_CAPS,
-  KSPROPERTY_VIDEOENCODER_STANDARD,
-  KSPROPERTY_VIDEOENCODER_COPYPROTECTION,
-  KSPROPERTY_VIDEOENCODER_CC_ENABLE
-} KSPROPERTY_VIDCAP_VIDEOENCODER;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_VIDEOENCODER_S,*PKSPROPERTY_VIDEOENCODER_S;
-
-#define STATIC_PROPSETID_VIDCAP_VIDEODECODER				\
-	0xC6E13350L,0x30AC,0x11d0,0xA1,0x8C,0x00,0xA0,0xC9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("C6E13350-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_VIDEODECODER);
-#define PROPSETID_VIDCAP_VIDEODECODER DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEODECODER)
-
-typedef enum {
-  KSPROPERTY_VIDEODECODER_CAPS,
-  KSPROPERTY_VIDEODECODER_STANDARD,
-  KSPROPERTY_VIDEODECODER_STATUS,
-  KSPROPERTY_VIDEODECODER_OUTPUT_ENABLE,
-  KSPROPERTY_VIDEODECODER_VCR_TIMING
-} KSPROPERTY_VIDCAP_VIDEODECODER;
-
-typedef enum {
-  KS_VIDEODECODER_FLAGS_CAN_DISABLE_OUTPUT = 0X0001,
-  KS_VIDEODECODER_FLAGS_CAN_USE_VCR_LOCKING = 0X0002,
-  KS_VIDEODECODER_FLAGS_CAN_INDICATE_LOCKED = 0X0004
-} KS_VIDEODECODER_FLAGS;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StandardsSupported;
-  ULONG Capabilities;
-  ULONG SettlingTime;
-  ULONG HSyncPerVSync;
-} KSPROPERTY_VIDEODECODER_CAPS_S,*PKSPROPERTY_VIDEODECODER_CAPS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG NumberOfLines;
-  ULONG SignalLocked;
-} KSPROPERTY_VIDEODECODER_STATUS_S,*PKSPROPERTY_VIDEODECODER_STATUS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Value;
-} KSPROPERTY_VIDEODECODER_S,*PKSPROPERTY_VIDEODECODER_S;
-
-#define STATIC_EVENTSETID_VIDEODECODER					\
-	0x6a2e0621L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0621-28e4-11d0-a18c-00a0c9118956",EVENTSETID_VIDEODECODER);
-#define EVENTSETID_VIDEODECODER DEFINE_GUIDNAMED(EVENTSETID_VIDEODECODER)
-
-typedef enum {
-  KSEVENT_VIDEODECODER_CHANGED
-} KSEVENT_VIDEODECODER;
-
-#define STATIC_PROPSETID_VIDCAP_CAMERACONTROL				\
-	0xC6E13370L,0x30AC,0x11d0,0xa1,0x8C,0x00,0xA0,0xC9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("C6E13370-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_CAMERACONTROL);
-#define PROPSETID_VIDCAP_CAMERACONTROL DEFINE_GUIDNAMED(PROPSETID_VIDCAP_CAMERACONTROL)
-
-typedef enum {
-  KSPROPERTY_CAMERACONTROL_PAN,
-  KSPROPERTY_CAMERACONTROL_TILT,
-  KSPROPERTY_CAMERACONTROL_ROLL,
-  KSPROPERTY_CAMERACONTROL_ZOOM,
-  KSPROPERTY_CAMERACONTROL_EXPOSURE,
-  KSPROPERTY_CAMERACONTROL_IRIS,
-  KSPROPERTY_CAMERACONTROL_FOCUS,
-  KSPROPERTY_CAMERACONTROL_SCANMODE,
-  KSPROPERTY_CAMERACONTROL_PRIVACY,
-  KSPROPERTY_CAMERACONTROL_PANTILT,
-  KSPROPERTY_CAMERACONTROL_PAN_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_TILT_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_ROLL_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_ZOOM_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_EXPOSURE_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_IRIS_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_FOCUS_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_PANTILT_RELATIVE,
-  KSPROPERTY_CAMERACONTROL_FOCAL_LENGTH
-} KSPROPERTY_VIDCAP_CAMERACONTROL;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_CAMERACONTROL_S,*PKSPROPERTY_CAMERACONTROL_S;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  LONG Value;
-  ULONG Flags;
-  ULONG Capabilities;
-} KSPROPERTY_CAMERACONTROL_NODE_S,PKSPROPERTY_CAMERACONTROL_NODE_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG Value1;
-  ULONG Flags;
-  ULONG Capabilities;
-  LONG Value2;
-} KSPROPERTY_CAMERACONTROL_S2,*PKSPROPERTY_CAMERACONTROL_S2;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  LONG Value1;
-  ULONG Flags;
-  ULONG Capabilities;
-  LONG Value2;
-} KSPROPERTY_CAMERACONTROL_NODE_S2,*PKSPROPERTY_CAMERACONTROL_NODE_S2;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONG lOcularFocalLength;
-  LONG lObjectiveFocalLengthMin;
-  LONG lObjectiveFocalLengthMax;
-} KSPROPERTY_CAMERACONTROL_FOCAL_LENGTH_S,*PKSPROPERTY_CAMERACONTROL_FOCAL_LENGTH_S;
-
-typedef struct {
-  KSNODEPROPERTY NodeProperty;
-  LONG lOcularFocalLength;
-  LONG lObjectiveFocalLengthMin;
-  LONG lObjectiveFocalLengthMax;
-} KSPROPERTY_CAMERACONTROL_NODE_FOCAL_LENGTH_S,*PKSPROPERTY_CAMERACONTROL_NODE_FOCAL_LENGTH_S;
-
-#define KSPROPERTY_CAMERACONTROL_FLAGS_AUTO	0X0001L
-#define KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL	0X0002L
-
-#define KSPROPERTY_CAMERACONTROL_FLAGS_ABSOLUTE	0X0000L
-#define KSPROPERTY_CAMERACONTROL_FLAGS_RELATIVE	0X0010L
-
-#ifndef __EDevCtrl__
-#define __EDevCtrl__
-
-#define STATIC_PROPSETID_EXT_DEVICE					\
-	0xB5730A90L,0x1A2C,0x11cf,0x8c,0x23,0x00,0xAA,0x00,0x6B,0x68,0x14
-DEFINE_GUIDSTRUCT("B5730A90-1A2C-11cf-8C23-00AA006B6814",PROPSETID_EXT_DEVICE);
-#define PROPSETID_EXT_DEVICE DEFINE_GUIDNAMED(PROPSETID_EXT_DEVICE)
-
-typedef enum {
-  KSPROPERTY_EXTDEVICE_ID,
-  KSPROPERTY_EXTDEVICE_VERSION,
-  KSPROPERTY_EXTDEVICE_POWER_STATE,
-  KSPROPERTY_EXTDEVICE_PORT,
-  KSPROPERTY_EXTDEVICE_CAPABILITIES
-} KSPROPERTY_EXTDEVICE;
-
-typedef struct tagDEVCAPS{
-  LONG CanRecord;
-  LONG CanRecordStrobe;
-  LONG HasAudio;
-  LONG HasVideo;
-  LONG UsesFiles;
-  LONG CanSave;
-  LONG DeviceType;
-  LONG TCRead;
-  LONG TCWrite;
-  LONG CTLRead;
-  LONG IndexRead;
-  LONG Preroll;
-  LONG Postroll;
-  LONG SyncAcc;
-  LONG NormRate;
-  LONG CanPreview;
-  LONG CanMonitorSrc;
-  LONG CanTest;
-  LONG VideoIn;
-  LONG AudioIn;
-  LONG Calibrate;
-  LONG SeekType;
-  LONG SimulatedHardware;
-} DEVCAPS,*PDEVCAPS;
-
-typedef struct {
-  KSPROPERTY Property;
-  union {
-    DEVCAPS Capabilities;
-    ULONG DevPort;
-    ULONG PowerState;
-    WCHAR pawchString[MAX_PATH];
-    DWORD NodeUniqueID[2];
-  } u;
-} KSPROPERTY_EXTDEVICE_S,*PKSPROPERTY_EXTDEVICE_S;
-
-#define STATIC_PROPSETID_EXT_TRANSPORT					\
-	0xA03CD5F0L,0x3045,0x11cf,0x8c,0x44,0x00,0xAA,0x00,0x6B,0x68,0x14
-DEFINE_GUIDSTRUCT("A03CD5F0-3045-11cf-8C44-00AA006B6814",PROPSETID_EXT_TRANSPORT);
-#define PROPSETID_EXT_TRANSPORT DEFINE_GUIDNAMED(PROPSETID_EXT_TRANSPORT)
-
-typedef enum {
-  KSPROPERTY_EXTXPORT_CAPABILITIES,
-  KSPROPERTY_EXTXPORT_INPUT_SIGNAL_MODE,
-  KSPROPERTY_EXTXPORT_OUTPUT_SIGNAL_MODE,
-  KSPROPERTY_EXTXPORT_LOAD_MEDIUM,
-  KSPROPERTY_EXTXPORT_MEDIUM_INFO,
-  KSPROPERTY_EXTXPORT_STATE,
-  KSPROPERTY_EXTXPORT_STATE_NOTIFY,
-  KSPROPERTY_EXTXPORT_TIMECODE_SEARCH,
-  KSPROPERTY_EXTXPORT_ATN_SEARCH,
-  KSPROPERTY_EXTXPORT_RTC_SEARCH,
-  KSPROPERTY_RAW_AVC_CMD
-} KSPROPERTY_EXTXPORT;
-
-typedef struct tagTRANSPORTSTATUS {
-  LONG Mode;
-  LONG LastError;
-  LONG RecordInhibit;
-  LONG ServoLock;
-  LONG MediaPresent;
-  LONG MediaLength;
-  LONG MediaSize;
-  LONG MediaTrackCount;
-  LONG MediaTrackLength;
-  LONG MediaTrackSide;
-  LONG MediaType;
-  LONG LinkMode;
-  LONG NotifyOn;
-} TRANSPORTSTATUS,*PTRANSPORTSTATUS;
-
-typedef struct tagTRANSPORTBASICPARMS {
-  LONG TimeFormat;
-  LONG TimeReference;
-  LONG Superimpose;
-  LONG EndStopAction;
-  LONG RecordFormat;
-  LONG StepFrames;
-  LONG SetpField;
-  LONG Preroll;
-  LONG RecPreroll;
-  LONG Postroll;
-  LONG EditDelay;
-  LONG PlayTCDelay;
-  LONG RecTCDelay;
-  LONG EditField;
-  LONG FrameServo;
-  LONG ColorFrameServo;
-  LONG ServoRef;
-  LONG WarnGenlock;
-  LONG SetTracking;
-  TCHAR VolumeName[40];
-  LONG Ballistic[20];
-  LONG Speed;
-  LONG CounterFormat;
-  LONG TunerChannel;
-  LONG TunerNumber;
-  LONG TimerEvent;
-  LONG TimerStartDay;
-  LONG TimerStartTime;
-  LONG TimerStopDay;
-  LONG TimerStopTime;
-} TRANSPORTBASICPARMS,*PTRANSPORTBASICPARMS;
-
-typedef struct tagTRANSPORTVIDEOPARMS {
-  LONG OutputMode;
-  LONG Input;
-} TRANSPORTVIDEOPARMS,*PTRANSPORTVIDEOPARMS;
-
-typedef struct tagTRANSPORTAUDIOPARMS {
-  LONG EnableOutput;
-  LONG EnableRecord;
-  LONG EnableSelsync;
-  LONG Input;
-  LONG MonitorSource;
-} TRANSPORTAUDIOPARMS,*PTRANSPORTAUDIOPARMS;
-
-typedef struct {
-  WINBOOL MediaPresent;
-  ULONG MediaType;
-  WINBOOL RecordInhibit;
-} MEDIUM_INFO,*PMEDIUM_INFO;
-
-typedef struct {
-  ULONG Mode;
-  ULONG State;
-} TRANSPORT_STATE,*PTRANSPORT_STATE;
-
-typedef struct {
-  KSPROPERTY Property;
-  union {
-    ULONG Capabilities;
-    ULONG SignalMode;
-    ULONG LoadMedium;
-    MEDIUM_INFO MediumInfo;
-    TRANSPORT_STATE XPrtState;
-    struct {
-      BYTE frame;
-      BYTE second;
-      BYTE minute;
-      BYTE hour;
-    } Timecode;
-    DWORD dwTimecode;
-    DWORD dwAbsTrackNumber;
-    struct {
-      ULONG PayloadSize;
-      BYTE Payload[512];
-    } RawAVC;
-  } u;
-} KSPROPERTY_EXTXPORT_S,*PKSPROPERTY_EXTXPORT_S;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  union {
-    ULONG Capabilities;
-    ULONG SignalMode;
-    ULONG LoadMedium;
-    MEDIUM_INFO MediumInfo;
-    TRANSPORT_STATE XPrtState;
-    struct {
-      BYTE frame;
-      BYTE second;
-      BYTE minute;
-      BYTE hour;
-    } Timecode;
-    DWORD dwTimecode;
-    DWORD dwAbsTrackNumber;
-    struct {
-      ULONG PayloadSize;
-      BYTE Payload[512];
-    } RawAVC;
-  } u;
-} KSPROPERTY_EXTXPORT_NODE_S,*PKSPROPERTY_EXTXPORT_NODE_S;
-
-#define STATIC_PROPSETID_TIMECODE_READER				\
-	0x9B496CE1L,0x811B,0x11cf,0x8C,0x77,0x00,0xAA,0x00,0x6B,0x68,0x14
-DEFINE_GUIDSTRUCT("9B496CE1-811B-11cf-8C77-00AA006B6814",PROPSETID_TIMECODE_READER);
-#define PROPSETID_TIMECODE_READER DEFINE_GUIDNAMED(PROPSETID_TIMECODE_READER)
-
-typedef enum {
-  KSPROPERTY_TIMECODE_READER,
-  KSPROPERTY_ATN_READER,
-  KSPROPERTY_RTC_READER
-} KSPROPERTY_TIMECODE;
-
-#ifndef TIMECODE_DEFINED
-#define TIMECODE_DEFINED
-typedef union _timecode {
-  struct {
-    WORD wFrameRate;
-    WORD wFrameFract;
-    DWORD dwFrames;
-  };
-  DWORDLONG qw;
-} TIMECODE;
-typedef TIMECODE *PTIMECODE;
-
-typedef struct tagTIMECODE_SAMPLE {
-  LONGLONG qwTick;
-  TIMECODE timecode;
-  DWORD dwUser;
-  DWORD dwFlags;
-} TIMECODE_SAMPLE;
-
-typedef TIMECODE_SAMPLE *PTIMECODE_SAMPLE;
-#endif /* TIMECODE_DEFINED */
-
-typedef struct {
-  KSPROPERTY Property;
-  TIMECODE_SAMPLE TimecodeSamp;
-} KSPROPERTY_TIMECODE_S,*PKSPROPERTY_TIMECODE_S;
-
-typedef struct {
-  KSP_NODE NodeProperty;
-  TIMECODE_SAMPLE TimecodeSamp;
-} KSPROPERTY_TIMECODE_NODE_S,*PKSPROPERTY_TIMECODE_NODE_S;
-
-#define STATIC_KSEVENTSETID_EXTDEV_Command				\
-	0x109c7988L,0xb3cb,0x11d2,0xb4,0x8e,0x00,0x60,0x97,0xb3,0x39,0x1b
-DEFINE_GUIDSTRUCT("109c7988-b3cb-11d2-b48e-006097b3391b",KSEVENTSETID_EXTDEV_Command);
-#define KSEVENTSETID_EXTDEV_Command DEFINE_GUIDNAMED(KSEVENTSETID_EXTDEV_Command)
-
-typedef enum {
-  KSEVENT_EXTDEV_COMMAND_NOTIFY_INTERIM_READY,
-  KSEVENT_EXTDEV_COMMAND_CONTROL_INTERIM_READY,
-  KSEVENT_EXTDEV_COMMAND_BUSRESET,
-  KSEVENT_EXTDEV_TIMECODE_UPDATE,
-  KSEVENT_EXTDEV_OPERATION_MODE_UPDATE,
-  KSEVENT_EXTDEV_TRANSPORT_STATE_UPDATE,
-  KSEVENT_EXTDEV_NOTIFY_REMOVAL,
-  KSEVENT_EXTDEV_NOTIFY_MEDIUM_CHANGE
-} KSEVENT_DEVCMD;
-#endif /* __EDevCtrl__ */
-
-#define STATIC_PROPSETID_VIDCAP_CROSSBAR				\
-	0x6a2e0640L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0640-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_CROSSBAR);
-#define PROPSETID_VIDCAP_CROSSBAR DEFINE_GUIDNAMED(PROPSETID_VIDCAP_CROSSBAR)
-
-typedef enum {
-  KSPROPERTY_CROSSBAR_CAPS,
-  KSPROPERTY_CROSSBAR_PININFO,
-  KSPROPERTY_CROSSBAR_CAN_ROUTE,
-  KSPROPERTY_CROSSBAR_ROUTE
-} KSPROPERTY_VIDCAP_CROSSBAR;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG NumberOfInputs;
-  ULONG NumberOfOutputs;
-} KSPROPERTY_CROSSBAR_CAPS_S,*PKSPROPERTY_CROSSBAR_CAPS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  KSPIN_DATAFLOW Direction;
-  ULONG Index;
-  ULONG PinType;
-  ULONG RelatedPinIndex;
-  KSPIN_MEDIUM Medium;
-} KSPROPERTY_CROSSBAR_PININFO_S,*PKSPROPERTY_CROSSBAR_PININFO_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG IndexInputPin;
-  ULONG IndexOutputPin;
-  ULONG CanRoute;
-} KSPROPERTY_CROSSBAR_ROUTE_S,*PKSPROPERTY_CROSSBAR_ROUTE_S;
-
-#define STATIC_EVENTSETID_CROSSBAR					\
-	0x6a2e0641L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0641-28e4-11d0-a18c-00a0c9118956",EVENTSETID_CROSSBAR);
-#define EVENTSETID_CROSSBAR DEFINE_GUIDNAMED(EVENTSETID_CROSSBAR)
-
-typedef enum {
-  KSEVENT_CROSSBAR_CHANGED
-} KSEVENT_CROSSBAR;
-
-typedef enum {
-  KS_PhysConn_Video_Tuner = 1,
-  KS_PhysConn_Video_Composite,
-  KS_PhysConn_Video_SVideo,
-  KS_PhysConn_Video_RGB,
-  KS_PhysConn_Video_YRYBY,
-  KS_PhysConn_Video_SerialDigital,
-  KS_PhysConn_Video_ParallelDigital,
-  KS_PhysConn_Video_SCSI,
-  KS_PhysConn_Video_AUX,
-  KS_PhysConn_Video_1394,
-  KS_PhysConn_Video_USB,
-  KS_PhysConn_Video_VideoDecoder,
-  KS_PhysConn_Video_VideoEncoder,
-  KS_PhysConn_Video_SCART,
-  KS_PhysConn_Audio_Tuner = 4096,
-  KS_PhysConn_Audio_Line,
-  KS_PhysConn_Audio_Mic,
-  KS_PhysConn_Audio_AESDigital,
-  KS_PhysConn_Audio_SPDIFDigital,
-  KS_PhysConn_Audio_SCSI,
-  KS_PhysConn_Audio_AUX,
-  KS_PhysConn_Audio_1394,
-  KS_PhysConn_Audio_USB,
-  KS_PhysConn_Audio_AudioDecoder
-} KS_PhysicalConnectorType;
-
-#define STATIC_PROPSETID_VIDCAP_TVAUDIO					\
-	0x6a2e0650L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0650-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_TVAUDIO);
-#define PROPSETID_VIDCAP_TVAUDIO DEFINE_GUIDNAMED(PROPSETID_VIDCAP_TVAUDIO)
-
-typedef enum {
-  KSPROPERTY_TVAUDIO_CAPS,
-  KSPROPERTY_TVAUDIO_MODE,
-  KSPROPERTY_TVAUDIO_CURRENTLY_AVAILABLE_MODES
-} KSPROPERTY_VIDCAP_TVAUDIO;
-
-#define KS_TVAUDIO_MODE_MONO	0x0001
-#define KS_TVAUDIO_MODE_STEREO	0x0002
-#define KS_TVAUDIO_MODE_LANG_A	0x0010
-#define KS_TVAUDIO_MODE_LANG_B	0x0020
-#define KS_TVAUDIO_MODE_LANG_C	0x0040
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Capabilities;
-  KSPIN_MEDIUM InputMedium;
-  KSPIN_MEDIUM OutputMedium;
-} KSPROPERTY_TVAUDIO_CAPS_S,*PKSPROPERTY_TVAUDIO_CAPS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG Mode;
-} KSPROPERTY_TVAUDIO_S,*PKSPROPERTY_TVAUDIO_S;
-
-#define STATIC_KSEVENTSETID_VIDCAP_TVAUDIO				\
-	0x6a2e0651L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0651-28e4-11d0-a18c-00a0c9118956",KSEVENTSETID_VIDCAP_TVAUDIO);
-#define KSEVENTSETID_VIDCAP_TVAUDIO DEFINE_GUIDNAMED(KSEVENTSETID_VIDCAP_TVAUDIO)
-
-typedef enum {
-  KSEVENT_TVAUDIO_CHANGED
-} KSEVENT_TVAUDIO;
-
-#define STATIC_PROPSETID_VIDCAP_VIDEOCOMPRESSION			\
-	0xC6E13343L,0x30AC,0x11d0,0xA1,0x8C,0x00,0xA0,0xC9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("C6E13343-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_VIDEOCOMPRESSION);
-#define PROPSETID_VIDCAP_VIDEOCOMPRESSION DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOCOMPRESSION)
-
-typedef enum {
-  KSPROPERTY_VIDEOCOMPRESSION_GETINFO,
-  KSPROPERTY_VIDEOCOMPRESSION_KEYFRAME_RATE,
-  KSPROPERTY_VIDEOCOMPRESSION_PFRAMES_PER_KEYFRAME,
-  KSPROPERTY_VIDEOCOMPRESSION_QUALITY,
-  KSPROPERTY_VIDEOCOMPRESSION_OVERRIDE_KEYFRAME,
-  KSPROPERTY_VIDEOCOMPRESSION_OVERRIDE_FRAME_SIZE,
-  KSPROPERTY_VIDEOCOMPRESSION_WINDOWSIZE
-} KSPROPERTY_VIDCAP_VIDEOCOMPRESSION;
-
-typedef enum {
-  KS_CompressionCaps_CanQuality = 1,
-  KS_CompressionCaps_CanCrunch = 2,
-  KS_CompressionCaps_CanKeyFrame = 4,
-  KS_CompressionCaps_CanBFrame = 8,
-  KS_CompressionCaps_CanWindow = 0x10
-} KS_CompressionCaps;
-
-typedef enum {
-  KS_StreamingHint_FrameInterval = 0x0100,
-  KS_StreamingHint_KeyFrameRate = 0x0200,
-  KS_StreamingHint_PFrameRate = 0x0400,
-  KS_StreamingHint_CompQuality = 0x0800,
-  KS_StreamingHint_CompWindowSize = 0x1000
-} KS_VideoStreamingHints;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  LONG DefaultKeyFrameRate;
-  LONG DefaultPFrameRate;
-  LONG DefaultQuality;
-  LONG NumberOfQualitySettings;
-  LONG Capabilities;
-} KSPROPERTY_VIDEOCOMPRESSION_GETINFO_S,*PKSPROPERTY_VIDEOCOMPRESSION_GETINFO_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  LONG Value;
-} KSPROPERTY_VIDEOCOMPRESSION_S,*PKSPROPERTY_VIDEOCOMPRESSION_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  LONG Value;
-  ULONG Flags;
-} KSPROPERTY_VIDEOCOMPRESSION_S1,*PKSPROPERTY_VIDEOCOMPRESSION_S1;
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_OVERLAY				\
-	0xe436eb7fL,0x524f,0x11ce,0x9f,0x53,0x00,0x20,0xaf,0x0b,0xa7,0x70
-DEFINE_GUIDSTRUCT("e436eb7f-524f-11ce-9f53-0020af0ba770",KSDATAFORMAT_SUBTYPE_OVERLAY);
-#define KSDATAFORMAT_SUBTYPE_OVERLAY DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_OVERLAY)
-
-#define STATIC_KSPROPSETID_OverlayUpdate				\
-	0x490EA5CFL,0x7681,0x11D1,0xA2,0x1C,0x00,0xA0,0xC9,0x22,0x31,0x96
-DEFINE_GUIDSTRUCT("490EA5CF-7681-11D1-A21C-00A0C9223196",KSPROPSETID_OverlayUpdate);
-#define KSPROPSETID_OverlayUpdate DEFINE_GUIDNAMED(KSPROPSETID_OverlayUpdate)
-
-typedef enum {
-  KSPROPERTY_OVERLAYUPDATE_INTERESTS,
-  KSPROPERTY_OVERLAYUPDATE_CLIPLIST = 0x1,
-  KSPROPERTY_OVERLAYUPDATE_PALETTE = 0x2,
-  KSPROPERTY_OVERLAYUPDATE_COLORKEY = 0x4,
-  KSPROPERTY_OVERLAYUPDATE_VIDEOPOSITION = 0x8,
-  KSPROPERTY_OVERLAYUPDATE_DISPLAYCHANGE = 0x10,
-  KSPROPERTY_OVERLAYUPDATE_COLORREF = 0x10000000
-} KSPROPERTY_OVERLAYUPDATE;
-
-typedef struct {
-  ULONG PelsWidth;
-  ULONG PelsHeight;
-  ULONG BitsPerPel;
-  WCHAR DeviceID[1];
-} KSDISPLAYCHANGE,*PKSDISPLAYCHANGE;
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_INTERESTS(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_INTERESTS,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(ULONG),				\
-				NULL, NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_PALETTE(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_PALETTE,	\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				0,					\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_COLORKEY(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_COLORKEY,	\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				sizeof(COLORKEY),			\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_CLIPLIST(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_CLIPLIST,	\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				2 *sizeof(RECT) + sizeof(RGNDATAHEADER),\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_VIDEOPOSITION(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_VIDEOPOSITION,	\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				2 *sizeof(RECT),			\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_DISPLAYCHANGE(Handler)	\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_DISPLAYCHANGE,	\
-				NULL,					\
-				sizeof(KSPROPERTY),			\
-				sizeof(KSDISPLAYCHANGE),		\
-				(Handler),				\
-				NULL, 0, NULL, NULL, 0)
-
-#define DEFINE_KSPROPERTY_ITEM_OVERLAYUPDATE_COLORREF(Handler)		\
-	DEFINE_KSPROPERTY_ITEM(						\
-				KSPROPERTY_OVERLAYUPDATE_COLORREF,	\
-				(Handler),				\
-				sizeof(KSPROPERTY),			\
-				sizeof(COLORREF),			\
-				NULL,					\
-				NULL, 0, NULL, NULL, 0)
-
-#define STATIC_PROPSETID_VIDCAP_VIDEOCONTROL				\
-	0x6a2e0670L,0x28e4,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("6a2e0670-28e4-11d0-a18c-00a0c9118956",PROPSETID_VIDCAP_VIDEOCONTROL);
-#define PROPSETID_VIDCAP_VIDEOCONTROL DEFINE_GUIDNAMED(PROPSETID_VIDCAP_VIDEOCONTROL)
-
-typedef enum {
-  KSPROPERTY_VIDEOCONTROL_CAPS,
-  KSPROPERTY_VIDEOCONTROL_ACTUAL_FRAME_RATE,
-  KSPROPERTY_VIDEOCONTROL_FRAME_RATES,
-  KSPROPERTY_VIDEOCONTROL_MODE
-} KSPROPERTY_VIDCAP_VIDEOCONTROL;
-
-typedef enum {
-  KS_VideoControlFlag_FlipHorizontal = 0x0001,
-  KS_VideoControlFlag_FlipVertical = 0x0002,
-  KS_Obsolete_VideoControlFlag_ExternalTriggerEnable = 0x0010,
-  KS_Obsolete_VideoControlFlag_Trigger = 0x0020,
-  KS_VideoControlFlag_ExternalTriggerEnable = 0x0004,
-  KS_VideoControlFlag_Trigger = 0x0008
-} KS_VideoControlFlags;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  ULONG VideoControlCaps;
-} KSPROPERTY_VIDEOCONTROL_CAPS_S,*PKSPROPERTY_VIDEOCONTROL_CAPS_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  LONG Mode;
-} KSPROPERTY_VIDEOCONTROL_MODE_S,*PKSPROPERTY_VIDEOCONTROL_MODE_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  ULONG RangeIndex;
-  SIZE Dimensions;
-  LONGLONG CurrentActualFrameRate;
-  LONGLONG CurrentMaxAvailableFrameRate;
-} KSPROPERTY_VIDEOCONTROL_ACTUAL_FRAME_RATE_S,*PKSPROPERTY_VIDEOCONTROL_ACTUAL_FRAME_RATE_S;
-
-typedef struct {
-  KSPROPERTY Property;
-  ULONG StreamIndex;
-  ULONG RangeIndex;
-  SIZE Dimensions;
-} KSPROPERTY_VIDEOCONTROL_FRAME_RATES_S,*PKSPROPERTY_VIDEOCONTROL_FRAME_RATES_S;
-
-#define STATIC_PROPSETID_VIDCAP_DROPPEDFRAMES				\
-	0xC6E13344L,0x30AC,0x11d0,0xa1,0x8c,0x00,0xa0,0xc9,0x11,0x89,0x56
-DEFINE_GUIDSTRUCT("C6E13344-30AC-11d0-A18C-00A0C9118956",PROPSETID_VIDCAP_DROPPEDFRAMES);
-#define PROPSETID_VIDCAP_DROPPEDFRAMES DEFINE_GUIDNAMED(PROPSETID_VIDCAP_DROPPEDFRAMES)
-
-typedef enum {
-  KSPROPERTY_DROPPEDFRAMES_CURRENT
-} KSPROPERTY_VIDCAP_DROPPEDFRAMES;
-
-typedef struct {
-  KSPROPERTY Property;
-  LONGLONG PictureNumber;
-  LONGLONG DropCount;
-  ULONG AverageFrameSize;
-} KSPROPERTY_DROPPEDFRAMES_CURRENT_S,*PKSPROPERTY_DROPPEDFRAMES_CURRENT_S;
-
-#define STATIC_KSPROPSETID_VPConfig					\
-	0xbc29a660L,0x30e3,0x11d0,0x9e,0x69,0x00,0xc0,0x4f,0xd7,0xc1,0x5b
-DEFINE_GUIDSTRUCT("bc29a660-30e3-11d0-9e69-00c04fd7c15b",KSPROPSETID_VPConfig);
-#define KSPROPSETID_VPConfig DEFINE_GUIDNAMED(KSPROPSETID_VPConfig)
-
-#define STATIC_KSPROPSETID_VPVBIConfig					\
-	0xec529b00L,0x1a1f,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
-DEFINE_GUIDSTRUCT("ec529b00-1a1f-11d1-bad9-00609744111a",KSPROPSETID_VPVBIConfig);
-#define KSPROPSETID_VPVBIConfig DEFINE_GUIDNAMED(KSPROPSETID_VPVBIConfig)
-
-typedef enum {
-  KSPROPERTY_VPCONFIG_NUMCONNECTINFO,
-  KSPROPERTY_VPCONFIG_GETCONNECTINFO,
-  KSPROPERTY_VPCONFIG_SETCONNECTINFO,
-  KSPROPERTY_VPCONFIG_VPDATAINFO,
-  KSPROPERTY_VPCONFIG_MAXPIXELRATE,
-  KSPROPERTY_VPCONFIG_INFORMVPINPUT,
-  KSPROPERTY_VPCONFIG_NUMVIDEOFORMAT,
-  KSPROPERTY_VPCONFIG_GETVIDEOFORMAT,
-  KSPROPERTY_VPCONFIG_SETVIDEOFORMAT,
-  KSPROPERTY_VPCONFIG_INVERTPOLARITY,
-  KSPROPERTY_VPCONFIG_DECIMATIONCAPABILITY,
-  KSPROPERTY_VPCONFIG_SCALEFACTOR,
-  KSPROPERTY_VPCONFIG_DDRAWHANDLE,
-  KSPROPERTY_VPCONFIG_VIDEOPORTID,
-  KSPROPERTY_VPCONFIG_DDRAWSURFACEHANDLE,
-  KSPROPERTY_VPCONFIG_SURFACEPARAMS
-} KSPROPERTY_VPCONFIG;
-
-#define STATIC_CLSID_KsIBasicAudioInterfaceHandler			\
-	0xb9f8ac3e,0x0f71,0x11d2,0xb7,0x2c,0x00,0xc0,0x4f,0xb6,0xbd,0x3d
-DEFINE_GUIDSTRUCT("b9f8ac3e-0f71-11d2-b72c-00c04fb6bd3d",CLSID_KsIBasicAudioInterfaceHandler);
-#define CLSID_KsIBasicAudioInterfaceHandler DEFINE_GUIDNAMED(CLSID_KsIBasicAudioInterfaceHandler)
-
-#ifdef __IVPType__
-typedef struct {
-  AMVPSIZE Size;
-  DWORD MaxPixelsPerSecond;
-  DWORD Reserved;
-} KSVPMAXPIXELRATE,*PKSVPMAXPIXELRATE;
-
-typedef struct {
-  KSPROPERTY Property;
-  AMVPSIZE Size;
-} KSVPSIZE_PROP,*PKSVPSIZE_PROP;
-
-typedef struct {
-  DWORD dwPitch;
-  DWORD dwXOrigin;
-  DWORD dwYOrigin;
-} KSVPSURFACEPARAMS,*PKSVPSURFACEPARAMS;
-#else /* __IVPType__ */
-
-#ifndef __DDRAW_INCLUDED__
-#define DDPF_FOURCC 0x00000004l
-
-typedef struct _DDPIXELFORMAT
-{
-  DWORD dwSize;
-  DWORD dwFlags;
-  DWORD dwFourCC;
-  __MINGW_EXTENSION union
-  {
-    DWORD dwRGBBitCount;
-    DWORD dwYUVBitCount;
-    DWORD dwZBufferBitDepth;
-    DWORD dwAlphaBitDepth;
-  };
-  __MINGW_EXTENSION union
-  {
-    DWORD dwRBitMask;
-    DWORD dwYBitMask;
-  };
-  __MINGW_EXTENSION union
-  {
-    DWORD dwGBitMask;
-    DWORD dwUBitMask;
-  };
-  __MINGW_EXTENSION union
-  {
-    DWORD dwBBitMask;
-    DWORD dwVBitMask;
-  };
-  __MINGW_EXTENSION union
-  {
-    DWORD dwRGBAlphaBitMask;
-    DWORD dwYUVAlphaBitMask;
-    DWORD dwRGBZBitMask;
-    DWORD dwYUVZBitMask;
-  };
-} DDPIXELFORMAT,*LPDDPIXELFORMAT;
-#endif /* __DDRAW_INCLUDED__ */
-
-#ifndef __DVP_INCLUDED__
-typedef struct _DDVIDEOPORTCONNECT {
-  DWORD dwSize;
-  DWORD dwPortWidth;
-  GUID guidTypeID;
-  DWORD dwFlags;
-  ULONG_PTR dwReserved1;
-} DDVIDEOPORTCONNECT,*LPDDVIDEOPORTCONNECT;
-
-#define DDVPTYPE_E_HREFH_VREFH						\
-	0x54F39980L,0xDA60,0x11CF,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8
-
-#define DDVPTYPE_E_HREFL_VREFL						\
-	0xE09C77E0L,0xDA60,0x11CF,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8
-#endif /* __DVP_INCLUDED__ */
-
-typedef enum
-{
-  KS_PixAspectRatio_NTSC4x3,
-  KS_PixAspectRatio_NTSC16x9,
-  KS_PixAspectRatio_PAL4x3,
-  KS_PixAspectRatio_PAL16x9
-} KS_AMPixAspectRatio;
-
-typedef enum
-{
-  KS_AMVP_DO_NOT_CARE,
-  KS_AMVP_BEST_BANDWIDTH,
-  KS_AMVP_INPUT_SAME_AS_OUTPUT
-} KS_AMVP_SELECTFORMATBY;
-
-typedef enum
-{
-  KS_AMVP_MODE_WEAVE,
-  KS_AMVP_MODE_BOBINTERLEAVED,
-  KS_AMVP_MODE_BOBNONINTERLEAVED,
-  KS_AMVP_MODE_SKIPEVEN,
-  KS_AMVP_MODE_SKIPODD
-} KS_AMVP_MODE;
-
-typedef struct tagKS_AMVPDIMINFO
-{
-  DWORD dwFieldWidth;
-  DWORD dwFieldHeight;
-  DWORD dwVBIWidth;
-  DWORD dwVBIHeight;
-  RECT rcValidRegion;
-} KS_AMVPDIMINFO,*PKS_AMVPDIMINFO;
-
-typedef struct tagKS_AMVPDATAINFO
-{
-  DWORD dwSize;
-  DWORD dwMicrosecondsPerField;
-  KS_AMVPDIMINFO amvpDimInfo;
-  DWORD dwPictAspectRatioX;
-  DWORD dwPictAspectRatioY;
-  WINBOOL bEnableDoubleClock;
-  WINBOOL bEnableVACT;
-  WINBOOL bDataIsInterlaced;
-  LONG lHalfLinesOdd;
-  WINBOOL bFieldPolarityInverted;
-  DWORD dwNumLinesInVREF;
-  LONG lHalfLinesEven;
-  DWORD dwReserved1;
-} KS_AMVPDATAINFO,*PKS_AMVPDATAINFO;
-
-typedef struct tagKS_AMVPSIZE
-{
-  DWORD dwWidth;
-  DWORD dwHeight;
-} KS_AMVPSIZE,*PKS_AMVPSIZE;
-
-typedef struct {
-  KS_AMVPSIZE Size;
-  DWORD MaxPixelsPerSecond;
-  DWORD Reserved;
-} KSVPMAXPIXELRATE,*PKSVPMAXPIXELRATE;
-
-typedef struct {
-  KSPROPERTY Property;
-  KS_AMVPSIZE Size;
-} KSVPSIZE_PROP,*PKSVPSIZE_PROP;
-
-typedef struct {
-  DWORD dwPitch;
-  DWORD dwXOrigin;
-  DWORD dwYOrigin;
-} KSVPSURFACEPARAMS,*PKSVPSURFACEPARAMS;
-#endif /* __IVPType__ */
-
-#define STATIC_KSEVENTSETID_VPNotify					\
-	0x20c5598eL,0xd3c8,0x11d0,0x8d,0xfc,0x00,0xc0,0x4f,0xd7,0xc0,0x8b
-DEFINE_GUIDSTRUCT("20c5598e-d3c8-11d0-8dfc-00c04fd7c08b",KSEVENTSETID_VPNotify);
-#define KSEVENTSETID_VPNotify DEFINE_GUIDNAMED(KSEVENTSETID_VPNotify)
-
-typedef enum {
-  KSEVENT_VPNOTIFY_FORMATCHANGE
-} KSEVENT_VPNOTIFY;
-
-#define STATIC_KSEVENTSETID_VIDCAPTOSTI					\
-	0xdb47de20,0xf628,0x11d1,0xba,0x41,0x0,0xa0,0xc9,0xd,0x2b,0x5
-DEFINE_GUIDSTRUCT("DB47DE20-F628-11d1-BA41-00A0C90D2B05",KSEVENTSETID_VIDCAPTOSTI);
-#define KSEVENTSETID_VIDCAPNotify DEFINE_GUIDNAMED(KSEVENTSETID_VIDCAPTOSTI)
-
-typedef enum {
-  KSEVENT_VIDCAPTOSTI_EXT_TRIGGER,
-  KSEVENT_VIDCAP_AUTO_UPDATE,
-  KSEVENT_VIDCAP_SEARCH
-} KSEVENT_VIDCAPTOSTI;
-
-typedef enum {
-  KSPROPERTY_EXTENSION_UNIT_INFO,
-  KSPROPERTY_EXTENSION_UNIT_CONTROL,
-  KSPROPERTY_EXTENSION_UNIT_PASS_THROUGH = 0xffff
-} KSPROPERTY_EXTENSION_UNIT,*PKSPROPERTY_EXTENSION_UNIT;
-
-#define STATIC_KSEVENTSETID_VPVBINotify					\
-	0xec529b01L,0x1a1f,0x11d1,0xba,0xd9,0x0,0x60,0x97,0x44,0x11,0x1a
-DEFINE_GUIDSTRUCT("ec529b01-1a1f-11d1-bad9-00609744111a",KSEVENTSETID_VPVBINotify);
-#define KSEVENTSETID_VPVBINotify DEFINE_GUIDNAMED(KSEVENTSETID_VPVBINotify)
-
-typedef enum {
-  KSEVENT_VPVBINOTIFY_FORMATCHANGE
-} KSEVENT_VPVBINOTIFY;
-
-#define STATIC_KSDATAFORMAT_TYPE_AUXLine21Data				\
-	0x670aea80L,0x3a82,0x11d0,0xb7,0x9b,0x00,0xaa,0x00,0x37,0x67,0xa7
-DEFINE_GUIDSTRUCT("670aea80-3a82-11d0-b79b-00aa003767a7",KSDATAFORMAT_TYPE_AUXLine21Data);
-#define KSDATAFORMAT_TYPE_AUXLine21Data DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_AUXLine21Data)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_Line21_BytePair			\
-	0x6e8d4a22L,0x310c,0x11d0,0xb7,0x9a,0x00,0xaa,0x00,0x37,0x67,0xa7
-DEFINE_GUIDSTRUCT("6e8d4a22-310c-11d0-b79a-00aa003767a7",KSDATAFORMAT_SUBTYPE_Line21_BytePair);
-#define KSDATAFORMAT_SUBTYPE_Line21_BytePair DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_Line21_BytePair)
-
-#define STATIC_KSDATAFORMAT_SUBTYPE_Line21_GOPPacket			\
-	0x6e8d4a23L,0x310c,0x11d0,0xb7,0x9a,0x00,0xaa,0x00,0x37,0x67,0xa7
-DEFINE_GUIDSTRUCT("6e8d4a23-310c-11d0-b79a-00aa003767a7",KSDATAFORMAT_SUBTYPE_Line21_GOPPacket);
-#define KSDATAFORMAT_SUBTYPE_Line21_GOPPacket DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_Line21_GOPPacket)
-
-typedef struct _KSGOP_USERDATA {
-  ULONG sc;
-  ULONG reserved1;
-  BYTE cFields;
-  CHAR l21Data[3];
-} KSGOP_USERDATA,*PKSGOP_USERDATA;
-
-#define STATIC_KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK			\
-	0xed0b916a,0x044d,0x11d1,0xaa,0x78,0x00,0xc0,0x4f,0xc3,0x1d,0x60
-DEFINE_GUIDSTRUCT("ed0b916a-044d-11d1-aa78-00c04fc31d60",KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK);
-#define KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK DEFINE_GUIDNAMED(KSDATAFORMAT_TYPE_DVD_ENCRYPTED_PACK)
-
-#define KS_AM_UseNewCSSKey			0x1
-
-#define STATIC_KSPROPSETID_TSRateChange					\
-	0xa503c5c0,0x1d1d,0x11d1,0xad,0x80,0x44,0x45,0x53,0x54,0x0,0x0
-DEFINE_GUIDSTRUCT("A503C5C0-1D1D-11D1-AD80-444553540000",KSPROPSETID_TSRateChange);
-#define KSPROPSETID_TSRateChange DEFINE_GUIDNAMED(KSPROPSETID_TSRateChange)
-
-typedef enum {
-  KS_AM_RATE_SimpleRateChange = 1,
-  KS_AM_RATE_ExactRateChange = 2,
-  KS_AM_RATE_MaxFullDataRate = 3,
-  KS_AM_RATE_Step = 4
-} KS_AM_PROPERTY_TS_RATE_CHANGE;
-
-typedef struct {
-  REFERENCE_TIME StartTime;
-  LONG Rate;
-} KS_AM_SimpleRateChange,*PKS_AM_SimpleRateChange;
-
-typedef struct {
-  REFERENCE_TIME OutputZeroTime;
-  LONG Rate;
-} KS_AM_ExactRateChange,*PKS_AM_ExactRateChange;
-
-typedef LONG KS_AM_MaxFullDataRate;
-typedef DWORD KS_AM_Step;
-
-#define STATIC_KSCATEGORY_ENCODER					\
-	0x19689bf6,0xc384,0x48fd,0xad,0x51,0x90,0xe5,0x8c,0x79,0xf7,0xb
-DEFINE_GUIDSTRUCT("19689BF6-C384-48fd-AD51-90E58C79F70B",KSCATEGORY_ENCODER);
-#define KSCATEGORY_ENCODER DEFINE_GUIDNAMED(KSCATEGORY_ENCODER)
-
-#define STATIC_KSCATEGORY_MULTIPLEXER					\
-	0x7a5de1d3,0x1a1,0x452c,0xb4,0x81,0x4f,0xa2,0xb9,0x62,0x71,0xe8
-DEFINE_GUIDSTRUCT("7A5DE1D3-01A1-452c-B481-4FA2B96271E8",KSCATEGORY_MULTIPLEXER);
-#define KSCATEGORY_MULTIPLEXER DEFINE_GUIDNAMED(KSCATEGORY_MULTIPLEXER)
-
-#ifndef __ENCODER_API_GUIDS__
-#define __ENCODER_API_GUIDS__
-
-#define STATIC_ENCAPIPARAM_BITRATE					\
-	0x49cc4c43,0xca83,0x4ad4,0xa9,0xaf,0xf3,0x69,0x6a,0xf6,0x66,0xdf
-DEFINE_GUIDSTRUCT("49CC4C43-CA83-4ad4-A9AF-F3696AF666DF",ENCAPIPARAM_BITRATE);
-#define ENCAPIPARAM_BITRATE DEFINE_GUIDNAMED(ENCAPIPARAM_BITRATE)
-
-#define STATIC_ENCAPIPARAM_PEAK_BITRATE					\
-	0x703f16a9,0x3d48,0x44a1,0xb0,0x77,0x1,0x8d,0xff,0x91,0x5d,0x19
-DEFINE_GUIDSTRUCT("703F16A9-3D48-44a1-B077-018DFF915D19",ENCAPIPARAM_PEAK_BITRATE);
-#define ENCAPIPARAM_PEAK_BITRATE DEFINE_GUIDNAMED(ENCAPIPARAM_PEAK_BITRATE)
-
-#define STATIC_ENCAPIPARAM_BITRATE_MODE					\
-	0xee5fb25c,0xc713,0x40d1,0x9d,0x58,0xc0,0xd7,0x24,0x1e,0x25,0xf
-DEFINE_GUIDSTRUCT("EE5FB25C-C713-40d1-9D58-C0D7241E250F",ENCAPIPARAM_BITRATE_MODE);
-#define ENCAPIPARAM_BITRATE_MODE DEFINE_GUIDNAMED(ENCAPIPARAM_BITRATE_MODE)
-
-#define STATIC_CODECAPI_CHANGELISTS					\
-	0x62b12acf,0xf6b0,0x47d9,0x94,0x56,0x96,0xf2,0x2c,0x4e,0x0b,0x9d
-DEFINE_GUIDSTRUCT("62B12ACF-F6B0-47D9-9456-96F22C4E0B9D",CODECAPI_CHANGELISTS);
-#define CODECAPI_CHANGELISTS DEFINE_GUIDNAMED(CODECAPI_CHANGELISTS)
-
-#define STATIC_CODECAPI_VIDEO_ENCODER					\
-	0x7112e8e1,0x3d03,0x47ef,0x8e,0x60,0x03,0xf1,0xcf,0x53,0x73,0x01
-DEFINE_GUIDSTRUCT("7112E8E1-3D03-47EF-8E60-03F1CF537301",CODECAPI_VIDEO_ENCODER);
-#define CODECAPI_VIDEO_ENCODER DEFINE_GUIDNAMED(CODECAPI_VIDEO_ENCODER)
-
-#define STATIC_CODECAPI_AUDIO_ENCODER					\
-	0xb9d19a3e,0xf897,0x429c,0xbc,0x46,0x81,0x38,0xb7,0x27,0x2b,0x2d
-DEFINE_GUIDSTRUCT("B9D19A3E-F897-429C-BC46-8138B7272B2D",CODECAPI_AUDIO_ENCODER);
-#define CODECAPI_AUDIO_ENCODER DEFINE_GUIDNAMED(CODECAPI_AUDIO_ENCODER)
-
-#define STATIC_CODECAPI_SETALLDEFAULTS					\
-	0x6c5e6a7c,0xacf8,0x4f55,0xa9,0x99,0x1a,0x62,0x81,0x09,0x05,0x1b
-DEFINE_GUIDSTRUCT("6C5E6A7C-ACF8-4F55-A999-1A628109051B",CODECAPI_SETALLDEFAULTS);
-#define CODECAPI_SETALLDEFAULTS DEFINE_GUIDNAMED(CODECAPI_SETALLDEFAULTS)
-
-#define STATIC_CODECAPI_ALLSETTINGS					\
-	0x6a577e92,0x83e1,0x4113,0xad,0xc2,0x4f,0xce,0xc3,0x2f,0x83,0xa1
-DEFINE_GUIDSTRUCT("6A577E92-83E1-4113-ADC2-4FCEC32F83A1",CODECAPI_ALLSETTINGS);
-#define CODECAPI_ALLSETTINGS DEFINE_GUIDNAMED(CODECAPI_ALLSETTINGS)
-
-#define STATIC_CODECAPI_SUPPORTSEVENTS					\
-	0x0581af97,0x7693,0x4dbd,0x9d,0xca,0x3f,0x9e,0xbd,0x65,0x85,0xa1
-DEFINE_GUIDSTRUCT("0581AF97-7693-4DBD-9DCA-3F9EBD6585A1",CODECAPI_SUPPORTSEVENTS);
-#define CODECAPI_SUPPORTSEVENTS DEFINE_GUIDNAMED(CODECAPI_SUPPORTSEVENTS)
-
-#define STATIC_CODECAPI_CURRENTCHANGELIST				\
-	0x1cb14e83,0x7d72,0x4657,0x83,0xfd,0x47,0xa2,0xc5,0xb9,0xd1,0x3d
-DEFINE_GUIDSTRUCT("1CB14E83-7D72-4657-83FD-47A2C5B9D13D",CODECAPI_CURRENTCHANGELIST);
-#define CODECAPI_CURRENTCHANGELIST DEFINE_GUIDNAMED(CODECAPI_CURRENTCHANGELIST)
-#endif /* __ENCODER_API_GUIDS__ */
-
-#ifndef __ENCODER_API_DEFINES__
-#define __ENCODER_API_DEFINES__
-typedef enum {
-  ConstantBitRate = 0,
-  VariableBitRateAverage,
-  VariableBitRatePeak
-} VIDEOENCODER_BITRATE_MODE;
-#endif /* __ENCODER_API_DEFINES__ */
-
-#define STATIC_KSPROPSETID_Jack\
-    0x4509f757, 0x2d46, 0x4637, 0x8e, 0x62, 0xce, 0x7d, 0xb9, 0x44, 0xf5, 0x7b
-DEFINE_GUIDSTRUCT("4509F757-2D46-4637-8E62-CE7DB944F57B", KSPROPSETID_Jack);
-#define KSPROPSETID_Jack DEFINE_GUIDNAMED(KSPROPSETID_Jack)
-
-typedef enum {
-    KSPROPERTY_JACK_DESCRIPTION = 1,
-    KSPROPERTY_JACK_DESCRIPTION2,
-    KSPROPERTY_JACK_SINK_INFO
-} KSPROPERTY_JACK;
-
-typedef enum
-{
-    eConnTypeUnknown,
-    eConnType3Point5mm,
-    eConnTypeQuarter,
-    eConnTypeAtapiInternal,
-    eConnTypeRCA,
-    eConnTypeOptical,
-    eConnTypeOtherDigital,
-    eConnTypeOtherAnalog,
-    eConnTypeMultichannelAnalogDIN,
-    eConnTypeXlrProfessional,
-    eConnTypeRJ11Modem,
-    eConnTypeCombination
-} EPcxConnectionType;
-
-typedef enum
-{
-    eGeoLocRear = 0x1,
-    eGeoLocFront,
-    eGeoLocLeft,
-    eGeoLocRight,
-    eGeoLocTop,
-    eGeoLocBottom,
-    eGeoLocRearPanel,
-    eGeoLocRiser,
-    eGeoLocInsideMobileLid,
-    eGeoLocDrivebay,
-    eGeoLocHDMI,
-    eGeoLocOutsideMobileLid,
-    eGeoLocATAPI,
-    eGeoLocReserved5,
-    eGeoLocReserved6,
-    EPcxGeoLocation_enum_count
-} EPcxGeoLocation;
-
-typedef enum
-{
-    eGenLocPrimaryBox = 0,
-    eGenLocInternal,
-    eGenLocSeparate,
-    eGenLocOther,
-    EPcxGenLocation_enum_count
-} EPcxGenLocation;
-
-typedef enum
-{
-    ePortConnJack = 0,
-    ePortConnIntegratedDevice,
-    ePortConnBothIntegratedAndJack,
-    ePortConnUnknown
-} EPxcPortConnection;
-
-typedef struct 
-{
-    DWORD                 ChannelMapping;
-    COLORREF              Color;
-    EPcxConnectionType    ConnectionType;
-    EPcxGeoLocation       GeoLocation;
-    EPcxGenLocation       GenLocation;
-    EPxcPortConnection    PortConnection;
-    BOOL                  IsConnected;
-} KSJACK_DESCRIPTION, *PKSJACK_DESCRIPTION;
-
-typedef enum 
-{
-    KSJACK_SINK_CONNECTIONTYPE_HDMI = 0,           
-    KSJACK_SINK_CONNECTIONTYPE_DISPLAYPORT,         
-} KSJACK_SINK_CONNECTIONTYPE;
-
-#define MAX_SINK_DESCRIPTION_NAME_LENGTH 32
-typedef struct _tagKSJACK_SINK_INFORMATION
-{
-  KSJACK_SINK_CONNECTIONTYPE ConnType;              
-  WORD  ManufacturerId;                            
-  WORD  ProductId;                                  
-  WORD  AudioLatency;                               
-  BOOL  HDCPCapable;                                
-  BOOL  AICapable;                                  
-  UCHAR SinkDescriptionLength;                      
-  WCHAR SinkDescription[MAX_SINK_DESCRIPTION_NAME_LENGTH];
-  LUID  PortId;                                 
-}  KSJACK_SINK_INFORMATION, *PKSJACK_SINK_INFORMATION;
-
-#define JACKDESC2_PRESENCE_DETECT_CAPABILITY       0x00000001 
-#define JACKDESC2_DYNAMIC_FORMAT_CHANGE_CAPABILITY 0x00000002
-
-typedef struct _tagKSJACK_DESCRIPTION2
-{
-  DWORD              DeviceStateInfo;
-  DWORD              JackCapabilities;
-} KSJACK_DESCRIPTION2, *PKSJACK_DESCRIPTION2;
-
-#endif /* _KSMEDIA_ */
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ksproxy.h b/portaudio/src/hostapi/wasapi/mingw-include/ksproxy.h
deleted file mode 100644
index e6e049dab..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/ksproxy.h
+++ /dev/null
@@ -1,639 +0,0 @@
-/**
- * This file has no copyright assigned and is placed in the Public Domain.
- * This file is part of the w64 mingw-runtime package.
- * No warranty is given; refer to the file DISCLAIMER.PD within this package.
- */
-#ifndef __KSPROXY__
-#define __KSPROXY__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#undef KSDDKAPI
-#ifdef _KSDDK_
-#define KSDDKAPI
-#else
-#define KSDDKAPI DECLSPEC_IMPORT
-#endif
-
-#define STATIC_IID_IKsObject						\
-	0x423c13a2L,0x2070,0x11d0,0x9e,0xf7,0x00,0xaa,0x00,0xa2,0x16,0xa1
-
-#define STATIC_IID_IKsPinEx						\
-	0x7bb38260L,0xd19c,0x11d2,0xb3,0x8a,0x00,0xa0,0xc9,0x5e,0xc2,0x2e
-
-#define STATIC_IID_IKsPin						\
-	0xb61178d1L,0xa2d9,0x11cf,0x9e,0x53,0x00,0xaa,0x00,0xa2,0x16,0xa1
-
-#define STATIC_IID_IKsPinPipe						\
-	0xe539cd90L,0xa8b4,0x11d1,0x81,0x89,0x00,0xa0,0xc9,0x06,0x28,0x02
-
-#define STATIC_IID_IKsDataTypeHandler					\
-	0x5ffbaa02L,0x49a3,0x11d0,0x9f,0x36,0x00,0xaa,0x00,0xa2,0x16,0xa1
-
-#define STATIC_IID_IKsDataTypeCompletion				\
-	0x827D1A0EL,0x0F73,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#define STATIC_IID_IKsInterfaceHandler					\
-	0xD3ABC7E0L,0x9A61,0x11D0,0xA4,0x0D,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#define STATIC_IID_IKsClockPropertySet					\
-	0x5C5CBD84L,0xE755,0x11D0,0xAC,0x18,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#define STATIC_IID_IKsAllocator						\
-	0x8da64899L,0xc0d9,0x11d0,0x84,0x13,0x00,0x00,0xf8,0x22,0xfe,0x8a
-
-#define STATIC_IID_IKsAllocatorEx					\
-	0x091bb63aL,0x603f,0x11d1,0xb0,0x67,0x00,0xa0,0xc9,0x06,0x28,0x02
-
-#ifndef STATIC_IID_IKsPropertySet
-#define STATIC_IID_IKsPropertySet					\
-	0x31EFAC30L,0x515C,0x11d0,0xA9,0xAA,0x00,0xAA,0x00,0x61,0xBE,0x93
-#endif
-
-#define STATIC_IID_IKsTopology						\
-	0x28F54683L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#ifndef STATIC_IID_IKsControl
-#define STATIC_IID_IKsControl						\
-	0x28F54685L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96
-#endif
-
-#define STATIC_IID_IKsAggregateControl					\
-	0x7F40EAC0L,0x3947,0x11D2,0x87,0x4E,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#define STATIC_CLSID_Proxy						\
-	0x17CCA71BL,0xECD7,0x11D0,0xB9,0x08,0x00,0xA0,0xC9,0x22,0x31,0x96
-
-#ifdef _KS_
-
-DEFINE_GUIDEX(IID_IKsObject);
-
-DEFINE_GUIDEX(IID_IKsPin);
-
-DEFINE_GUIDEX(IID_IKsPinEx);
-
-DEFINE_GUIDEX(IID_IKsPinPipe);
-
-DEFINE_GUIDEX(IID_IKsDataTypeHandler);
-
-DEFINE_GUIDEX(IID_IKsDataTypeCompletion);
-
-DEFINE_GUIDEX(IID_IKsInterfaceHandler);
-
-DEFINE_GUIDEX(IID_IKsClockPropertySet);
-
-DEFINE_GUIDEX(IID_IKsAllocator);
-
-DEFINE_GUIDEX(IID_IKsAllocatorEx);
-
-#define IID_IKsQualityForwarder KSCATEGORY_QUALITY
-#define STATIC_IID_IKsQualityForwarder STATIC_KSCATEGORY_QUALITY
-
-typedef enum {
-  KsAllocatorMode_User,
-  KsAllocatorMode_Kernel
-} KSALLOCATORMODE;
-
-typedef enum {
-  FramingProp_Uninitialized,
-  FramingProp_None,
-  FramingProp_Old,
-  FramingProp_Ex
-} FRAMING_PROP;
-
-typedef FRAMING_PROP *PFRAMING_PROP;
-
-typedef enum {
-  Framing_Cache_Update,
-  Framing_Cache_ReadLast,
-  Framing_Cache_ReadOrig,
-  Framing_Cache_Write
-} FRAMING_CACHE_OPS;
-
-typedef struct {
-  LONGLONG MinTotalNominator;
-  LONGLONG MaxTotalNominator;
-  LONGLONG TotalDenominator;
-} OPTIMAL_WEIGHT_TOTALS;
-
-typedef struct IPin IPin;
-typedef struct IKsPin IKsPin;
-typedef struct IKsAllocator IKsAllocator;
-typedef struct IKsAllocatorEx IKsAllocatorEx;
-
-#define AllocatorStrategy_DontCare			0
-#define AllocatorStrategy_MinimizeNumberOfFrames	0x00000001
-#define AllocatorStrategy_MinimizeFrameSize		0x00000002
-#define AllocatorStrategy_MinimizeNumberOfAllocators	0x00000004
-#define AllocatorStrategy_MaximizeSpeed			0x00000008
-
-#define PipeFactor_None					0
-#define PipeFactor_UserModeUpstream			0x00000001
-#define PipeFactor_UserModeDownstream			0x00000002
-#define PipeFactor_MemoryTypes				0x00000004
-#define PipeFactor_Flags				0x00000008
-#define PipeFactor_PhysicalRanges			0x00000010
-#define PipeFactor_OptimalRanges			0x00000020
-#define PipeFactor_FixedCompression			0x00000040
-#define PipeFactor_UnknownCompression			0x00000080
-
-#define PipeFactor_Buffers				0x00000100
-#define PipeFactor_Align				0x00000200
-#define PipeFactor_PhysicalEnd				0x00000400
-#define PipeFactor_LogicalEnd				0x00000800
-
-typedef enum {
-  PipeState_DontCare,
-  PipeState_RangeNotFixed,
-  PipeState_RangeFixed,
-  PipeState_CompressionUnknown,
-  PipeState_Finalized
-} PIPE_STATE;
-
-typedef struct _PIPE_DIMENSIONS {
-  KS_COMPRESSION AllocatorPin;
-  KS_COMPRESSION MaxExpansionPin;
-  KS_COMPRESSION EndPin;
-} PIPE_DIMENSIONS,*PPIPE_DIMENSIONS;
-
-typedef enum {
-  Pipe_Allocator_None,
-  Pipe_Allocator_FirstPin,
-  Pipe_Allocator_LastPin,
-  Pipe_Allocator_MiddlePin
-} PIPE_ALLOCATOR_PLACE;
-
-typedef PIPE_ALLOCATOR_PLACE *PPIPE_ALLOCATOR_PLACE;
-
-typedef enum {
-  KS_MemoryTypeDontCare = 0,
-  KS_MemoryTypeKernelPaged,
-  KS_MemoryTypeKernelNonPaged,
-  KS_MemoryTypeDeviceHostMapped,
-  KS_MemoryTypeDeviceSpecific,
-  KS_MemoryTypeUser,
-  KS_MemoryTypeAnyHost
-} KS_LogicalMemoryType;
-
-typedef KS_LogicalMemoryType *PKS_LogicalMemoryType;
-
-typedef struct _PIPE_TERMINATION {
-  ULONG Flags;
-  ULONG OutsideFactors;
-  ULONG Weigth;
-  KS_FRAMING_RANGE PhysicalRange;
-  KS_FRAMING_RANGE_WEIGHTED OptimalRange;
-  KS_COMPRESSION Compression;
-} PIPE_TERMINATION;
-
-typedef struct _ALLOCATOR_PROPERTIES_EX
-{
-  long cBuffers;
-  long cbBuffer;
-  long cbAlign;
-  long cbPrefix;
-
-  GUID MemoryType;
-  GUID BusType;
-  PIPE_STATE State;
-  PIPE_TERMINATION Input;
-  PIPE_TERMINATION Output;
-  ULONG Strategy;
-  ULONG Flags;
-  ULONG Weight;
-  KS_LogicalMemoryType LogicalMemoryType;
-  PIPE_ALLOCATOR_PLACE AllocatorPlace;
-  PIPE_DIMENSIONS Dimensions;
-  KS_FRAMING_RANGE PhysicalRange;
-  IKsAllocatorEx *PrevSegment;
-  ULONG CountNextSegments;
-  IKsAllocatorEx **NextSegments;
-  ULONG InsideFactors;
-  ULONG NumberPins;
-} ALLOCATOR_PROPERTIES_EX;
-
-typedef ALLOCATOR_PROPERTIES_EX *PALLOCATOR_PROPERTIES_EX;
-
-#ifdef __STREAMS__
-
-struct IKsClockPropertySet;
-#undef INTERFACE
-#define INTERFACE IKsClockPropertySet
-DECLARE_INTERFACE_(IKsClockPropertySet,IUnknown)
-{
-  STDMETHOD(KsGetTime)			(THIS_
-						LONGLONG *Time
-					) PURE;
-  STDMETHOD(KsSetTime)			(THIS_
-						LONGLONG Time
-					) PURE;
-  STDMETHOD(KsGetPhysicalTime)		(THIS_
-						LONGLONG *Time
-					) PURE;
-  STDMETHOD(KsSetPhysicalTime)		(THIS_
-						LONGLONG Time
-					) PURE;
-  STDMETHOD(KsGetCorrelatedTime)	(THIS_
-						KSCORRELATED_TIME *CorrelatedTime
-					) PURE;
-  STDMETHOD(KsSetCorrelatedTime)	(THIS_
-						KSCORRELATED_TIME *CorrelatedTime
-					) PURE;
-  STDMETHOD(KsGetCorrelatedPhysicalTime)(THIS_
-						KSCORRELATED_TIME *CorrelatedTime
-					) PURE;
-  STDMETHOD(KsSetCorrelatedPhysicalTime)(THIS_
-						KSCORRELATED_TIME *CorrelatedTime
-					) PURE;
-  STDMETHOD(KsGetResolution)		(THIS_
-						KSRESOLUTION *Resolution
-					) PURE;
-  STDMETHOD(KsGetState)			(THIS_
-						KSSTATE *State
-					) PURE;
-};
-
-struct IKsAllocator;
-#undef INTERFACE
-#define INTERFACE IKsAllocator
-DECLARE_INTERFACE_(IKsAllocator,IUnknown)
-{
-  STDMETHOD_(HANDLE,KsGetAllocatorHandle)(THIS) PURE;
-  STDMETHOD_(KSALLOCATORMODE,KsGetAllocatorMode)(THIS) PURE;
-  STDMETHOD(KsGetAllocatorStatus)	(THIS_
-						PKSSTREAMALLOCATOR_STATUS AllocatorStatus
-					) PURE;
-  STDMETHOD_(VOID,KsSetAllocatorMode)	(THIS_
-						KSALLOCATORMODE Mode
-					) PURE;
-};
-
-struct IKsAllocatorEx;
-#undef INTERFACE
-#define INTERFACE IKsAllocatorEx
-DECLARE_INTERFACE_(IKsAllocatorEx,IKsAllocator)
-{
-  STDMETHOD_(PALLOCATOR_PROPERTIES_EX,KsGetProperties)(THIS) PURE;
-  STDMETHOD_(VOID,KsSetProperties)	(THIS_
-						PALLOCATOR_PROPERTIES_EX
-					) PURE;
-  STDMETHOD_(VOID,KsSetAllocatorHandle)	(THIS_
-						HANDLE AllocatorHandle
-					) PURE;
-  STDMETHOD_(HANDLE,KsCreateAllocatorAndGetHandle)(THIS_
-						IKsPin *KsPin
-					) PURE;
-};
-
-typedef enum {
-  KsPeekOperation_PeekOnly,
-  KsPeekOperation_AddRef
-} KSPEEKOPERATION;
-
-typedef struct _KSSTREAM_SEGMENT *PKSSTREAM_SEGMENT;
-struct IKsPin;
-
-#undef INTERFACE
-#define INTERFACE IKsPin
-DECLARE_INTERFACE_(IKsPin,IUnknown)
-{
-  STDMETHOD(KsQueryMediums)		(THIS_
-						PKSMULTIPLE_ITEM *MediumList
-					) PURE;
-  STDMETHOD(KsQueryInterfaces)		(THIS_
-						PKSMULTIPLE_ITEM *InterfaceList
-					) PURE;
-  STDMETHOD(KsCreateSinkPinHandle)	(THIS_
-						KSPIN_INTERFACE& Interface,
-						KSPIN_MEDIUM& Medium
-					) PURE;
-  STDMETHOD(KsGetCurrentCommunication)	(THIS_
-						KSPIN_COMMUNICATION *Communication,
-						KSPIN_INTERFACE *Interface,
-						KSPIN_MEDIUM *Medium
-					) PURE;
-  STDMETHOD(KsPropagateAcquire)		(THIS) PURE;
-  STDMETHOD(KsDeliver)			(THIS_
-						IMediaSample *Sample,
-						ULONG Flags
-					) PURE;
-  STDMETHOD(KsMediaSamplesCompleted)	(THIS_
-						PKSSTREAM_SEGMENT StreamSegment
-					) PURE;
-  STDMETHOD_(IMemAllocator *,KsPeekAllocator)(THIS_
-						KSPEEKOPERATION Operation
-					) PURE;
-  STDMETHOD(KsReceiveAllocator)		(THIS_
-						IMemAllocator *MemAllocator
-					) PURE;
-  STDMETHOD(KsRenegotiateAllocator)	(THIS) PURE;
-  STDMETHOD_(LONG,KsIncrementPendingIoCount)(THIS) PURE;
-  STDMETHOD_(LONG,KsDecrementPendingIoCount)(THIS) PURE;
-  STDMETHOD(KsQualityNotify)		(THIS_
-						ULONG Proportion,
-						REFERENCE_TIME TimeDelta
-					) PURE;
-};
-
-struct IKsPinEx;
-#undef INTERFACE
-#define INTERFACE IKsPinEx
-DECLARE_INTERFACE_(IKsPinEx,IKsPin)
-{
-  STDMETHOD_(VOID,KsNotifyError)	(THIS_
-						IMediaSample *Sample,
-						HRESULT hr
-					) PURE;
-};
-
-struct IKsPinPipe;
-#undef INTERFACE
-#define INTERFACE IKsPinPipe
-DECLARE_INTERFACE_(IKsPinPipe,IUnknown)
-{
-  STDMETHOD(KsGetPinFramingCache)	(THIS_
-						PKSALLOCATOR_FRAMING_EX *FramingEx,
-						PFRAMING_PROP FramingProp,
-						FRAMING_CACHE_OPS Option
-					) PURE;
-  STDMETHOD(KsSetPinFramingCache)	(THIS_
-						PKSALLOCATOR_FRAMING_EX FramingEx,
-						PFRAMING_PROP FramingProp,
-						FRAMING_CACHE_OPS Option
-					) PURE;
-  STDMETHOD_(IPin*,KsGetConnectedPin)	(THIS) PURE;
-  STDMETHOD_(IKsAllocatorEx*,KsGetPipe)	(THIS_
-						KSPEEKOPERATION Operation
-					) PURE;
-  STDMETHOD(KsSetPipe)			(THIS_
-						IKsAllocatorEx *KsAllocator
-					) PURE;
-  STDMETHOD_(ULONG,KsGetPipeAllocatorFlag)(THIS) PURE;
-  STDMETHOD(KsSetPipeAllocatorFlag)	(THIS_
-						ULONG Flag
-					) PURE;
-  STDMETHOD_(GUID,KsGetPinBusCache)	(THIS) PURE;
-  STDMETHOD(KsSetPinBusCache)		(THIS_
-						GUID Bus
-					) PURE;
-  STDMETHOD_(PWCHAR,KsGetPinName)	(THIS) PURE;
-  STDMETHOD_(PWCHAR,KsGetFilterName)	(THIS) PURE;
-};
-
-struct IKsPinFactory;
-#undef INTERFACE
-#define INTERFACE IKsPinFactory
-DECLARE_INTERFACE_(IKsPinFactory,IUnknown)
-{
-  STDMETHOD(KsPinFactory)		(THIS_
-						ULONG *PinFactory
-					) PURE;
-};
-
-typedef enum {
-  KsIoOperation_Write,
-  KsIoOperation_Read
-} KSIOOPERATION;
-
-struct IKsDataTypeHandler;
-#undef INTERFACE
-#define INTERFACE IKsDataTypeHandler
-DECLARE_INTERFACE_(IKsDataTypeHandler,IUnknown)
-{
-  STDMETHOD(KsCompleteIoOperation)	(THIS_
-						IMediaSample *Sample,
-						PVOID StreamHeader,
-						KSIOOPERATION IoOperation,
-						WINBOOL Cancelled
-					) PURE;
-  STDMETHOD(KsIsMediaTypeInRanges)	(THIS_
-						PVOID DataRanges
-					) PURE;
-  STDMETHOD(KsPrepareIoOperation)	(THIS_
-						IMediaSample *Sample,
-						PVOID StreamHeader,
-						KSIOOPERATION IoOperation
-					) PURE;
-  STDMETHOD(KsQueryExtendedSize)	(THIS_
-						ULONG *ExtendedSize
-					) PURE;
-  STDMETHOD(KsSetMediaType)		(THIS_
-						const AM_MEDIA_TYPE *AmMediaType
-					) PURE;
-};
-
-struct IKsDataTypeCompletion;
-#undef INTERFACE
-#define INTERFACE IKsDataTypeCompletion
-DECLARE_INTERFACE_(IKsDataTypeCompletion,IUnknown)
-{
-  STDMETHOD(KsCompleteMediaType)	(THIS_
-						HANDLE FilterHandle,
-						ULONG PinFactoryId,
-						AM_MEDIA_TYPE *AmMediaType
-					) PURE;
-};
-
-struct IKsInterfaceHandler;
-#undef INTERFACE
-#define INTERFACE IKsInterfaceHandler
-DECLARE_INTERFACE_(IKsInterfaceHandler,IUnknown)
-{
-  STDMETHOD(KsSetPin)			(THIS_
-						IKsPin *KsPin
-					) PURE;
-  STDMETHOD(KsProcessMediaSamples)	(THIS_
-						IKsDataTypeHandler *KsDataTypeHandler,
-						IMediaSample **SampleList,
-						PLONG SampleCount,
-						KSIOOPERATION IoOperation,
-						PKSSTREAM_SEGMENT *StreamSegment
-					) PURE;
-  STDMETHOD(KsCompleteIo)		(THIS_
-						PKSSTREAM_SEGMENT StreamSegment
-					) PURE;
-};
-
-typedef struct _KSSTREAM_SEGMENT {
-  IKsInterfaceHandler *KsInterfaceHandler;
-  IKsDataTypeHandler *KsDataTypeHandler;
-  KSIOOPERATION IoOperation;
-  HANDLE CompletionEvent;
-} KSSTREAM_SEGMENT;
-
-struct IKsObject;
-#undef INTERFACE
-#define INTERFACE IKsObject
-DECLARE_INTERFACE_(IKsObject,IUnknown)
-{
-  STDMETHOD_(HANDLE,KsGetObjectHandle)	(THIS) PURE;
-};
-
-struct IKsQualityForwarder;
-#undef INTERFACE
-#define INTERFACE IKsQualityForwarder
-DECLARE_INTERFACE_(IKsQualityForwarder,IKsObject)
-{
-  STDMETHOD_(VOID,KsFlushClient)	(THIS_
-						IKsPin *Pin
-					) PURE;
-};
-
-struct IKsNotifyEvent;
-#undef INTERFACE
-#define INTERFACE IKsNotifyEvent
-DECLARE_INTERFACE_(IKsNotifyEvent,IUnknown)
-{
-  STDMETHOD(KsNotifyEvent)		(THIS_
-						ULONG Event,
-						ULONG_PTR lParam1,
-						ULONG_PTR lParam2
-					) PURE;
-};
-
-KSDDKAPI HRESULT WINAPI KsResolveRequiredAttributes(PKSDATARANGE DataRange,PKSMULTIPLE_ITEM Attributes);
-KSDDKAPI HRESULT WINAPI KsOpenDefaultDevice(REFGUID Category,ACCESS_MASK Access,PHANDLE DeviceHandle);
-KSDDKAPI HRESULT WINAPI KsSynchronousDeviceControl(HANDLE Handle,ULONG IoControl,PVOID InBuffer,ULONG InLength,PVOID OutBuffer,ULONG OutLength,PULONG BytesReturned);
-KSDDKAPI HRESULT WINAPI KsGetMultiplePinFactoryItems(HANDLE FilterHandle,ULONG PinFactoryId,ULONG PropertyId,PVOID *Items);
-KSDDKAPI HRESULT WINAPI KsGetMediaTypeCount(HANDLE FilterHandle,ULONG PinFactoryId,ULONG *MediaTypeCount);
-KSDDKAPI HRESULT WINAPI KsGetMediaType(int Position,AM_MEDIA_TYPE *AmMediaType,HANDLE FilterHandle,ULONG PinFactoryId);
-#endif /* __STREAMS__ */
-
-#ifndef _IKsPropertySet_
-DEFINE_GUIDEX(IID_IKsPropertySet);
-#endif
-
-#ifndef _IKsControl_
-DEFINE_GUIDEX(IID_IKsControl);
-#endif
-
-DEFINE_GUIDEX(IID_IKsAggregateControl);
-#ifndef _IKsTopology_
-DEFINE_GUIDEX(IID_IKsTopology);
-#endif
-DEFINE_GUIDSTRUCT("17CCA71B-ECD7-11D0-B908-00A0C9223196",CLSID_Proxy);
-#define CLSID_Proxy DEFINE_GUIDNAMED(CLSID_Proxy)
-
-#else /* _KS_ */
-
-#ifndef _IKsPropertySet_
-DEFINE_GUID(IID_IKsPropertySet,STATIC_IID_IKsPropertySet);
-#endif
-
-DEFINE_GUID(CLSID_Proxy,STATIC_CLSID_Proxy);
-
-#endif /* _KS_ */
-
-#ifndef _IKsPropertySet_
-#define _IKsPropertySet_
-#define KSPROPERTY_SUPPORT_GET 1
-#define KSPROPERTY_SUPPORT_SET 2
-
-#ifdef DECLARE_INTERFACE_
-struct IKsPropertySet;
-#undef INTERFACE
-#define INTERFACE IKsPropertySet
-DECLARE_INTERFACE_(IKsPropertySet,IUnknown)
-{
-  STDMETHOD(Set)			(THIS_
-						REFGUID PropSet,
-						ULONG Id,
-						LPVOID InstanceData,
-						ULONG InstanceLength,
-						LPVOID PropertyData,
-						ULONG DataLength
-					) PURE;
-  STDMETHOD(Get)			(THIS_
-						REFGUID PropSet,
-						ULONG Id,
-						LPVOID InstanceData,
-						ULONG InstanceLength,
-						LPVOID PropertyData,
-						ULONG DataLength,
-						ULONG *BytesReturned
-					) PURE;
-  STDMETHOD(QuerySupported)		(THIS_
-						REFGUID PropSet,
-						ULONG Id,
-						ULONG *TypeSupport
-					) PURE;
-};
-#endif /* DECLARE_INTERFACE_ */
-#endif /* _IKsPropertySet_ */
-
-#ifndef _IKsControl_
-#define _IKsControl_
-#ifdef DECLARE_INTERFACE_
-struct IKsControl;
-#undef INTERFACE
-#define INTERFACE IKsControl
-DECLARE_INTERFACE_(IKsControl,IUnknown)
-{
-  STDMETHOD(KsProperty)			(THIS_
-						PKSPROPERTY Property,
-						ULONG PropertyLength,
-						LPVOID PropertyData,
-						ULONG DataLength,
-						ULONG *BytesReturned
-					) PURE;
-  STDMETHOD(KsMethod)			(THIS_
-						PKSMETHOD Method,
-						ULONG MethodLength,
-						LPVOID MethodData,
-						ULONG DataLength,
-						ULONG *BytesReturned
-					) PURE;
-  STDMETHOD(KsEvent)			(THIS_
-						PKSEVENT Event,
-						ULONG EventLength,
-						LPVOID EventData,
-						ULONG DataLength,
-						ULONG *BytesReturned
-					) PURE;
-};
-#endif /* DECLARE_INTERFACE_ */
-#endif /* _IKsControl_ */
-
-#ifdef DECLARE_INTERFACE_
-struct IKsAggregateControl;
-#undef INTERFACE
-#define INTERFACE IKsAggregateControl
-DECLARE_INTERFACE_(IKsAggregateControl,IUnknown)
-{
-  STDMETHOD(KsAddAggregate)		(THIS_
-						REFGUID AggregateClass
-					) PURE;
-  STDMETHOD(KsRemoveAggregate)		(THIS_
-						REFGUID AggregateClass
-					) PURE;
-};
-#endif /* DECLARE_INTERFACE_ */
-
-#ifndef _IKsTopology_
-#define _IKsTopology_
-#ifdef DECLARE_INTERFACE_
-struct IKsTopology;
-#undef INTERFACE
-#define INTERFACE IKsTopology
-DECLARE_INTERFACE_(IKsTopology,IUnknown)
-{
-  STDMETHOD(CreateNodeInstance)		(THIS_
-						ULONG NodeId,
-						ULONG Flags,
-						ACCESS_MASK DesiredAccess,
-						IUnknown *UnkOuter,
-						REFGUID InterfaceId,
-						LPVOID *Interface
-					) PURE;
-};
-#endif /* DECLARE_INTERFACE_ */
-#endif /* _IKsTopology_ */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __KSPROXY__ */
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/ksuuids.h b/portaudio/src/hostapi/wasapi/mingw-include/ksuuids.h
deleted file mode 100644
index 7d0efff65..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/ksuuids.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * This file has no copyright assigned and is placed in the Public Domain.
- * This file is part of the w64 mingw-runtime package.
- * No warranty is given; refer to the file DISCLAIMER.PD within this package.
- */
-
-OUR_GUID_ENTRY(MEDIATYPE_MPEG2_PACK,
-		0x36523B13,0x8EE5,0x11d1,0x8C,0xA3,0x00,0x60,0xB0,0x57,0x66,0x4A)
-
-OUR_GUID_ENTRY(MEDIATYPE_MPEG2_PES,
-		0xe06d8020,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIATYPE_MPEG2_SECTIONS,
-		0x455f176c,0x4b06,0x47ce,0x9a,0xef,0x8c,0xae,0xf7,0x3d,0xf7,0xb5)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_ATSC_SI,
-		0xb3c7397c,0xd303,0x414d,0xb3,0x3c,0x4e,0xd2,0xc9,0xd2,0x97,0x33)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DVB_SI,
-		0xe9dd31a3,0x221d,0x4adb,0x85,0x32,0x9a,0xf3,0x9,0xc1,0xa4,0x8)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_MPEG2DATA,
-		0xc892e55b,0x252d,0x42b5,0xa3,0x16,0xd9,0x97,0xe7,0xa5,0xd9,0x95)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_MPEG2_VIDEO,
-		0xe06d8026,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(FORMAT_MPEG2_VIDEO,
-		0xe06d80e3,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x5f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(FORMAT_VIDEOINFO2,
-		0xf72a76A0L,0xeb0a,0x11d0,0xac,0xe4,0x0,0x0,0xc0,0xcc,0x16,0xba)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_MPEG2_PROGRAM,
-		0xe06d8022,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_MPEG2_TRANSPORT,
-		0xe06d8023,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_MPEG2_TRANSPORT_STRIDE,
-		0x138aa9a4,0x1ee2,0x4c5b,0x98,0x8e,0x19,0xab,0xfd,0xbc,0x8a,0x11)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_MPEG2_AUDIO,
-		0xe06d802b,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DOLBY_AC3,
-		0xe06d802c,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DVD_SUBPICTURE,
-		0xe06d802d,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DVD_LPCM_AUDIO,
-		0xe06d8032,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DTS,
-		0xe06d8033,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_SDDS,
-		0xe06d8034,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIATYPE_DVD_ENCRYPTED_PACK,
-		0xed0b916a,0x044d,0x11d1,0xaa,0x78,0x00,0xc0,0x04f,0xc3,0x1d,0x60)
-
-OUR_GUID_ENTRY(MEDIATYPE_DVD_NAVIGATION,
-		0xe06d802e,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DVD_NAVIGATION_PCI,
-		0xe06d802f,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DVD_NAVIGATION_DSI,
-		0xe06d8030,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(MEDIASUBTYPE_DVD_NAVIGATION_PROVIDER,
-		0xe06d8031,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(FORMAT_MPEG2Video,
-		0xe06d80e3,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(FORMAT_DolbyAC3,
-		0xe06d80e4,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(FORMAT_MPEG2Audio,
-		0xe06d80e5,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(FORMAT_DVD_LPCMAudio,
-		0xe06d80e6,0xdb46,0x11cf,0xb4,0xd1,0x00,0x80,0x05f,0x6c,0xbb,0xea)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_AC3,
-		0xBFABE720,0x6E1F,0x11D0,0xBC,0xF2,0x44,0x45,0x53,0x54,0x00,0x00)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_DvdSubPic,
-		0xac390460,0x43af,0x11d0,0xbd,0x6a,0x00,0x35,0x05,0xc1,0x03,0xa9)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_CopyProt,
-		0x0E8A0A40,0x6AEF,0x11D0,0x9E,0xD0,0x00,0xA0,0x24,0xCA,0x19,0xB3)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_TSRateChange,
-		0xa503c5c0,0x1d1d,0x11d1,0xad,0x80,0x44,0x45,0x53,0x54,0x0,0x0)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_DVD_RateChange,
-		0x3577eb09,0x9582,0x477f,0xb2,0x9c,0xb0,0xc4,0x52,0xa4,0xff,0x9a)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_DvdKaraoke,
-		0xae4720ae,0xaa71,0x42d8,0xb8,0x2a,0xff,0xfd,0xf5,0x8b,0x76,0xfd)
-
-OUR_GUID_ENTRY(AM_KSPROPSETID_FrameStep,
-		0xc830acbd,0xab07,0x492f,0x88,0x52,0x45,0xb6,0x98,0x7c,0x29,0x79)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_CAPTURE,
-		0x65E8773DL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_RENDER,
-		0x65E8773EL,0x8F56,0x11D0,0xA3,0xB9,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_DATACOMPRESSOR,
-		0x1E84C900L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_AUDIO,
-		0x6994AD04L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_VIDEO,
-		0x6994AD05L,0x93EF,0x11D0,0xA3,0xCC,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_TVTUNER,
-		0xa799a800L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_CROSSBAR,
-		0xa799a801L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_TVAUDIO,
-		0xa799a802L,0xa46d,0x11d0,0xa1,0x8c,0x00,0xa0,0x24,0x01,0xdc,0xd4)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_VBICODEC,
-		0x07dad660L,0x22f1,0x11d1,0xa9,0xf4,0x00,0xc0,0x4f,0xbb,0xde,0x8f)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_VBICODEC_MI,
-		0x9c24a977,0x951,0x451a,0x80,0x6,0xe,0x49,0xbd,0x28,0xcd,0x5f)
-
-OUR_GUID_ENTRY(AM_KSCATEGORY_SPLITTER,
-		0x0A4252A0L,0x7E70,0x11D0,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00)
-
-OUR_GUID_ENTRY(IID_IKsInterfaceHandler,
-		0xD3ABC7E0L,0x9A61,0x11D0,0xA4,0x0D,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(IID_IKsDataTypeHandler,
-		0x5FFBAA02L,0x49A3,0x11D0,0x9F,0x36,0x00,0xAA,0x00,0xA2,0x16,0xA1)
-
-OUR_GUID_ENTRY(IID_IKsPin,
-		0xb61178d1L,0xa2d9,0x11cf,0x9e,0x53,0x00,0xaa,0x00,0xa2,0x16,0xa1)
-
-OUR_GUID_ENTRY(IID_IKsControl,
-		0x28F54685L,0x06FD,0x11D2,0xB2,0x7A,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(IID_IKsPinFactory,
-		0xCD5EBE6BL,0x8B6E,0x11D1,0x8A,0xE0,0x00,0xA0,0xC9,0x22,0x31,0x96)
-
-OUR_GUID_ENTRY(AM_INTERFACESETID_Standard,
-		0x1A8766A0L,0x62CE,0x11CF,0xA5,0xD6,0x28,0xDB,0x04,0xC1,0x00,0x00)
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/mmdeviceapi.h b/portaudio/src/hostapi/wasapi/mingw-include/mmdeviceapi.h
deleted file mode 100644
index c1e7925f6..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/mmdeviceapi.h
+++ /dev/null
@@ -1,929 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for mmdeviceapi.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 500
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __mmdeviceapi_h__
-#define __mmdeviceapi_h__
-
-#if __GNUC__ >=3
-#pragma GCC system_header
-#endif
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-#ifndef __IMMNotificationClient_FWD_DEFINED__
-#define __IMMNotificationClient_FWD_DEFINED__
-typedef interface IMMNotificationClient IMMNotificationClient;
-#endif 	/* __IMMNotificationClient_FWD_DEFINED__ */
-
-
-#ifndef __IMMDevice_FWD_DEFINED__
-#define __IMMDevice_FWD_DEFINED__
-typedef interface IMMDevice IMMDevice;
-#endif 	/* __IMMDevice_FWD_DEFINED__ */
-
-
-#ifndef __IMMDeviceCollection_FWD_DEFINED__
-#define __IMMDeviceCollection_FWD_DEFINED__
-typedef interface IMMDeviceCollection IMMDeviceCollection;
-#endif 	/* __IMMDeviceCollection_FWD_DEFINED__ */
-
-
-#ifndef __IMMEndpoint_FWD_DEFINED__
-#define __IMMEndpoint_FWD_DEFINED__
-typedef interface IMMEndpoint IMMEndpoint;
-#endif 	/* __IMMEndpoint_FWD_DEFINED__ */
-
-
-#ifndef __IMMDeviceEnumerator_FWD_DEFINED__
-#define __IMMDeviceEnumerator_FWD_DEFINED__
-typedef interface IMMDeviceEnumerator IMMDeviceEnumerator;
-#endif 	/* __IMMDeviceEnumerator_FWD_DEFINED__ */
-
-
-#ifndef __IMMDeviceActivator_FWD_DEFINED__
-#define __IMMDeviceActivator_FWD_DEFINED__
-typedef interface IMMDeviceActivator IMMDeviceActivator;
-#endif 	/* __IMMDeviceActivator_FWD_DEFINED__ */
-
-
-#ifndef __MMDeviceEnumerator_FWD_DEFINED__
-#define __MMDeviceEnumerator_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class MMDeviceEnumerator MMDeviceEnumerator;
-#else
-typedef struct MMDeviceEnumerator MMDeviceEnumerator;
-#endif /* __cplusplus */
-
-#endif 	/* __MMDeviceEnumerator_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "unknwn.h"
-#include "propsys.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_mmdeviceapi_0000_0000 */
-/* [local] */ 
-
-#define E_NOTFOUND HRESULT_FROM_WIN32(ERROR_NOT_FOUND)
-#define E_UNSUPPORTED_TYPE HRESULT_FROM_WIN32(ERROR_UNSUPPORTED_TYPE)
-#define DEVICE_STATE_ACTIVE      0x00000001
-#define DEVICE_STATE_DISABLED    0x00000002
-#define DEVICE_STATE_NOTPRESENT  0x00000004
-#define DEVICE_STATE_UNPLUGGED   0x00000008
-#define DEVICE_STATEMASK_ALL     0x0000000f
-#ifdef DEFINE_PROPERTYKEY
-#undef DEFINE_PROPERTYKEY
-#endif
-#ifdef INITGUID
-#define DEFINE_PROPERTYKEY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8, pid) EXTERN_C const PROPERTYKEY name = { { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }, pid }
-#else
-#define DEFINE_PROPERTYKEY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8, pid) EXTERN_C const PROPERTYKEY name
-#endif // INITGUID
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 0); 
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_ControlPanelPageProvider, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 1); 
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_Association, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 2);
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_PhysicalSpeakers, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 3);
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 4);
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_Disable_SysFx, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 5);
-#define ENDPOINT_SYSFX_ENABLED          0x00000000  // System Effects are enabled.
-#define ENDPOINT_SYSFX_DISABLED         0x00000001  // System Effects are disabled.
-DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FullRangeSpeakers, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, 6);
-DEFINE_PROPERTYKEY(PKEY_AudioEngine_DeviceFormat, 0xf19f064d, 0x82c, 0x4e27, 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, 0); 
-typedef struct tagDIRECTX_AUDIO_ACTIVATION_PARAMS
-    {
-    DWORD cbDirectXAudioActivationParams;
-    GUID guidAudioSession;
-    DWORD dwAudioStreamFlags;
-    } 	DIRECTX_AUDIO_ACTIVATION_PARAMS;
-
-typedef struct tagDIRECTX_AUDIO_ACTIVATION_PARAMS *PDIRECTX_AUDIO_ACTIVATION_PARAMS;
-
-typedef /* [public][public][public][public][public] */ 
-enum __MIDL___MIDL_itf_mmdeviceapi_0000_0000_0001
-    {	eRender	= 0,
-	eCapture	= ( eRender + 1 ) ,
-	eAll	= ( eCapture + 1 ) ,
-	EDataFlow_enum_count	= ( eAll + 1 ) 
-    } 	EDataFlow;
-
-typedef /* [public][public][public] */ 
-enum __MIDL___MIDL_itf_mmdeviceapi_0000_0000_0002
-    {	eConsole	= 0,
-	eMultimedia	= ( eConsole + 1 ) ,
-	eCommunications	= ( eMultimedia + 1 ) ,
-	ERole_enum_count	= ( eCommunications + 1 ) 
-    } 	ERole;
-
-typedef /* [public] */ 
-enum __MIDL___MIDL_itf_mmdeviceapi_0000_0000_0003
-    {	RemoteNetworkDevice	= 0,
-	Speakers	= ( RemoteNetworkDevice + 1 ) ,
-	LineLevel	= ( Speakers + 1 ) ,
-	Headphones	= ( LineLevel + 1 ) ,
-	Microphone	= ( Headphones + 1 ) ,
-	Headset	= ( Microphone + 1 ) ,
-	Handset	= ( Headset + 1 ) ,
-	UnknownDigitalPassthrough	= ( Handset + 1 ) ,
-	SPDIF	= ( UnknownDigitalPassthrough + 1 ) ,
-	HDMI	= ( SPDIF + 1 ) ,
-	UnknownFormFactor	= ( HDMI + 1 ) 
-    } 	EndpointFormFactor;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_mmdeviceapi_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_mmdeviceapi_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IMMNotificationClient_INTERFACE_DEFINED__
-#define __IMMNotificationClient_INTERFACE_DEFINED__
-
-/* interface IMMNotificationClient */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IMMNotificationClient;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("7991EEC9-7E89-4D85-8390-6C703CEC60C0")
-    IMMNotificationClient : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnDeviceStateChanged( 
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId,
-            /* [in] */ 
-            __in  DWORD dwNewState) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnDeviceAdded( 
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnDeviceRemoved( 
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged( 
-            /* [in] */ 
-            __in  EDataFlow flow,
-            /* [in] */ 
-            __in  ERole role,
-            /* [in] */ 
-            __in  LPCWSTR pwstrDefaultDeviceId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OnPropertyValueChanged( 
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId,
-            /* [in] */ 
-            __in  const PROPERTYKEY key) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMMNotificationClientVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMMNotificationClient * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMMNotificationClient * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMMNotificationClient * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OnDeviceStateChanged )( 
-            IMMNotificationClient * This,
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId,
-            /* [in] */ 
-            __in  DWORD dwNewState);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OnDeviceAdded )( 
-            IMMNotificationClient * This,
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OnDeviceRemoved )( 
-            IMMNotificationClient * This,
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OnDefaultDeviceChanged )( 
-            IMMNotificationClient * This,
-            /* [in] */ 
-            __in  EDataFlow flow,
-            /* [in] */ 
-            __in  ERole role,
-            /* [in] */ 
-            __in  LPCWSTR pwstrDefaultDeviceId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OnPropertyValueChanged )( 
-            IMMNotificationClient * This,
-            /* [in] */ 
-            __in  LPCWSTR pwstrDeviceId,
-            /* [in] */ 
-            __in  const PROPERTYKEY key);
-        
-        END_INTERFACE
-    } IMMNotificationClientVtbl;
-
-    interface IMMNotificationClient
-    {
-        CONST_VTBL struct IMMNotificationClientVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMMNotificationClient_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMMNotificationClient_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMMNotificationClient_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMMNotificationClient_OnDeviceStateChanged(This,pwstrDeviceId,dwNewState)	\
-    ( (This)->lpVtbl -> OnDeviceStateChanged(This,pwstrDeviceId,dwNewState) ) 
-
-#define IMMNotificationClient_OnDeviceAdded(This,pwstrDeviceId)	\
-    ( (This)->lpVtbl -> OnDeviceAdded(This,pwstrDeviceId) ) 
-
-#define IMMNotificationClient_OnDeviceRemoved(This,pwstrDeviceId)	\
-    ( (This)->lpVtbl -> OnDeviceRemoved(This,pwstrDeviceId) ) 
-
-#define IMMNotificationClient_OnDefaultDeviceChanged(This,flow,role,pwstrDefaultDeviceId)	\
-    ( (This)->lpVtbl -> OnDefaultDeviceChanged(This,flow,role,pwstrDefaultDeviceId) ) 
-
-#define IMMNotificationClient_OnPropertyValueChanged(This,pwstrDeviceId,key)	\
-    ( (This)->lpVtbl -> OnPropertyValueChanged(This,pwstrDeviceId,key) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMMNotificationClient_INTERFACE_DEFINED__ */
-
-
-#ifndef __IMMDevice_INTERFACE_DEFINED__
-#define __IMMDevice_INTERFACE_DEFINED__
-
-/* interface IMMDevice */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IMMDevice;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("D666063F-1587-4E43-81F1-B948E807363F")
-    IMMDevice : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Activate( 
-            /* [in] */ 
-            __in  REFIID iid,
-            /* [in] */ 
-            __in  DWORD dwClsCtx,
-            /* [unique][in] */ 
-            __in_opt  PROPVARIANT *pActivationParams,
-            /* [iid_is][out] */ 
-            __out  void **ppInterface) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE OpenPropertyStore( 
-            /* [in] */ 
-            __in  DWORD stgmAccess,
-            /* [out] */ 
-            __out  IPropertyStore **ppProperties) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetId( 
-            /* [out] */ 
-            __deref_out  LPWSTR *ppstrId) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetState( 
-            /* [out] */ 
-            __out  DWORD *pdwState) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMMDeviceVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMMDevice * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMMDevice * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMMDevice * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Activate )( 
-            IMMDevice * This,
-            /* [in] */ 
-            __in  REFIID iid,
-            /* [in] */ 
-            __in  DWORD dwClsCtx,
-            /* [unique][in] */ 
-            __in_opt  PROPVARIANT *pActivationParams,
-            /* [iid_is][out] */ 
-            __out  void **ppInterface);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *OpenPropertyStore )( 
-            IMMDevice * This,
-            /* [in] */ 
-            __in  DWORD stgmAccess,
-            /* [out] */ 
-            __out  IPropertyStore **ppProperties);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetId )( 
-            IMMDevice * This,
-            /* [out] */ 
-            __deref_out  LPWSTR *ppstrId);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetState )( 
-            IMMDevice * This,
-            /* [out] */ 
-            __out  DWORD *pdwState);
-        
-        END_INTERFACE
-    } IMMDeviceVtbl;
-
-    interface IMMDevice
-    {
-        CONST_VTBL struct IMMDeviceVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMMDevice_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMMDevice_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMMDevice_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMMDevice_Activate(This,iid,dwClsCtx,pActivationParams,ppInterface)	\
-    ( (This)->lpVtbl -> Activate(This,iid,dwClsCtx,pActivationParams,ppInterface) ) 
-
-#define IMMDevice_OpenPropertyStore(This,stgmAccess,ppProperties)	\
-    ( (This)->lpVtbl -> OpenPropertyStore(This,stgmAccess,ppProperties) ) 
-
-#define IMMDevice_GetId(This,ppstrId)	\
-    ( (This)->lpVtbl -> GetId(This,ppstrId) ) 
-
-#define IMMDevice_GetState(This,pdwState)	\
-    ( (This)->lpVtbl -> GetState(This,pdwState) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMMDevice_INTERFACE_DEFINED__ */
-
-
-#ifndef __IMMDeviceCollection_INTERFACE_DEFINED__
-#define __IMMDeviceCollection_INTERFACE_DEFINED__
-
-/* interface IMMDeviceCollection */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IMMDeviceCollection;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E")
-    IMMDeviceCollection : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCount( 
-            /* [out] */ 
-            __out  UINT *pcDevices) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Item( 
-            /* [in] */ 
-            __in  UINT nDevice,
-            /* [out] */ 
-            __out  IMMDevice **ppDevice) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMMDeviceCollectionVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMMDeviceCollection * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMMDeviceCollection * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMMDeviceCollection * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IMMDeviceCollection * This,
-            /* [out] */ 
-            __out  UINT *pcDevices);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Item )( 
-            IMMDeviceCollection * This,
-            /* [in] */ 
-            __in  UINT nDevice,
-            /* [out] */ 
-            __out  IMMDevice **ppDevice);
-        
-        END_INTERFACE
-    } IMMDeviceCollectionVtbl;
-
-    interface IMMDeviceCollection
-    {
-        CONST_VTBL struct IMMDeviceCollectionVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMMDeviceCollection_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMMDeviceCollection_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMMDeviceCollection_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMMDeviceCollection_GetCount(This,pcDevices)	\
-    ( (This)->lpVtbl -> GetCount(This,pcDevices) ) 
-
-#define IMMDeviceCollection_Item(This,nDevice,ppDevice)	\
-    ( (This)->lpVtbl -> Item(This,nDevice,ppDevice) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMMDeviceCollection_INTERFACE_DEFINED__ */
-
-
-#ifndef __IMMEndpoint_INTERFACE_DEFINED__
-#define __IMMEndpoint_INTERFACE_DEFINED__
-
-/* interface IMMEndpoint */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IMMEndpoint;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("1BE09788-6894-4089-8586-9A2A6C265AC5")
-    IMMEndpoint : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDataFlow( 
-            /* [out] */ 
-            __out  EDataFlow *pDataFlow) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMMEndpointVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMMEndpoint * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMMEndpoint * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMMEndpoint * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDataFlow )( 
-            IMMEndpoint * This,
-            /* [out] */ 
-            __out  EDataFlow *pDataFlow);
-        
-        END_INTERFACE
-    } IMMEndpointVtbl;
-
-    interface IMMEndpoint
-    {
-        CONST_VTBL struct IMMEndpointVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMMEndpoint_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMMEndpoint_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMMEndpoint_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMMEndpoint_GetDataFlow(This,pDataFlow)	\
-    ( (This)->lpVtbl -> GetDataFlow(This,pDataFlow) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMMEndpoint_INTERFACE_DEFINED__ */
-
-
-#ifndef __IMMDeviceEnumerator_INTERFACE_DEFINED__
-#define __IMMDeviceEnumerator_INTERFACE_DEFINED__
-
-/* interface IMMDeviceEnumerator */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IMMDeviceEnumerator;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("A95664D2-9614-4F35-A746-DE8DB63617E6")
-    IMMDeviceEnumerator : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE EnumAudioEndpoints( 
-            /* [in] */ 
-            __in  EDataFlow dataFlow,
-            /* [in] */ 
-            __in  DWORD dwStateMask,
-            /* [out] */ 
-            __out  IMMDeviceCollection **ppDevices) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDefaultAudioEndpoint( 
-            /* [in] */ 
-            __in  EDataFlow dataFlow,
-            /* [in] */ 
-            __in  ERole role,
-            /* [out] */ 
-            __out  IMMDevice **ppEndpoint) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetDevice( 
-            /*  */ 
-            __in  LPCWSTR pwstrId,
-            /* [out] */ 
-            __out  IMMDevice **ppDevice) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RegisterEndpointNotificationCallback( 
-            /* [in] */ 
-            __in  IMMNotificationClient *pClient) = 0;
-        
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE UnregisterEndpointNotificationCallback( 
-            /* [in] */ 
-            __in  IMMNotificationClient *pClient) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMMDeviceEnumeratorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMMDeviceEnumerator * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMMDeviceEnumerator * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMMDeviceEnumerator * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *EnumAudioEndpoints )( 
-            IMMDeviceEnumerator * This,
-            /* [in] */ 
-            __in  EDataFlow dataFlow,
-            /* [in] */ 
-            __in  DWORD dwStateMask,
-            /* [out] */ 
-            __out  IMMDeviceCollection **ppDevices);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDefaultAudioEndpoint )( 
-            IMMDeviceEnumerator * This,
-            /* [in] */ 
-            __in  EDataFlow dataFlow,
-            /* [in] */ 
-            __in  ERole role,
-            /* [out] */ 
-            __out  IMMDevice **ppEndpoint);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetDevice )( 
-            IMMDeviceEnumerator * This,
-            /*  */ 
-            __in  LPCWSTR pwstrId,
-            /* [out] */ 
-            __out  IMMDevice **ppDevice);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RegisterEndpointNotificationCallback )( 
-            IMMDeviceEnumerator * This,
-            /* [in] */ 
-            __in  IMMNotificationClient *pClient);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *UnregisterEndpointNotificationCallback )( 
-            IMMDeviceEnumerator * This,
-            /* [in] */ 
-            __in  IMMNotificationClient *pClient);
-        
-        END_INTERFACE
-    } IMMDeviceEnumeratorVtbl;
-
-    interface IMMDeviceEnumerator
-    {
-        CONST_VTBL struct IMMDeviceEnumeratorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMMDeviceEnumerator_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMMDeviceEnumerator_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMMDeviceEnumerator_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMMDeviceEnumerator_EnumAudioEndpoints(This,dataFlow,dwStateMask,ppDevices)	\
-    ( (This)->lpVtbl -> EnumAudioEndpoints(This,dataFlow,dwStateMask,ppDevices) ) 
-
-#define IMMDeviceEnumerator_GetDefaultAudioEndpoint(This,dataFlow,role,ppEndpoint)	\
-    ( (This)->lpVtbl -> GetDefaultAudioEndpoint(This,dataFlow,role,ppEndpoint) ) 
-
-#define IMMDeviceEnumerator_GetDevice(This,pwstrId,ppDevice)	\
-    ( (This)->lpVtbl -> GetDevice(This,pwstrId,ppDevice) ) 
-
-#define IMMDeviceEnumerator_RegisterEndpointNotificationCallback(This,pClient)	\
-    ( (This)->lpVtbl -> RegisterEndpointNotificationCallback(This,pClient) ) 
-
-#define IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(This,pClient)	\
-    ( (This)->lpVtbl -> UnregisterEndpointNotificationCallback(This,pClient) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMMDeviceEnumerator_INTERFACE_DEFINED__ */
-
-
-#ifndef __IMMDeviceActivator_INTERFACE_DEFINED__
-#define __IMMDeviceActivator_INTERFACE_DEFINED__
-
-/* interface IMMDeviceActivator */
-/* [unique][helpstring][nonextensible][uuid][local][object] */ 
-
-
-EXTERN_C const IID IID_IMMDeviceActivator;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("3B0D0EA4-D0A9-4B0E-935B-09516746FAC0")
-    IMMDeviceActivator : public IUnknown
-    {
-    public:
-        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Activate( 
-            /* [in] */ 
-            __in  REFIID iid,
-            /* [in] */ 
-            __in  IMMDevice *pDevice,
-            /* [in] */ 
-            __in_opt  PROPVARIANT *pActivationParams,
-            /* [iid_is][out] */ 
-            __out  void **ppInterface) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMMDeviceActivatorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMMDeviceActivator * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMMDeviceActivator * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMMDeviceActivator * This);
-        
-        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Activate )( 
-            IMMDeviceActivator * This,
-            /* [in] */ 
-            __in  REFIID iid,
-            /* [in] */ 
-            __in  IMMDevice *pDevice,
-            /* [in] */ 
-            __in_opt  PROPVARIANT *pActivationParams,
-            /* [iid_is][out] */ 
-            __out  void **ppInterface);
-        
-        END_INTERFACE
-    } IMMDeviceActivatorVtbl;
-
-    interface IMMDeviceActivator
-    {
-        CONST_VTBL struct IMMDeviceActivatorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMMDeviceActivator_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMMDeviceActivator_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMMDeviceActivator_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMMDeviceActivator_Activate(This,iid,pDevice,pActivationParams,ppInterface)	\
-    ( (This)->lpVtbl -> Activate(This,iid,pDevice,pActivationParams,ppInterface) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMMDeviceActivator_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_mmdeviceapi_0000_0006 */
-/* [local] */ 
-
-typedef /* [public] */ struct __MIDL___MIDL_itf_mmdeviceapi_0000_0006_0001
-    {
-    LPARAM AddPageParam;
-    IMMDevice *pEndpoint;
-    IMMDevice *pPnpInterface;
-    IMMDevice *pPnpDevnode;
-    } 	AudioExtensionParams;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_mmdeviceapi_0000_0006_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_mmdeviceapi_0000_0006_v0_0_s_ifspec;
-
-
-#ifndef __MMDeviceAPILib_LIBRARY_DEFINED__
-#define __MMDeviceAPILib_LIBRARY_DEFINED__
-
-/* library MMDeviceAPILib */
-/* [helpstring][version][uuid] */ 
-
-
-EXTERN_C const IID LIBID_MMDeviceAPILib;
-
-EXTERN_C const CLSID CLSID_MMDeviceEnumerator;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("BCDE0395-E52F-467C-8E3D-C4579291692E")
-MMDeviceEnumerator;
-#endif
-#endif /* __MMDeviceAPILib_LIBRARY_DEFINED__ */
-
-/* Additional Prototypes for ALL interfaces */
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/propidl.h b/portaudio/src/hostapi/wasapi/mingw-include/propidl.h
deleted file mode 100644
index 7efbfcdf4..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/propidl.h
+++ /dev/null
@@ -1,1275 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for propidl.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data
-    VC __declspec() decoration level:
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 500
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __propidl_h__
-#define __propidl_h__
-
-#if __GNUC__ >=3
-#pragma GCC system_header
-#endif
-
-#define interface struct
-#include "sal.h"
-#include "rpcsal.h"
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */
-
-#ifndef __IPropertyStorage_FWD_DEFINED__
-#define __IPropertyStorage_FWD_DEFINED__
-typedef interface IPropertyStorage IPropertyStorage;
-#endif 	/* __IPropertyStorage_FWD_DEFINED__ */
-
-
-#ifndef __IPropertySetStorage_FWD_DEFINED__
-#define __IPropertySetStorage_FWD_DEFINED__
-typedef interface IPropertySetStorage IPropertySetStorage;
-#endif 	/* __IPropertySetStorage_FWD_DEFINED__ */
-
-
-#ifndef __IEnumSTATPROPSTG_FWD_DEFINED__
-#define __IEnumSTATPROPSTG_FWD_DEFINED__
-typedef interface IEnumSTATPROPSTG IEnumSTATPROPSTG;
-#endif 	/* __IEnumSTATPROPSTG_FWD_DEFINED__ */
-
-
-#ifndef __IEnumSTATPROPSETSTG_FWD_DEFINED__
-#define __IEnumSTATPROPSETSTG_FWD_DEFINED__
-typedef interface IEnumSTATPROPSETSTG IEnumSTATPROPSETSTG;
-#endif 	/* __IEnumSTATPROPSETSTG_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "objidl.h"
-#include "oaidl.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif
-
-
-/* interface __MIDL_itf_propidl_0000_0000 */
-/* [local] */
-
-//+-------------------------------------------------------------------------
-//
-//  Microsoft Windows
-//  Copyright (c) Microsoft Corporation. All rights reserved.
-//
-//--------------------------------------------------------------------------
-#if ( _MSC_VER >= 800 )
-#if _MSC_VER >= 1200
-#pragma warning(push)
-#endif
-#pragma warning(disable:4201)    /* Nameless struct/union */
-#pragma warning(disable:4237)    /* obsolete member named 'bool' */
-#endif
-#if ( _MSC_VER >= 1020 )
-#pragma once
-#endif
-
-
-
-typedef struct tagVersionedStream
-    {
-    GUID guidVersion;
-    IStream *pStream;
-    } 	VERSIONEDSTREAM;
-
-typedef struct tagVersionedStream *LPVERSIONEDSTREAM;
-
-
-// Flags for IPropertySetStorage::Create
-#define	PROPSETFLAG_DEFAULT	( 0 )
-
-#define	PROPSETFLAG_NONSIMPLE	( 1 )
-
-#define	PROPSETFLAG_ANSI	( 2 )
-
-//   (This flag is only supported on StgCreatePropStg & StgOpenPropStg
-#define	PROPSETFLAG_UNBUFFERED	( 4 )
-
-//   (This flag causes a version-1 property set to be created
-#define	PROPSETFLAG_CASE_SENSITIVE	( 8 )
-
-
-// Flags for the reservied PID_BEHAVIOR property
-#define	PROPSET_BEHAVIOR_CASE_SENSITIVE	( 1 )
-
-#ifdef MIDL_PASS
-// This is the PROPVARIANT definition for marshaling.
-typedef struct tag_inner_PROPVARIANT PROPVARIANT;
-
-#else
-// This is the standard C layout of the PROPVARIANT.
-typedef struct tagPROPVARIANT PROPVARIANT;
-#endif
-typedef struct tagCAC
-    {
-    ULONG cElems;
-    CHAR *pElems;
-    } 	CAC;
-#ifdef WIN64
-typedef struct tagCAUB
-    {
-    ULONG cElems;
-    UCHAR *pElems;
-    } 	CAUB;
-
-typedef struct tagCAI
-    {
-    ULONG cElems;
-    SHORT *pElems;
-    } 	CAI;
-
-typedef struct tagCAUI
-    {
-    ULONG cElems;
-    USHORT *pElems;
-    } 	CAUI;
-
-typedef struct tagCAL
-    {
-    ULONG cElems;
-    LONG *pElems;
-    } 	CAL;
-
-typedef struct tagCAUL
-    {
-    ULONG cElems;
-    ULONG *pElems;
-    } 	CAUL;
-
-typedef struct tagCAFLT
-    {
-    ULONG cElems;
-    FLOAT *pElems;
-    } 	CAFLT;
-
-typedef struct tagCADBL
-    {
-    ULONG cElems;
-    DOUBLE *pElems;
-    } 	CADBL;
-
-typedef struct tagCACY
-    {
-    ULONG cElems;
-    CY *pElems;
-    } 	CACY;
-
-typedef struct tagCADATE
-    {
-    ULONG cElems;
-    DATE *pElems;
-    } 	CADATE;
-
-typedef struct tagCABSTR
-    {
-    ULONG cElems;
-    BSTR *pElems;
-    } 	CABSTR;
-
-typedef struct tagCABSTRBLOB
-    {
-    ULONG cElems;
-    BSTRBLOB *pElems;
-    } 	CABSTRBLOB;
-
-typedef struct tagCABOOL
-    {
-    ULONG cElems;
-    VARIANT_BOOL *pElems;
-    } 	CABOOL;
-
-typedef struct tagCASCODE
-    {
-    ULONG cElems;
-    SCODE *pElems;
-    } 	CASCODE;
-
-typedef struct tagCAPROPVARIANT
-    {
-    ULONG cElems;
-    PROPVARIANT *pElems;
-    } 	CAPROPVARIANT;
-
-typedef struct tagCAH
-    {
-    ULONG cElems;
-    LARGE_INTEGER *pElems;
-    } 	CAH;
-
-typedef struct tagCAUH
-    {
-    ULONG cElems;
-    ULARGE_INTEGER *pElems;
-    } 	CAUH;
-
-typedef struct tagCALPSTR
-    {
-    ULONG cElems;
-    LPSTR *pElems;
-    } 	CALPSTR;
-
-typedef struct tagCALPWSTR
-    {
-    ULONG cElems;
-    LPWSTR *pElems;
-    } 	CALPWSTR;
-
-typedef struct tagCAFILETIME
-    {
-    ULONG cElems;
-    FILETIME *pElems;
-    } 	CAFILETIME;
-
-typedef struct tagCACLIPDATA
-    {
-    ULONG cElems;
-    CLIPDATA *pElems;
-    } 	CACLIPDATA;
-
-typedef struct tagCACLSID
-    {
-    ULONG cElems;
-    CLSID *pElems;
-    } 	CACLSID;
-#endif
-#ifdef MIDL_PASS
-// This is the PROPVARIANT padding layout for marshaling.
-typedef BYTE PROPVAR_PAD1;
-
-typedef BYTE PROPVAR_PAD2;
-
-typedef ULONG PROPVAR_PAD3;
-
-#else
-// This is the standard C layout of the structure.
-typedef WORD PROPVAR_PAD1;
-typedef WORD PROPVAR_PAD2;
-typedef WORD PROPVAR_PAD3;
-#define tag_inner_PROPVARIANT
-#endif
-#ifdef WIN64
-#ifndef MIDL_PASS
-struct tagPROPVARIANT {
-  union {
-#endif
-struct tag_inner_PROPVARIANT
-    {
-    VARTYPE vt;
-    PROPVAR_PAD1 wReserved1;
-    PROPVAR_PAD2 wReserved2;
-    PROPVAR_PAD3 wReserved3;
-    /* [switch_type] */ union
-        {
-         /* Empty union arm */
-        CHAR cVal;
-        UCHAR bVal;
-        SHORT iVal;
-        USHORT uiVal;
-        LONG lVal;
-        ULONG ulVal;
-        INT intVal;
-        UINT uintVal;
-        LARGE_INTEGER hVal;
-        ULARGE_INTEGER uhVal;
-        FLOAT fltVal;
-        DOUBLE dblVal;
-        VARIANT_BOOL boolVal;
-        //_VARIANT_BOOL bool;
-        SCODE scode;
-        CY cyVal;
-        DATE date;
-        FILETIME filetime;
-        CLSID *puuid;
-        CLIPDATA *pclipdata;
-        BSTR bstrVal;
-        BSTRBLOB bstrblobVal;
-        BLOB blob;
-        LPSTR pszVal;
-        LPWSTR pwszVal;
-        IUnknown *punkVal;
-        IDispatch *pdispVal;
-        IStream *pStream;
-        IStorage *pStorage;
-        LPVERSIONEDSTREAM pVersionedStream;
-        LPSAFEARRAY parray;
-        CAC cac;
-        CAUB caub;
-        CAI cai;
-        CAUI caui;
-        CAL cal;
-        CAUL caul;
-        CAH cah;
-        CAUH cauh;
-        CAFLT caflt;
-        CADBL cadbl;
-        CABOOL cabool;
-        CASCODE cascode;
-        CACY cacy;
-        CADATE cadate;
-        CAFILETIME cafiletime;
-        CACLSID cauuid;
-        CACLIPDATA caclipdata;
-        CABSTR cabstr;
-        CABSTRBLOB cabstrblob;
-        CALPSTR calpstr;
-        CALPWSTR calpwstr;
-        CAPROPVARIANT capropvar;
-        CHAR *pcVal;
-        UCHAR *pbVal;
-        SHORT *piVal;
-        USHORT *puiVal;
-        LONG *plVal;
-        ULONG *pulVal;
-        INT *pintVal;
-        UINT *puintVal;
-        FLOAT *pfltVal;
-        DOUBLE *pdblVal;
-        VARIANT_BOOL *pboolVal;
-        DECIMAL *pdecVal;
-        SCODE *pscode;
-        CY *pcyVal;
-        DATE *pdate;
-        BSTR *pbstrVal;
-        IUnknown **ppunkVal;
-        IDispatch **ppdispVal;
-        LPSAFEARRAY *pparray;
-        PROPVARIANT *pvarVal;
-        } 	;
-    } ;
-#ifndef MIDL_PASS
-    DECIMAL decVal;
-  };
-};
-#endif
-#endif
-#ifdef MIDL_PASS
-// This is the LPPROPVARIANT definition for marshaling.
-typedef struct tag_inner_PROPVARIANT *LPPROPVARIANT;
-
-typedef const PROPVARIANT *REFPROPVARIANT;
-
-#else
-
-// This is the standard C layout of the PROPVARIANT.
-#ifdef WIN64
-typedef struct tagPROPVARIANT * LPPROPVARIANT;
-#endif
-
-#ifndef _REFPROPVARIANT_DEFINED
-#define _REFPROPVARIANT_DEFINED
-#ifdef __cplusplus
-#define REFPROPVARIANT const PROPVARIANT &
-#else
-#define REFPROPVARIANT const PROPVARIANT * __MIDL_CONST
-#endif
-#endif
-
-#endif // MIDL_PASS
-
-// Reserved global Property IDs
-#define	PID_DICTIONARY	( 0 )
-
-#define	PID_CODEPAGE	( 0x1 )
-
-#define	PID_FIRST_USABLE	( 0x2 )
-
-#define	PID_FIRST_NAME_DEFAULT	( 0xfff )
-
-#define	PID_LOCALE	( 0x80000000 )
-
-#define	PID_MODIFY_TIME	( 0x80000001 )
-
-#define	PID_SECURITY	( 0x80000002 )
-
-#define	PID_BEHAVIOR	( 0x80000003 )
-
-#define	PID_ILLEGAL	( 0xffffffff )
-
-// Range which is read-only to downlevel implementations
-#define	PID_MIN_READONLY	( 0x80000000 )
-
-#define	PID_MAX_READONLY	( 0xbfffffff )
-
-// Property IDs for the DiscardableInformation Property Set
-
-#define PIDDI_THUMBNAIL          0x00000002L // VT_BLOB
-
-// Property IDs for the SummaryInformation Property Set
-
-#define PIDSI_TITLE               0x00000002L  // VT_LPSTR
-#define PIDSI_SUBJECT             0x00000003L  // VT_LPSTR
-#define PIDSI_AUTHOR              0x00000004L  // VT_LPSTR
-#define PIDSI_KEYWORDS            0x00000005L  // VT_LPSTR
-#define PIDSI_COMMENTS            0x00000006L  // VT_LPSTR
-#define PIDSI_TEMPLATE            0x00000007L  // VT_LPSTR
-#define PIDSI_LASTAUTHOR          0x00000008L  // VT_LPSTR
-#define PIDSI_REVNUMBER           0x00000009L  // VT_LPSTR
-#define PIDSI_EDITTIME            0x0000000aL  // VT_FILETIME (UTC)
-#define PIDSI_LASTPRINTED         0x0000000bL  // VT_FILETIME (UTC)
-#define PIDSI_CREATE_DTM          0x0000000cL  // VT_FILETIME (UTC)
-#define PIDSI_LASTSAVE_DTM        0x0000000dL  // VT_FILETIME (UTC)
-#define PIDSI_PAGECOUNT           0x0000000eL  // VT_I4
-#define PIDSI_WORDCOUNT           0x0000000fL  // VT_I4
-#define PIDSI_CHARCOUNT           0x00000010L  // VT_I4
-#define PIDSI_THUMBNAIL           0x00000011L  // VT_CF
-#define PIDSI_APPNAME             0x00000012L  // VT_LPSTR
-#define PIDSI_DOC_SECURITY        0x00000013L  // VT_I4
-
-// Property IDs for the DocSummaryInformation Property Set
-
-#define PIDDSI_CATEGORY          0x00000002 // VT_LPSTR
-#define PIDDSI_PRESFORMAT        0x00000003 // VT_LPSTR
-#define PIDDSI_BYTECOUNT         0x00000004 // VT_I4
-#define PIDDSI_LINECOUNT         0x00000005 // VT_I4
-#define PIDDSI_PARCOUNT          0x00000006 // VT_I4
-#define PIDDSI_SLIDECOUNT        0x00000007 // VT_I4
-#define PIDDSI_NOTECOUNT         0x00000008 // VT_I4
-#define PIDDSI_HIDDENCOUNT       0x00000009 // VT_I4
-#define PIDDSI_MMCLIPCOUNT       0x0000000A // VT_I4
-#define PIDDSI_SCALE             0x0000000B // VT_BOOL
-#define PIDDSI_HEADINGPAIR       0x0000000C // VT_VARIANT | VT_VECTOR
-#define PIDDSI_DOCPARTS          0x0000000D // VT_LPSTR | VT_VECTOR
-#define PIDDSI_MANAGER           0x0000000E // VT_LPSTR
-#define PIDDSI_COMPANY           0x0000000F // VT_LPSTR
-#define PIDDSI_LINKSDIRTY        0x00000010 // VT_BOOL
-
-
-//  FMTID_MediaFileSummaryInfo - Property IDs
-
-#define PIDMSI_EDITOR                   0x00000002L  // VT_LPWSTR
-#define PIDMSI_SUPPLIER                 0x00000003L  // VT_LPWSTR
-#define PIDMSI_SOURCE                   0x00000004L  // VT_LPWSTR
-#define PIDMSI_SEQUENCE_NO              0x00000005L  // VT_LPWSTR
-#define PIDMSI_PROJECT                  0x00000006L  // VT_LPWSTR
-#define PIDMSI_STATUS                   0x00000007L  // VT_UI4
-#define PIDMSI_OWNER                    0x00000008L  // VT_LPWSTR
-#define PIDMSI_RATING                   0x00000009L  // VT_LPWSTR
-#define PIDMSI_PRODUCTION               0x0000000AL  // VT_FILETIME (UTC)
-#define PIDMSI_COPYRIGHT                0x0000000BL  // VT_LPWSTR
-
-//  PIDMSI_STATUS value definitions
-
-enum PIDMSI_STATUS_VALUE
-    {	PIDMSI_STATUS_NORMAL	= 0,
-	PIDMSI_STATUS_NEW	= ( PIDMSI_STATUS_NORMAL + 1 ) ,
-	PIDMSI_STATUS_PRELIM	= ( PIDMSI_STATUS_NEW + 1 ) ,
-	PIDMSI_STATUS_DRAFT	= ( PIDMSI_STATUS_PRELIM + 1 ) ,
-	PIDMSI_STATUS_INPROGRESS	= ( PIDMSI_STATUS_DRAFT + 1 ) ,
-	PIDMSI_STATUS_EDIT	= ( PIDMSI_STATUS_INPROGRESS + 1 ) ,
-	PIDMSI_STATUS_REVIEW	= ( PIDMSI_STATUS_EDIT + 1 ) ,
-	PIDMSI_STATUS_PROOF	= ( PIDMSI_STATUS_REVIEW + 1 ) ,
-	PIDMSI_STATUS_FINAL	= ( PIDMSI_STATUS_PROOF + 1 ) ,
-	PIDMSI_STATUS_OTHER	= 0x7fff
-    } ;
-#define	PRSPEC_INVALID	( 0xffffffff )
-
-#define	PRSPEC_LPWSTR	( 0 )
-
-#define	PRSPEC_PROPID	( 1 )
-
-#ifdef WIN64
-typedef struct tagPROPSPEC
-    {
-    ULONG ulKind;
-    /* [switch_type] */ union
-        {
-        PROPID propid;
-        LPOLESTR lpwstr;
-         /* Empty union arm */
-        } 	;
-    } 	PROPSPEC;
-
-typedef struct tagSTATPROPSTG
-    {
-    LPOLESTR lpwstrName;
-    PROPID propid;
-    VARTYPE vt;
-    } 	STATPROPSTG;
-#endif
-
-// Macros for parsing the OS Version of the Property Set Header
-#define PROPSETHDR_OSVER_KIND(dwOSVer)      HIWORD( (dwOSVer) )
-#define PROPSETHDR_OSVER_MAJOR(dwOSVer)     LOBYTE(LOWORD( (dwOSVer) ))
-#define PROPSETHDR_OSVER_MINOR(dwOSVer)     HIBYTE(LOWORD( (dwOSVer) ))
-#define PROPSETHDR_OSVERSION_UNKNOWN        0xFFFFFFFF
-#ifdef WIN64
-typedef struct tagSTATPROPSETSTG
-    {
-    FMTID fmtid;
-    CLSID clsid;
-    DWORD grfFlags;
-    FILETIME mtime;
-    FILETIME ctime;
-    FILETIME atime;
-    DWORD dwOSVersion;
-    } 	STATPROPSETSTG;
-#endif
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IPropertyStorage_INTERFACE_DEFINED__
-#define __IPropertyStorage_INTERFACE_DEFINED__
-
-/* interface IPropertyStorage */
-/* [unique][uuid][object] */
-
-
-EXTERN_C const IID IID_IPropertyStorage;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-
-    MIDL_INTERFACE("00000138-0000-0000-C000-000000000046")
-    IPropertyStorage : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE ReadMultiple(
-            /* [in] */ ULONG cpspec,
-            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[  ],
-            /* [size_is][out] */ __RPC__out_ecount_full(cpspec) PROPVARIANT rgpropvar[  ]) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE WriteMultiple(
-            /* [in] */ ULONG cpspec,
-            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[  ],
-            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPVARIANT rgpropvar[  ],
-            /* [in] */ PROPID propidNameFirst) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE DeleteMultiple(
-            /* [in] */ ULONG cpspec,
-            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[  ]) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE ReadPropertyNames(
-            /* [in] */ ULONG cpropid,
-            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[  ],
-            /* [size_is][out] */ __RPC__out_ecount_full(cpropid) LPOLESTR rglpwstrName[  ]) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE WritePropertyNames(
-            /* [in] */ ULONG cpropid,
-            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[  ],
-            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const LPOLESTR rglpwstrName[  ]) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE DeletePropertyNames(
-            /* [in] */ ULONG cpropid,
-            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[  ]) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Commit(
-            /* [in] */ DWORD grfCommitFlags) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Revert( void) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Enum(
-            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE SetTimes(
-            /* [in] */ __RPC__in const FILETIME *pctime,
-            /* [in] */ __RPC__in const FILETIME *patime,
-            /* [in] */ __RPC__in const FILETIME *pmtime) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE SetClass(
-            /* [in] */ __RPC__in REFCLSID clsid) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Stat(
-            /* [out] */ __RPC__out STATPROPSETSTG *pstatpsstg) = 0;
-
-    };
-
-#else 	/* C style interface */
-
-//    typedef struct IPropertyStorageVtbl
-//    {
-//        BEGIN_INTERFACE
-//
-//        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
-//            IPropertyStorage * This,
-//            /* [in] */ __RPC__in REFIID riid,
-//            /* [iid_is][out] */
-//            __RPC__deref_out  void **ppvObject);
-//
-//        ULONG ( STDMETHODCALLTYPE *AddRef )(
-//            IPropertyStorage * This);
-//
-//        ULONG ( STDMETHODCALLTYPE *Release )(
-//            IPropertyStorage * This);
-//
-//        HRESULT ( STDMETHODCALLTYPE *ReadMultiple )(
-//            IPropertyStorage * This,
-//            /* [in] */ ULONG cpspec,
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[  ],
-//            /* [size_is][out] */ __RPC__out_ecount_full(cpspec) PROPVARIANT rgpropvar[  ]);
-//
-//        HRESULT ( STDMETHODCALLTYPE *WriteMultiple )(
-//            IPropertyStorage * This,
-//            /* [in] */ ULONG cpspec,
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[  ],
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPVARIANT rgpropvar[  ],
-//            /* [in] */ PROPID propidNameFirst);
-//
-//        HRESULT ( STDMETHODCALLTYPE *DeleteMultiple )(
-//            IPropertyStorage * This,
-//            /* [in] */ ULONG cpspec,
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpspec) const PROPSPEC rgpspec[  ]);
-//
-//        HRESULT ( STDMETHODCALLTYPE *ReadPropertyNames )(
-//            IPropertyStorage * This,
-//            /* [in] */ ULONG cpropid,
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[  ],
-//            /* [size_is][out] */ __RPC__out_ecount_full(cpropid) LPOLESTR rglpwstrName[  ]);
-//
-//        HRESULT ( STDMETHODCALLTYPE *WritePropertyNames )(
-//            IPropertyStorage * This,
-//            /* [in] */ ULONG cpropid,
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[  ],
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const LPOLESTR rglpwstrName[  ]);
-//
-//        HRESULT ( STDMETHODCALLTYPE *DeletePropertyNames )(
-//            IPropertyStorage * This,
-//            /* [in] */ ULONG cpropid,
-//            /* [size_is][in] */ __RPC__in_ecount_full(cpropid) const PROPID rgpropid[  ]);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Commit )(
-//            IPropertyStorage * This,
-//            /* [in] */ DWORD grfCommitFlags);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Revert )(
-//            IPropertyStorage * This);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Enum )(
-//            IPropertyStorage * This,
-//            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum);
-//
-//        HRESULT ( STDMETHODCALLTYPE *SetTimes )(
-//            IPropertyStorage * This,
-//            /* [in] */ __RPC__in const FILETIME *pctime,
-//            /* [in] */ __RPC__in const FILETIME *patime,
-//            /* [in] */ __RPC__in const FILETIME *pmtime);
-//
-//        HRESULT ( STDMETHODCALLTYPE *SetClass )(
-//            IPropertyStorage * This,
-//            /* [in] */ __RPC__in REFCLSID clsid);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Stat )(
-//            IPropertyStorage * This,
-//            /* [out] */ __RPC__out STATPROPSETSTG *pstatpsstg);
-//
-//        END_INTERFACE
-//    } IPropertyStorageVtbl;
-//
-//    interface IPropertyStorage
-//    {
-//        CONST_VTBL struct IPropertyStorageVtbl *lpVtbl;
-//    };
-
-
-
-#ifdef COBJMACROS
-
-
-#define IPropertyStorage_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
-
-#define IPropertyStorage_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) )
-
-#define IPropertyStorage_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) )
-
-
-#define IPropertyStorage_ReadMultiple(This,cpspec,rgpspec,rgpropvar)	\
-    ( (This)->lpVtbl -> ReadMultiple(This,cpspec,rgpspec,rgpropvar) )
-
-#define IPropertyStorage_WriteMultiple(This,cpspec,rgpspec,rgpropvar,propidNameFirst)	\
-    ( (This)->lpVtbl -> WriteMultiple(This,cpspec,rgpspec,rgpropvar,propidNameFirst) )
-
-#define IPropertyStorage_DeleteMultiple(This,cpspec,rgpspec)	\
-    ( (This)->lpVtbl -> DeleteMultiple(This,cpspec,rgpspec) )
-
-#define IPropertyStorage_ReadPropertyNames(This,cpropid,rgpropid,rglpwstrName)	\
-    ( (This)->lpVtbl -> ReadPropertyNames(This,cpropid,rgpropid,rglpwstrName) )
-
-#define IPropertyStorage_WritePropertyNames(This,cpropid,rgpropid,rglpwstrName)	\
-    ( (This)->lpVtbl -> WritePropertyNames(This,cpropid,rgpropid,rglpwstrName) )
-
-#define IPropertyStorage_DeletePropertyNames(This,cpropid,rgpropid)	\
-    ( (This)->lpVtbl -> DeletePropertyNames(This,cpropid,rgpropid) )
-
-#define IPropertyStorage_Commit(This,grfCommitFlags)	\
-    ( (This)->lpVtbl -> Commit(This,grfCommitFlags) )
-
-#define IPropertyStorage_Revert(This)	\
-    ( (This)->lpVtbl -> Revert(This) )
-
-#define IPropertyStorage_Enum(This,ppenum)	\
-    ( (This)->lpVtbl -> Enum(This,ppenum) )
-
-#define IPropertyStorage_SetTimes(This,pctime,patime,pmtime)	\
-    ( (This)->lpVtbl -> SetTimes(This,pctime,patime,pmtime) )
-
-#define IPropertyStorage_SetClass(This,clsid)	\
-    ( (This)->lpVtbl -> SetClass(This,clsid) )
-
-#define IPropertyStorage_Stat(This,pstatpsstg)	\
-    ( (This)->lpVtbl -> Stat(This,pstatpsstg) )
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyStorage_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertySetStorage_INTERFACE_DEFINED__
-#define __IPropertySetStorage_INTERFACE_DEFINED__
-
-/* interface IPropertySetStorage */
-/* [unique][uuid][object] */
-
-typedef /* [unique] */  __RPC_unique_pointer IPropertySetStorage *LPPROPERTYSETSTORAGE;
-
-
-EXTERN_C const IID IID_IPropertySetStorage;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-
-    MIDL_INTERFACE("0000013A-0000-0000-C000-000000000046")
-    IPropertySetStorage : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Create(
-            /* [in] */ __RPC__in REFFMTID rfmtid,
-            /* [unique][in] */ __RPC__in_opt const CLSID *pclsid,
-            /* [in] */ DWORD grfFlags,
-            /* [in] */ DWORD grfMode,
-            /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Open(
-            /* [in] */ __RPC__in REFFMTID rfmtid,
-            /* [in] */ DWORD grfMode,
-            /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Delete(
-            /* [in] */ __RPC__in REFFMTID rfmtid) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Enum(
-            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum) = 0;
-
-    };
-
-#else 	/* C style interface */
-
-//    typedef struct IPropertySetStorageVtbl
-//    {
-//        BEGIN_INTERFACE
-//
-//        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
-//            IPropertySetStorage * This,
-//            /* [in] */ __RPC__in REFIID riid,
-//            /* [iid_is][out] */
-//            __RPC__deref_out  void **ppvObject);
-//
-//        ULONG ( STDMETHODCALLTYPE *AddRef )(
-//            IPropertySetStorage * This);
-//
-//        ULONG ( STDMETHODCALLTYPE *Release )(
-//            IPropertySetStorage * This);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Create )(
-//            IPropertySetStorage * This,
-//            /* [in] */ __RPC__in REFFMTID rfmtid,
-//            /* [unique][in] */ __RPC__in_opt const CLSID *pclsid,
-//            /* [in] */ DWORD grfFlags,
-//            /* [in] */ DWORD grfMode,
-//            /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Open )(
-//            IPropertySetStorage * This,
-//            /* [in] */ __RPC__in REFFMTID rfmtid,
-//            /* [in] */ DWORD grfMode,
-//            /* [out] */ __RPC__deref_out_opt IPropertyStorage **ppprstg);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Delete )(
-//            IPropertySetStorage * This,
-//            /* [in] */ __RPC__in REFFMTID rfmtid);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Enum )(
-//            IPropertySetStorage * This,
-//            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum);
-//
-//        END_INTERFACE
-//    } IPropertySetStorageVtbl;
-//
-//    interface IPropertySetStorage
-//    {
-//        CONST_VTBL struct IPropertySetStorageVtbl *lpVtbl;
-//    };
-
-
-
-#ifdef COBJMACROS
-
-
-#define IPropertySetStorage_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
-
-#define IPropertySetStorage_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) )
-
-#define IPropertySetStorage_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) )
-
-
-#define IPropertySetStorage_Create(This,rfmtid,pclsid,grfFlags,grfMode,ppprstg)	\
-    ( (This)->lpVtbl -> Create(This,rfmtid,pclsid,grfFlags,grfMode,ppprstg) )
-
-#define IPropertySetStorage_Open(This,rfmtid,grfMode,ppprstg)	\
-    ( (This)->lpVtbl -> Open(This,rfmtid,grfMode,ppprstg) )
-
-#define IPropertySetStorage_Delete(This,rfmtid)	\
-    ( (This)->lpVtbl -> Delete(This,rfmtid) )
-
-#define IPropertySetStorage_Enum(This,ppenum)	\
-    ( (This)->lpVtbl -> Enum(This,ppenum) )
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertySetStorage_INTERFACE_DEFINED__ */
-
-
-#ifndef __IEnumSTATPROPSTG_INTERFACE_DEFINED__
-#define __IEnumSTATPROPSTG_INTERFACE_DEFINED__
-
-/* interface IEnumSTATPROPSTG */
-/* [unique][uuid][object] */
-
-//typedef /* [unique] */  __RPC_unique_pointer IEnumSTATPROPSTG *LPENUMSTATPROPSTG;
-
-
-EXTERN_C const IID IID_IEnumSTATPROPSTG;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-
-    MIDL_INTERFACE("00000139-0000-0000-C000-000000000046")
-    IEnumSTATPROPSTG : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE Next(
-            /* [in] */ ULONG celt,
-            /* [length_is][size_is][out] */ STATPROPSTG *rgelt,
-            /* [out] */ ULONG *pceltFetched) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Skip(
-            /* [in] */ ULONG celt) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Clone(
-            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum) = 0;
-
-    };
-
-#else 	/* C style interface */
-
-//    typedef struct IEnumSTATPROPSTGVtbl
-//    {
-//        BEGIN_INTERFACE
-//
-//        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
-//            IEnumSTATPROPSTG * This,
-//            /* [in] */ __RPC__in REFIID riid,
-//            /* [iid_is][out] */
-//            __RPC__deref_out  void **ppvObject);
-//
-//        ULONG ( STDMETHODCALLTYPE *AddRef )(
-//            IEnumSTATPROPSTG * This);
-//
-//        ULONG ( STDMETHODCALLTYPE *Release )(
-//            IEnumSTATPROPSTG * This);
-//
-//        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Next )(
-//            IEnumSTATPROPSTG * This,
-//            /* [in] */ ULONG celt,
-//            /* [length_is][size_is][out] */ STATPROPSTG *rgelt,
-//            /* [out] */ ULONG *pceltFetched);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Skip )(
-//            IEnumSTATPROPSTG * This,
-//            /* [in] */ ULONG celt);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Reset )(
-//            IEnumSTATPROPSTG * This);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Clone )(
-//            IEnumSTATPROPSTG * This,
-//            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSTG **ppenum);
-//
-//        END_INTERFACE
-//    } IEnumSTATPROPSTGVtbl;
-//
-//    interface IEnumSTATPROPSTG
-//    {
-//        CONST_VTBL struct IEnumSTATPROPSTGVtbl *lpVtbl;
-//    };
-
-
-
-#ifdef COBJMACROS
-
-
-#define IEnumSTATPROPSTG_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
-
-#define IEnumSTATPROPSTG_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) )
-
-#define IEnumSTATPROPSTG_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) )
-
-
-#define IEnumSTATPROPSTG_Next(This,celt,rgelt,pceltFetched)	\
-    ( (This)->lpVtbl -> Next(This,celt,rgelt,pceltFetched) )
-
-#define IEnumSTATPROPSTG_Skip(This,celt)	\
-    ( (This)->lpVtbl -> Skip(This,celt) )
-
-#define IEnumSTATPROPSTG_Reset(This)	\
-    ( (This)->lpVtbl -> Reset(This) )
-
-#define IEnumSTATPROPSTG_Clone(This,ppenum)	\
-    ( (This)->lpVtbl -> Clone(This,ppenum) )
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSTG_RemoteNext_Proxy(
-    IEnumSTATPROPSTG * This,
-    /* [in] */ ULONG celt,
-    /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSTG *rgelt,
-    /* [out] */ __RPC__out ULONG *pceltFetched);
-
-
-void __RPC_STUB IEnumSTATPROPSTG_RemoteNext_Stub(
-    IRpcStubBuffer *This,
-    IRpcChannelBuffer *_pRpcChannelBuffer,
-    PRPC_MESSAGE _pRpcMessage,
-    DWORD *_pdwStubPhase);
-
-
-
-#endif 	/* __IEnumSTATPROPSTG_INTERFACE_DEFINED__ */
-
-
-#ifndef __IEnumSTATPROPSETSTG_INTERFACE_DEFINED__
-#define __IEnumSTATPROPSETSTG_INTERFACE_DEFINED__
-
-/* interface IEnumSTATPROPSETSTG */
-/* [unique][uuid][object] */
-
-typedef /* [unique] */  __RPC_unique_pointer IEnumSTATPROPSETSTG *LPENUMSTATPROPSETSTG;
-
-
-EXTERN_C const IID IID_IEnumSTATPROPSETSTG;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-
-    MIDL_INTERFACE("0000013B-0000-0000-C000-000000000046")
-    IEnumSTATPROPSETSTG : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE Next(
-            /* [in] */ ULONG celt,
-            /* [length_is][size_is][out] */ STATPROPSETSTG *rgelt,
-            /* [out] */ ULONG *pceltFetched) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Skip(
-            /* [in] */ ULONG celt) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0;
-
-        virtual HRESULT STDMETHODCALLTYPE Clone(
-            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum) = 0;
-
-    };
-
-#else 	/* C style interface */
-
-//    typedef struct IEnumSTATPROPSETSTGVtbl
-//    {
-//        BEGIN_INTERFACE
-//
-//        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
-//            IEnumSTATPROPSETSTG * This,
-//            /* [in] */ __RPC__in REFIID riid,
-//            /* [iid_is][out] */
-//            __RPC__deref_out  void **ppvObject);
-//
-//        ULONG ( STDMETHODCALLTYPE *AddRef )(
-//            IEnumSTATPROPSETSTG * This);
-//
-//        ULONG ( STDMETHODCALLTYPE *Release )(
-//            IEnumSTATPROPSETSTG * This);
-//
-//        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Next )(
-//            IEnumSTATPROPSETSTG * This,
-//            /* [in] */ ULONG celt,
-//            /* [length_is][size_is][out] */ STATPROPSETSTG *rgelt,
-//            /* [out] */ ULONG *pceltFetched);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Skip )(
-//            IEnumSTATPROPSETSTG * This,
-//            /* [in] */ ULONG celt);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Reset )(
-//            IEnumSTATPROPSETSTG * This);
-//
-//        HRESULT ( STDMETHODCALLTYPE *Clone )(
-//            IEnumSTATPROPSETSTG * This,
-//            /* [out] */ __RPC__deref_out_opt IEnumSTATPROPSETSTG **ppenum);
-//
-//        END_INTERFACE
-//    } IEnumSTATPROPSETSTGVtbl;
-//
-//    interface IEnumSTATPROPSETSTG
-//    {
-//        CONST_VTBL struct IEnumSTATPROPSETSTGVtbl *lpVtbl;
-//    };
-
-
-
-#ifdef COBJMACROS
-
-
-#define IEnumSTATPROPSETSTG_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
-
-#define IEnumSTATPROPSETSTG_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) )
-
-#define IEnumSTATPROPSETSTG_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) )
-
-
-#define IEnumSTATPROPSETSTG_Next(This,celt,rgelt,pceltFetched)	\
-    ( (This)->lpVtbl -> Next(This,celt,rgelt,pceltFetched) )
-
-#define IEnumSTATPROPSETSTG_Skip(This,celt)	\
-    ( (This)->lpVtbl -> Skip(This,celt) )
-
-#define IEnumSTATPROPSETSTG_Reset(This)	\
-    ( (This)->lpVtbl -> Reset(This) )
-
-#define IEnumSTATPROPSETSTG_Clone(This,ppenum)	\
-    ( (This)->lpVtbl -> Clone(This,ppenum) )
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSETSTG_RemoteNext_Proxy(
-    IEnumSTATPROPSETSTG * This,
-    /* [in] */ ULONG celt,
-    /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSETSTG *rgelt,
-    /* [out] */ __RPC__out ULONG *pceltFetched);
-
-
-void __RPC_STUB IEnumSTATPROPSETSTG_RemoteNext_Stub(
-    IRpcStubBuffer *This,
-    IRpcChannelBuffer *_pRpcChannelBuffer,
-    PRPC_MESSAGE _pRpcMessage,
-    DWORD *_pdwStubPhase);
-
-
-
-#endif 	/* __IEnumSTATPROPSETSTG_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propidl_0000_0004 */
-/* [local] */
-
-typedef /* [unique] */  __RPC_unique_pointer IPropertyStorage *LPPROPERTYSTORAGE;
-
-WINOLEAPI PropVariantCopy ( PROPVARIANT * pvarDest, const PROPVARIANT * pvarSrc );
-WINOLEAPI PropVariantClear ( PROPVARIANT * pvar );
-WINOLEAPI FreePropVariantArray ( ULONG cVariants, PROPVARIANT * rgvars );
-
-#define _PROPVARIANTINIT_DEFINED_
-#   ifdef __cplusplus
-inline void PropVariantInit ( PROPVARIANT * pvar )
-{
-    memset ( pvar, 0, sizeof(PROPVARIANT) );
-}
-#   else
-#   define PropVariantInit(pvar) memset ( (pvar), 0, sizeof(PROPVARIANT) )
-#   endif
-
-
-#ifndef _STGCREATEPROPSTG_DEFINED_
-WINOLEAPI StgCreatePropStg( IUnknown* pUnk, REFFMTID fmtid, const CLSID *pclsid, DWORD grfFlags, DWORD dwReserved, IPropertyStorage **ppPropStg );
-WINOLEAPI StgOpenPropStg( IUnknown* pUnk, REFFMTID fmtid, DWORD grfFlags, DWORD dwReserved, IPropertyStorage **ppPropStg );
-WINOLEAPI StgCreatePropSetStg( IStorage *pStorage, DWORD dwReserved, IPropertySetStorage **ppPropSetStg);
-
-#define CCH_MAX_PROPSTG_NAME    31
-__checkReturn WINOLEAPI FmtIdToPropStgName( const FMTID *pfmtid, __out_ecount(CCH_MAX_PROPSTG_NAME+1) LPOLESTR oszName );
-WINOLEAPI PropStgNameToFmtId( __in __nullterminated const LPOLESTR oszName, FMTID *pfmtid );
-#endif
-#ifndef _SERIALIZEDPROPERTYVALUE_DEFINED_
-#define _SERIALIZEDPROPERTYVALUE_DEFINED_
-typedef struct tagSERIALIZEDPROPERTYVALUE		// prop
-{
-    DWORD	dwType;
-    BYTE	rgb[1];
-} SERIALIZEDPROPERTYVALUE;
-#endif
-
-EXTERN_C SERIALIZEDPROPERTYVALUE* __stdcall
-StgConvertVariantToProperty(
-            __in const PROPVARIANT* pvar,
-            USHORT CodePage,
-            __out_bcount_opt(*pcb) SERIALIZEDPROPERTYVALUE* pprop,
-            __inout ULONG* pcb,
-            PROPID pid,
-            __reserved BOOLEAN fReserved,
-            __out_opt ULONG* pcIndirect);
-
-#ifdef __cplusplus
-class PMemoryAllocator;
-
-EXTERN_C BOOLEAN __stdcall
-StgConvertPropertyToVariant(
-            __in const SERIALIZEDPROPERTYVALUE* pprop,
-            USHORT CodePage,
-            __out PROPVARIANT* pvar,
-            __in PMemoryAllocator* pma);
-#endif
-#if _MSC_VER >= 1200
-#pragma warning(pop)
-#else
-#pragma warning(default:4201)    /* Nameless struct/union */
-#pragma warning(default:4237)    /* keywords bool, true, false, etc.. */
-#endif
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0004_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propidl_0000_0004_v0_0_s_ifspec;
-
-/* Additional Prototypes for ALL interfaces */
-
-unsigned long             __RPC_USER  BSTR_UserSize(     unsigned long *, unsigned long            , BSTR * );
-unsigned char * __RPC_USER  BSTR_UserMarshal(  unsigned long *, unsigned char *, BSTR * );
-unsigned char * __RPC_USER  BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * );
-void                      __RPC_USER  BSTR_UserFree(     unsigned long *, BSTR * );
-
-unsigned long             __RPC_USER  LPSAFEARRAY_UserSize(     unsigned long *, unsigned long            , LPSAFEARRAY * );
-unsigned char * __RPC_USER  LPSAFEARRAY_UserMarshal(  unsigned long *, unsigned char *, LPSAFEARRAY * );
-unsigned char * __RPC_USER  LPSAFEARRAY_UserUnmarshal(unsigned long *, unsigned char *, LPSAFEARRAY * );
-void                      __RPC_USER  LPSAFEARRAY_UserFree(     unsigned long *, LPSAFEARRAY * );
-
-unsigned long             __RPC_USER  BSTR_UserSize64(     unsigned long *, unsigned long            , BSTR * );
-unsigned char * __RPC_USER  BSTR_UserMarshal64(  unsigned long *, unsigned char *, BSTR * );
-unsigned char * __RPC_USER  BSTR_UserUnmarshal64(unsigned long *, unsigned char *, BSTR * );
-void                      __RPC_USER  BSTR_UserFree64(     unsigned long *, BSTR * );
-
-unsigned long             __RPC_USER  LPSAFEARRAY_UserSize64(     unsigned long *, unsigned long            , LPSAFEARRAY * );
-unsigned char * __RPC_USER  LPSAFEARRAY_UserMarshal64(  unsigned long *, unsigned char *, LPSAFEARRAY * );
-unsigned char * __RPC_USER  LPSAFEARRAY_UserUnmarshal64(unsigned long *, unsigned char *, LPSAFEARRAY * );
-void                      __RPC_USER  LPSAFEARRAY_UserFree64(     unsigned long *, LPSAFEARRAY * );
-
-/* [local] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSTG_Next_Proxy(
-    IEnumSTATPROPSTG * This,
-    /* [in] */ ULONG celt,
-    /* [length_is][size_is][out] */ STATPROPSTG *rgelt,
-    /* [out] */ ULONG *pceltFetched);
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSTG_Next_Stub(
-    IEnumSTATPROPSTG * This,
-    /* [in] */ ULONG celt,
-    /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSTG *rgelt,
-    /* [out] */ __RPC__out ULONG *pceltFetched);
-
-/* [local] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSETSTG_Next_Proxy(
-    IEnumSTATPROPSETSTG * This,
-    /* [in] */ ULONG celt,
-    /* [length_is][size_is][out] */ STATPROPSETSTG *rgelt,
-    /* [out] */ ULONG *pceltFetched);
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IEnumSTATPROPSETSTG_Next_Stub(
-    IEnumSTATPROPSETSTG * This,
-    /* [in] */ ULONG celt,
-    /* [length_is][size_is][out] */ __RPC__out_ecount_part(celt, *pceltFetched) STATPROPSETSTG *rgelt,
-    /* [out] */ __RPC__out ULONG *pceltFetched);
-
-
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/propkey.h b/portaudio/src/hostapi/wasapi/mingw-include/propkey.h
deleted file mode 100644
index ea94fcf9b..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/propkey.h
+++ /dev/null
@@ -1,4274 +0,0 @@
-//===========================================================================
-//
-// Copyright (c) Microsoft Corporation. All rights reserved.
-//
-//===========================================================================
-
-
-#ifndef _INC_PROPKEY
-#define _INC_PROPKEY
-
-#ifndef DEFINE_API_PKEY
-#define DEFINE_API_PKEY(name, managed_name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8, pid) \
-        DEFINE_PROPERTYKEY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8, pid)
-#endif
-
-#include <propkeydef.h>
-
-#ifndef _WIN32_IE
-#define _WIN32_IE 0x0501
-#else
-#if (_WIN32_IE < 0x0400) && defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0500)
-#error _WIN32_IE setting conflicts with _WIN32_WINNT setting
-#endif
-#endif
-
- 
-//-----------------------------------------------------------------------------
-// Audio properties
-
-//  Name:     System.Audio.ChannelCount -- PKEY_Audio_ChannelCount
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 7 (PIDASI_CHANNEL_COUNT)
-//
-//  Indicates the channel count for the audio file.  Values: 1 (mono), 2 (stereo).
-DEFINE_PROPERTYKEY(PKEY_Audio_ChannelCount, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 7);
-
-// Possible discrete values for PKEY_Audio_ChannelCount are:
-#define AUDIO_CHANNELCOUNT_MONO             1ul
-#define AUDIO_CHANNELCOUNT_STEREO           2ul
-
-//  Name:     System.Audio.Compression -- PKEY_Audio_Compression
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 10 (PIDASI_COMPRESSION)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Audio_Compression, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 10);
-
-//  Name:     System.Audio.EncodingBitrate -- PKEY_Audio_EncodingBitrate
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 4 (PIDASI_AVG_DATA_RATE)
-//
-//  Indicates the average data rate in Hz for the audio file in "bits per second".
-DEFINE_PROPERTYKEY(PKEY_Audio_EncodingBitrate, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 4);
-
-//  Name:     System.Audio.Format -- PKEY_Audio_Format
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)  Legacy code may treat this as VT_BSTR.
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 2 (PIDASI_FORMAT)
-//
-//  Indicates the format of the audio file.
-DEFINE_PROPERTYKEY(PKEY_Audio_Format, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 2);
-
-//  Name:     System.Audio.IsVariableBitRate -- PKEY_Audio_IsVariableBitRate
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: E6822FEE-8C17-4D62-823C-8E9CFCBD1D5C, 100
-DEFINE_PROPERTYKEY(PKEY_Audio_IsVariableBitRate, 0xE6822FEE, 0x8C17, 0x4D62, 0x82, 0x3C, 0x8E, 0x9C, 0xFC, 0xBD, 0x1D, 0x5C, 100);
-
-//  Name:     System.Audio.PeakValue -- PKEY_Audio_PeakValue
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 2579E5D0-1116-4084-BD9A-9B4F7CB4DF5E, 100
-DEFINE_PROPERTYKEY(PKEY_Audio_PeakValue, 0x2579E5D0, 0x1116, 0x4084, 0xBD, 0x9A, 0x9B, 0x4F, 0x7C, 0xB4, 0xDF, 0x5E, 100);
-
-//  Name:     System.Audio.SampleRate -- PKEY_Audio_SampleRate
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 5 (PIDASI_SAMPLE_RATE)
-//
-//  Indicates the audio sample rate for the audio file in "samples per second".
-DEFINE_PROPERTYKEY(PKEY_Audio_SampleRate, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 5);
-
-//  Name:     System.Audio.SampleSize -- PKEY_Audio_SampleSize
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 6 (PIDASI_SAMPLE_SIZE)
-//
-//  Indicates the audio sample size for the audio file in "bits per sample".
-DEFINE_PROPERTYKEY(PKEY_Audio_SampleSize, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 6);
-
-//  Name:     System.Audio.StreamName -- PKEY_Audio_StreamName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 9 (PIDASI_STREAM_NAME)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Audio_StreamName, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 9);
-
-//  Name:     System.Audio.StreamNumber -- PKEY_Audio_StreamNumber
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 8 (PIDASI_STREAM_NUMBER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Audio_StreamNumber, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 8);
-
- 
- 
-//-----------------------------------------------------------------------------
-// Calendar properties
-
-//  Name:     System.Calendar.Duration -- PKEY_Calendar_Duration
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 293CA35A-09AA-4DD2-B180-1FE245728A52, 100
-//
-//  The duration as specified in a string.
-DEFINE_PROPERTYKEY(PKEY_Calendar_Duration, 0x293CA35A, 0x09AA, 0x4DD2, 0xB1, 0x80, 0x1F, 0xE2, 0x45, 0x72, 0x8A, 0x52, 100);
-
-//  Name:     System.Calendar.IsOnline -- PKEY_Calendar_IsOnline
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: BFEE9149-E3E2-49A7-A862-C05988145CEC, 100
-//
-//  Identifies if the event is an online event.
-DEFINE_PROPERTYKEY(PKEY_Calendar_IsOnline, 0xBFEE9149, 0xE3E2, 0x49A7, 0xA8, 0x62, 0xC0, 0x59, 0x88, 0x14, 0x5C, 0xEC, 100);
-
-//  Name:     System.Calendar.IsRecurring -- PKEY_Calendar_IsRecurring
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 315B9C8D-80A9-4EF9-AE16-8E746DA51D70, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_IsRecurring, 0x315B9C8D, 0x80A9, 0x4EF9, 0xAE, 0x16, 0x8E, 0x74, 0x6D, 0xA5, 0x1D, 0x70, 100);
-
-//  Name:     System.Calendar.Location -- PKEY_Calendar_Location
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F6272D18-CECC-40B1-B26A-3911717AA7BD, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_Location, 0xF6272D18, 0xCECC, 0x40B1, 0xB2, 0x6A, 0x39, 0x11, 0x71, 0x7A, 0xA7, 0xBD, 100);
-
-//  Name:     System.Calendar.OptionalAttendeeAddresses -- PKEY_Calendar_OptionalAttendeeAddresses
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D55BAE5A-3892-417A-A649-C6AC5AAAEAB3, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_OptionalAttendeeAddresses, 0xD55BAE5A, 0x3892, 0x417A, 0xA6, 0x49, 0xC6, 0xAC, 0x5A, 0xAA, 0xEA, 0xB3, 100);
-
-//  Name:     System.Calendar.OptionalAttendeeNames -- PKEY_Calendar_OptionalAttendeeNames
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 09429607-582D-437F-84C3-DE93A2B24C3C, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_OptionalAttendeeNames, 0x09429607, 0x582D, 0x437F, 0x84, 0xC3, 0xDE, 0x93, 0xA2, 0xB2, 0x4C, 0x3C, 100);
-
-//  Name:     System.Calendar.OrganizerAddress -- PKEY_Calendar_OrganizerAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 744C8242-4DF5-456C-AB9E-014EFB9021E3, 100
-//
-//  Address of the organizer organizing the event.
-DEFINE_PROPERTYKEY(PKEY_Calendar_OrganizerAddress, 0x744C8242, 0x4DF5, 0x456C, 0xAB, 0x9E, 0x01, 0x4E, 0xFB, 0x90, 0x21, 0xE3, 100);
-
-//  Name:     System.Calendar.OrganizerName -- PKEY_Calendar_OrganizerName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: AAA660F9-9865-458E-B484-01BC7FE3973E, 100
-//
-//  Name of the organizer organizing the event.
-DEFINE_PROPERTYKEY(PKEY_Calendar_OrganizerName, 0xAAA660F9, 0x9865, 0x458E, 0xB4, 0x84, 0x01, 0xBC, 0x7F, 0xE3, 0x97, 0x3E, 100);
-
-//  Name:     System.Calendar.ReminderTime -- PKEY_Calendar_ReminderTime
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 72FC5BA4-24F9-4011-9F3F-ADD27AFAD818, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_ReminderTime, 0x72FC5BA4, 0x24F9, 0x4011, 0x9F, 0x3F, 0xAD, 0xD2, 0x7A, 0xFA, 0xD8, 0x18, 100);
-
-//  Name:     System.Calendar.RequiredAttendeeAddresses -- PKEY_Calendar_RequiredAttendeeAddresses
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 0BA7D6C3-568D-4159-AB91-781A91FB71E5, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_RequiredAttendeeAddresses, 0x0BA7D6C3, 0x568D, 0x4159, 0xAB, 0x91, 0x78, 0x1A, 0x91, 0xFB, 0x71, 0xE5, 100);
-
-//  Name:     System.Calendar.RequiredAttendeeNames -- PKEY_Calendar_RequiredAttendeeNames
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: B33AF30B-F552-4584-936C-CB93E5CDA29F, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_RequiredAttendeeNames, 0xB33AF30B, 0xF552, 0x4584, 0x93, 0x6C, 0xCB, 0x93, 0xE5, 0xCD, 0xA2, 0x9F, 100);
-
-//  Name:     System.Calendar.Resources -- PKEY_Calendar_Resources
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 00F58A38-C54B-4C40-8696-97235980EAE1, 100
-DEFINE_PROPERTYKEY(PKEY_Calendar_Resources, 0x00F58A38, 0xC54B, 0x4C40, 0x86, 0x96, 0x97, 0x23, 0x59, 0x80, 0xEA, 0xE1, 100);
-
-//  Name:     System.Calendar.ShowTimeAs -- PKEY_Calendar_ShowTimeAs
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: 5BF396D4-5EB2-466F-BDE9-2FB3F2361D6E, 100
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Calendar_ShowTimeAs, 0x5BF396D4, 0x5EB2, 0x466F, 0xBD, 0xE9, 0x2F, 0xB3, 0xF2, 0x36, 0x1D, 0x6E, 100);
-
-// Possible discrete values for PKEY_Calendar_ShowTimeAs are:
-#define CALENDAR_SHOWTIMEAS_FREE            0u
-#define CALENDAR_SHOWTIMEAS_TENTATIVE       1u
-#define CALENDAR_SHOWTIMEAS_BUSY            2u
-#define CALENDAR_SHOWTIMEAS_OOF             3u
-
-//  Name:     System.Calendar.ShowTimeAsText -- PKEY_Calendar_ShowTimeAsText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 53DA57CF-62C0-45C4-81DE-7610BCEFD7F5, 100
-//  
-//  This is the user-friendly form of System.Calendar.ShowTimeAs.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Calendar_ShowTimeAsText, 0x53DA57CF, 0x62C0, 0x45C4, 0x81, 0xDE, 0x76, 0x10, 0xBC, 0xEF, 0xD7, 0xF5, 100);
- 
-//-----------------------------------------------------------------------------
-// Communication properties
-
-
-
-//  Name:     System.Communication.AccountName -- PKEY_Communication_AccountName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 9
-//
-//  Account Name
-DEFINE_PROPERTYKEY(PKEY_Communication_AccountName, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 9);
-
-//  Name:     System.Communication.Suffix -- PKEY_Communication_Suffix
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 807B653A-9E91-43EF-8F97-11CE04EE20C5, 100
-DEFINE_PROPERTYKEY(PKEY_Communication_Suffix, 0x807B653A, 0x9E91, 0x43EF, 0x8F, 0x97, 0x11, 0xCE, 0x04, 0xEE, 0x20, 0xC5, 100);
-
-//  Name:     System.Communication.TaskStatus -- PKEY_Communication_TaskStatus
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: BE1A72C6-9A1D-46B7-AFE7-AFAF8CEF4999, 100
-DEFINE_PROPERTYKEY(PKEY_Communication_TaskStatus, 0xBE1A72C6, 0x9A1D, 0x46B7, 0xAF, 0xE7, 0xAF, 0xAF, 0x8C, 0xEF, 0x49, 0x99, 100);
-
-// Possible discrete values for PKEY_Communication_TaskStatus are:
-#define TASKSTATUS_NOTSTARTED               0u
-#define TASKSTATUS_INPROGRESS               1u
-#define TASKSTATUS_COMPLETE                 2u
-#define TASKSTATUS_WAITING                  3u
-#define TASKSTATUS_DEFERRED                 4u
-
-//  Name:     System.Communication.TaskStatusText -- PKEY_Communication_TaskStatusText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A6744477-C237-475B-A075-54F34498292A, 100
-//  
-//  This is the user-friendly form of System.Communication.TaskStatus.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Communication_TaskStatusText, 0xA6744477, 0xC237, 0x475B, 0xA0, 0x75, 0x54, 0xF3, 0x44, 0x98, 0x29, 0x2A, 100);
- 
-//-----------------------------------------------------------------------------
-// Computer properties
-
-
-
-//  Name:     System.Computer.DecoratedFreeSpace -- PKEY_Computer_DecoratedFreeSpace
-//  Type:     Multivalue UInt64 -- VT_VECTOR | VT_UI8  (For variants: VT_ARRAY | VT_UI8)
-//  FormatID: (FMTID_Volume) 9B174B35-40FF-11D2-A27E-00C04FC30871, 7  (Filesystem Volume Properties)
-//
-//  Free space and total space: "%s free of %s"
-DEFINE_PROPERTYKEY(PKEY_Computer_DecoratedFreeSpace, 0x9B174B35, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 7);
- 
-//-----------------------------------------------------------------------------
-// Contact properties
-
-
-
-//  Name:     System.Contact.Anniversary -- PKEY_Contact_Anniversary
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 9AD5BADB-CEA7-4470-A03D-B84E51B9949E, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Anniversary, 0x9AD5BADB, 0xCEA7, 0x4470, 0xA0, 0x3D, 0xB8, 0x4E, 0x51, 0xB9, 0x94, 0x9E, 100);
-
-//  Name:     System.Contact.AssistantName -- PKEY_Contact_AssistantName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CD102C9C-5540-4A88-A6F6-64E4981C8CD1, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_AssistantName, 0xCD102C9C, 0x5540, 0x4A88, 0xA6, 0xF6, 0x64, 0xE4, 0x98, 0x1C, 0x8C, 0xD1, 100);
-
-//  Name:     System.Contact.AssistantTelephone -- PKEY_Contact_AssistantTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 9A93244D-A7AD-4FF8-9B99-45EE4CC09AF6, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_AssistantTelephone, 0x9A93244D, 0xA7AD, 0x4FF8, 0x9B, 0x99, 0x45, 0xEE, 0x4C, 0xC0, 0x9A, 0xF6, 100);
-
-//  Name:     System.Contact.Birthday -- PKEY_Contact_Birthday
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 47
-DEFINE_PROPERTYKEY(PKEY_Contact_Birthday, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 47);
-
-//  Name:     System.Contact.BusinessAddress -- PKEY_Contact_BusinessAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 730FB6DD-CF7C-426B-A03F-BD166CC9EE24, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddress, 0x730FB6DD, 0xCF7C, 0x426B, 0xA0, 0x3F, 0xBD, 0x16, 0x6C, 0xC9, 0xEE, 0x24, 100);
-
-//  Name:     System.Contact.BusinessAddressCity -- PKEY_Contact_BusinessAddressCity
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 402B5934-EC5A-48C3-93E6-85E86A2D934E, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddressCity, 0x402B5934, 0xEC5A, 0x48C3, 0x93, 0xE6, 0x85, 0xE8, 0x6A, 0x2D, 0x93, 0x4E, 100);
-
-//  Name:     System.Contact.BusinessAddressCountry -- PKEY_Contact_BusinessAddressCountry
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: B0B87314-FCF6-4FEB-8DFF-A50DA6AF561C, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddressCountry, 0xB0B87314, 0xFCF6, 0x4FEB, 0x8D, 0xFF, 0xA5, 0x0D, 0xA6, 0xAF, 0x56, 0x1C, 100);
-
-//  Name:     System.Contact.BusinessAddressPostalCode -- PKEY_Contact_BusinessAddressPostalCode
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E1D4A09E-D758-4CD1-B6EC-34A8B5A73F80, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddressPostalCode, 0xE1D4A09E, 0xD758, 0x4CD1, 0xB6, 0xEC, 0x34, 0xA8, 0xB5, 0xA7, 0x3F, 0x80, 100);
-
-//  Name:     System.Contact.BusinessAddressPostOfficeBox -- PKEY_Contact_BusinessAddressPostOfficeBox
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: BC4E71CE-17F9-48D5-BEE9-021DF0EA5409, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddressPostOfficeBox, 0xBC4E71CE, 0x17F9, 0x48D5, 0xBE, 0xE9, 0x02, 0x1D, 0xF0, 0xEA, 0x54, 0x09, 100);
-
-//  Name:     System.Contact.BusinessAddressState -- PKEY_Contact_BusinessAddressState
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 446F787F-10C4-41CB-A6C4-4D0343551597, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddressState, 0x446F787F, 0x10C4, 0x41CB, 0xA6, 0xC4, 0x4D, 0x03, 0x43, 0x55, 0x15, 0x97, 100);
-
-//  Name:     System.Contact.BusinessAddressStreet -- PKEY_Contact_BusinessAddressStreet
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DDD1460F-C0BF-4553-8CE4-10433C908FB0, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessAddressStreet, 0xDDD1460F, 0xC0BF, 0x4553, 0x8C, 0xE4, 0x10, 0x43, 0x3C, 0x90, 0x8F, 0xB0, 100);
-
-//  Name:     System.Contact.BusinessFaxNumber -- PKEY_Contact_BusinessFaxNumber
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 91EFF6F3-2E27-42CA-933E-7C999FBE310B, 100
-//
-//  Business fax number of the contact.
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessFaxNumber, 0x91EFF6F3, 0x2E27, 0x42CA, 0x93, 0x3E, 0x7C, 0x99, 0x9F, 0xBE, 0x31, 0x0B, 100);
-
-//  Name:     System.Contact.BusinessHomePage -- PKEY_Contact_BusinessHomePage
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 56310920-2491-4919-99CE-EADB06FAFDB2, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessHomePage, 0x56310920, 0x2491, 0x4919, 0x99, 0xCE, 0xEA, 0xDB, 0x06, 0xFA, 0xFD, 0xB2, 100);
-
-//  Name:     System.Contact.BusinessTelephone -- PKEY_Contact_BusinessTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6A15E5A0-0A1E-4CD7-BB8C-D2F1B0C929BC, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_BusinessTelephone, 0x6A15E5A0, 0x0A1E, 0x4CD7, 0xBB, 0x8C, 0xD2, 0xF1, 0xB0, 0xC9, 0x29, 0xBC, 100);
-
-//  Name:     System.Contact.CallbackTelephone -- PKEY_Contact_CallbackTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: BF53D1C3-49E0-4F7F-8567-5A821D8AC542, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_CallbackTelephone, 0xBF53D1C3, 0x49E0, 0x4F7F, 0x85, 0x67, 0x5A, 0x82, 0x1D, 0x8A, 0xC5, 0x42, 100);
-
-//  Name:     System.Contact.CarTelephone -- PKEY_Contact_CarTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 8FDC6DEA-B929-412B-BA90-397A257465FE, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_CarTelephone, 0x8FDC6DEA, 0xB929, 0x412B, 0xBA, 0x90, 0x39, 0x7A, 0x25, 0x74, 0x65, 0xFE, 100);
-
-//  Name:     System.Contact.Children -- PKEY_Contact_Children
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D4729704-8EF1-43EF-9024-2BD381187FD5, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Children, 0xD4729704, 0x8EF1, 0x43EF, 0x90, 0x24, 0x2B, 0xD3, 0x81, 0x18, 0x7F, 0xD5, 100);
-
-//  Name:     System.Contact.CompanyMainTelephone -- PKEY_Contact_CompanyMainTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 8589E481-6040-473D-B171-7FA89C2708ED, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_CompanyMainTelephone, 0x8589E481, 0x6040, 0x473D, 0xB1, 0x71, 0x7F, 0xA8, 0x9C, 0x27, 0x08, 0xED, 100);
-
-//  Name:     System.Contact.Department -- PKEY_Contact_Department
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: FC9F7306-FF8F-4D49-9FB6-3FFE5C0951EC, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Department, 0xFC9F7306, 0xFF8F, 0x4D49, 0x9F, 0xB6, 0x3F, 0xFE, 0x5C, 0x09, 0x51, 0xEC, 100);
-
-//  Name:     System.Contact.EmailAddress -- PKEY_Contact_EmailAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F8FA7FA3-D12B-4785-8A4E-691A94F7A3E7, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_EmailAddress, 0xF8FA7FA3, 0xD12B, 0x4785, 0x8A, 0x4E, 0x69, 0x1A, 0x94, 0xF7, 0xA3, 0xE7, 100);
-
-//  Name:     System.Contact.EmailAddress2 -- PKEY_Contact_EmailAddress2
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 38965063-EDC8-4268-8491-B7723172CF29, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_EmailAddress2, 0x38965063, 0xEDC8, 0x4268, 0x84, 0x91, 0xB7, 0x72, 0x31, 0x72, 0xCF, 0x29, 100);
-
-//  Name:     System.Contact.EmailAddress3 -- PKEY_Contact_EmailAddress3
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 644D37B4-E1B3-4BAD-B099-7E7C04966ACA, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_EmailAddress3, 0x644D37B4, 0xE1B3, 0x4BAD, 0xB0, 0x99, 0x7E, 0x7C, 0x04, 0x96, 0x6A, 0xCA, 100);
-
-//  Name:     System.Contact.EmailAddresses -- PKEY_Contact_EmailAddresses
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 84D8F337-981D-44B3-9615-C7596DBA17E3, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_EmailAddresses, 0x84D8F337, 0x981D, 0x44B3, 0x96, 0x15, 0xC7, 0x59, 0x6D, 0xBA, 0x17, 0xE3, 100);
-
-//  Name:     System.Contact.EmailName -- PKEY_Contact_EmailName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CC6F4F24-6083-4BD4-8754-674D0DE87AB8, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_EmailName, 0xCC6F4F24, 0x6083, 0x4BD4, 0x87, 0x54, 0x67, 0x4D, 0x0D, 0xE8, 0x7A, 0xB8, 100);
-
-//  Name:     System.Contact.FileAsName -- PKEY_Contact_FileAsName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F1A24AA7-9CA7-40F6-89EC-97DEF9FFE8DB, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_FileAsName, 0xF1A24AA7, 0x9CA7, 0x40F6, 0x89, 0xEC, 0x97, 0xDE, 0xF9, 0xFF, 0xE8, 0xDB, 100);
-
-//  Name:     System.Contact.FirstName -- PKEY_Contact_FirstName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 14977844-6B49-4AAD-A714-A4513BF60460, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_FirstName, 0x14977844, 0x6B49, 0x4AAD, 0xA7, 0x14, 0xA4, 0x51, 0x3B, 0xF6, 0x04, 0x60, 100);
-
-//  Name:     System.Contact.FullName -- PKEY_Contact_FullName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 635E9051-50A5-4BA2-B9DB-4ED056C77296, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_FullName, 0x635E9051, 0x50A5, 0x4BA2, 0xB9, 0xDB, 0x4E, 0xD0, 0x56, 0xC7, 0x72, 0x96, 100);
-
-//  Name:     System.Contact.Gender -- PKEY_Contact_Gender
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 3C8CEE58-D4F0-4CF9-B756-4E5D24447BCD, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Gender, 0x3C8CEE58, 0xD4F0, 0x4CF9, 0xB7, 0x56, 0x4E, 0x5D, 0x24, 0x44, 0x7B, 0xCD, 100);
-
-//  Name:     System.Contact.Hobbies -- PKEY_Contact_Hobbies
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 5DC2253F-5E11-4ADF-9CFE-910DD01E3E70, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Hobbies, 0x5DC2253F, 0x5E11, 0x4ADF, 0x9C, 0xFE, 0x91, 0x0D, 0xD0, 0x1E, 0x3E, 0x70, 100);
-
-//  Name:     System.Contact.HomeAddress -- PKEY_Contact_HomeAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 98F98354-617A-46B8-8560-5B1B64BF1F89, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddress, 0x98F98354, 0x617A, 0x46B8, 0x85, 0x60, 0x5B, 0x1B, 0x64, 0xBF, 0x1F, 0x89, 100);
-
-//  Name:     System.Contact.HomeAddressCity -- PKEY_Contact_HomeAddressCity
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 65
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddressCity, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 65);
-
-//  Name:     System.Contact.HomeAddressCountry -- PKEY_Contact_HomeAddressCountry
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 08A65AA1-F4C9-43DD-9DDF-A33D8E7EAD85, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddressCountry, 0x08A65AA1, 0xF4C9, 0x43DD, 0x9D, 0xDF, 0xA3, 0x3D, 0x8E, 0x7E, 0xAD, 0x85, 100);
-
-//  Name:     System.Contact.HomeAddressPostalCode -- PKEY_Contact_HomeAddressPostalCode
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 8AFCC170-8A46-4B53-9EEE-90BAE7151E62, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddressPostalCode, 0x8AFCC170, 0x8A46, 0x4B53, 0x9E, 0xEE, 0x90, 0xBA, 0xE7, 0x15, 0x1E, 0x62, 100);
-
-//  Name:     System.Contact.HomeAddressPostOfficeBox -- PKEY_Contact_HomeAddressPostOfficeBox
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7B9F6399-0A3F-4B12-89BD-4ADC51C918AF, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddressPostOfficeBox, 0x7B9F6399, 0x0A3F, 0x4B12, 0x89, 0xBD, 0x4A, 0xDC, 0x51, 0xC9, 0x18, 0xAF, 100);
-
-//  Name:     System.Contact.HomeAddressState -- PKEY_Contact_HomeAddressState
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C89A23D0-7D6D-4EB8-87D4-776A82D493E5, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddressState, 0xC89A23D0, 0x7D6D, 0x4EB8, 0x87, 0xD4, 0x77, 0x6A, 0x82, 0xD4, 0x93, 0xE5, 100);
-
-//  Name:     System.Contact.HomeAddressStreet -- PKEY_Contact_HomeAddressStreet
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 0ADEF160-DB3F-4308-9A21-06237B16FA2A, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeAddressStreet, 0x0ADEF160, 0xDB3F, 0x4308, 0x9A, 0x21, 0x06, 0x23, 0x7B, 0x16, 0xFA, 0x2A, 100);
-
-//  Name:     System.Contact.HomeFaxNumber -- PKEY_Contact_HomeFaxNumber
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 660E04D6-81AB-4977-A09F-82313113AB26, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeFaxNumber, 0x660E04D6, 0x81AB, 0x4977, 0xA0, 0x9F, 0x82, 0x31, 0x31, 0x13, 0xAB, 0x26, 100);
-
-//  Name:     System.Contact.HomeTelephone -- PKEY_Contact_HomeTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 20
-DEFINE_PROPERTYKEY(PKEY_Contact_HomeTelephone, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 20);
-
-//  Name:     System.Contact.IMAddress -- PKEY_Contact_IMAddress
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D68DBD8A-3374-4B81-9972-3EC30682DB3D, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_IMAddress, 0xD68DBD8A, 0x3374, 0x4B81, 0x99, 0x72, 0x3E, 0xC3, 0x06, 0x82, 0xDB, 0x3D, 100);
-
-//  Name:     System.Contact.Initials -- PKEY_Contact_Initials
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F3D8F40D-50CB-44A2-9718-40CB9119495D, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Initials, 0xF3D8F40D, 0x50CB, 0x44A2, 0x97, 0x18, 0x40, 0xCB, 0x91, 0x19, 0x49, 0x5D, 100);
-
-//  Name:     System.Contact.JA.CompanyNamePhonetic -- PKEY_Contact_JA_CompanyNamePhonetic
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 897B3694-FE9E-43E6-8066-260F590C0100, 2
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Contact_JA_CompanyNamePhonetic, 0x897B3694, 0xFE9E, 0x43E6, 0x80, 0x66, 0x26, 0x0F, 0x59, 0x0C, 0x01, 0x00, 2);
-
-//  Name:     System.Contact.JA.FirstNamePhonetic -- PKEY_Contact_JA_FirstNamePhonetic
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 897B3694-FE9E-43E6-8066-260F590C0100, 3
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Contact_JA_FirstNamePhonetic, 0x897B3694, 0xFE9E, 0x43E6, 0x80, 0x66, 0x26, 0x0F, 0x59, 0x0C, 0x01, 0x00, 3);
-
-//  Name:     System.Contact.JA.LastNamePhonetic -- PKEY_Contact_JA_LastNamePhonetic
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 897B3694-FE9E-43E6-8066-260F590C0100, 4
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Contact_JA_LastNamePhonetic, 0x897B3694, 0xFE9E, 0x43E6, 0x80, 0x66, 0x26, 0x0F, 0x59, 0x0C, 0x01, 0x00, 4);
-
-//  Name:     System.Contact.JobTitle -- PKEY_Contact_JobTitle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 6
-DEFINE_PROPERTYKEY(PKEY_Contact_JobTitle, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 6);
-
-//  Name:     System.Contact.Label -- PKEY_Contact_Label
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 97B0AD89-DF49-49CC-834E-660974FD755B, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Label, 0x97B0AD89, 0xDF49, 0x49CC, 0x83, 0x4E, 0x66, 0x09, 0x74, 0xFD, 0x75, 0x5B, 100);
-
-//  Name:     System.Contact.LastName -- PKEY_Contact_LastName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 8F367200-C270-457C-B1D4-E07C5BCD90C7, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_LastName, 0x8F367200, 0xC270, 0x457C, 0xB1, 0xD4, 0xE0, 0x7C, 0x5B, 0xCD, 0x90, 0xC7, 100);
-
-//  Name:     System.Contact.MailingAddress -- PKEY_Contact_MailingAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C0AC206A-827E-4650-95AE-77E2BB74FCC9, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_MailingAddress, 0xC0AC206A, 0x827E, 0x4650, 0x95, 0xAE, 0x77, 0xE2, 0xBB, 0x74, 0xFC, 0xC9, 100);
-
-//  Name:     System.Contact.MiddleName -- PKEY_Contact_MiddleName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 71
-DEFINE_PROPERTYKEY(PKEY_Contact_MiddleName, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 71);
-
-//  Name:     System.Contact.MobileTelephone -- PKEY_Contact_MobileTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 35
-DEFINE_PROPERTYKEY(PKEY_Contact_MobileTelephone, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 35);
-
-//  Name:     System.Contact.NickName -- PKEY_Contact_NickName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 74
-DEFINE_PROPERTYKEY(PKEY_Contact_NickName, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 74);
-
-//  Name:     System.Contact.OfficeLocation -- PKEY_Contact_OfficeLocation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 7
-DEFINE_PROPERTYKEY(PKEY_Contact_OfficeLocation, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 7);
-
-//  Name:     System.Contact.OtherAddress -- PKEY_Contact_OtherAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 508161FA-313B-43D5-83A1-C1ACCF68622C, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddress, 0x508161FA, 0x313B, 0x43D5, 0x83, 0xA1, 0xC1, 0xAC, 0xCF, 0x68, 0x62, 0x2C, 100);
-
-//  Name:     System.Contact.OtherAddressCity -- PKEY_Contact_OtherAddressCity
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6E682923-7F7B-4F0C-A337-CFCA296687BF, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddressCity, 0x6E682923, 0x7F7B, 0x4F0C, 0xA3, 0x37, 0xCF, 0xCA, 0x29, 0x66, 0x87, 0xBF, 100);
-
-//  Name:     System.Contact.OtherAddressCountry -- PKEY_Contact_OtherAddressCountry
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 8F167568-0AAE-4322-8ED9-6055B7B0E398, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddressCountry, 0x8F167568, 0x0AAE, 0x4322, 0x8E, 0xD9, 0x60, 0x55, 0xB7, 0xB0, 0xE3, 0x98, 100);
-
-//  Name:     System.Contact.OtherAddressPostalCode -- PKEY_Contact_OtherAddressPostalCode
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 95C656C1-2ABF-4148-9ED3-9EC602E3B7CD, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddressPostalCode, 0x95C656C1, 0x2ABF, 0x4148, 0x9E, 0xD3, 0x9E, 0xC6, 0x02, 0xE3, 0xB7, 0xCD, 100);
-
-//  Name:     System.Contact.OtherAddressPostOfficeBox -- PKEY_Contact_OtherAddressPostOfficeBox
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 8B26EA41-058F-43F6-AECC-4035681CE977, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddressPostOfficeBox, 0x8B26EA41, 0x058F, 0x43F6, 0xAE, 0xCC, 0x40, 0x35, 0x68, 0x1C, 0xE9, 0x77, 100);
-
-//  Name:     System.Contact.OtherAddressState -- PKEY_Contact_OtherAddressState
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 71B377D6-E570-425F-A170-809FAE73E54E, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddressState, 0x71B377D6, 0xE570, 0x425F, 0xA1, 0x70, 0x80, 0x9F, 0xAE, 0x73, 0xE5, 0x4E, 100);
-
-//  Name:     System.Contact.OtherAddressStreet -- PKEY_Contact_OtherAddressStreet
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: FF962609-B7D6-4999-862D-95180D529AEA, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_OtherAddressStreet, 0xFF962609, 0xB7D6, 0x4999, 0x86, 0x2D, 0x95, 0x18, 0x0D, 0x52, 0x9A, 0xEA, 100);
-
-//  Name:     System.Contact.PagerTelephone -- PKEY_Contact_PagerTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: D6304E01-F8F5-4F45-8B15-D024A6296789, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PagerTelephone, 0xD6304E01, 0xF8F5, 0x4F45, 0x8B, 0x15, 0xD0, 0x24, 0xA6, 0x29, 0x67, 0x89, 100);
-
-//  Name:     System.Contact.PersonalTitle -- PKEY_Contact_PersonalTitle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 69
-DEFINE_PROPERTYKEY(PKEY_Contact_PersonalTitle, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 69);
-
-//  Name:     System.Contact.PrimaryAddressCity -- PKEY_Contact_PrimaryAddressCity
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C8EA94F0-A9E3-4969-A94B-9C62A95324E0, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryAddressCity, 0xC8EA94F0, 0xA9E3, 0x4969, 0xA9, 0x4B, 0x9C, 0x62, 0xA9, 0x53, 0x24, 0xE0, 100);
-
-//  Name:     System.Contact.PrimaryAddressCountry -- PKEY_Contact_PrimaryAddressCountry
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E53D799D-0F3F-466E-B2FF-74634A3CB7A4, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryAddressCountry, 0xE53D799D, 0x0F3F, 0x466E, 0xB2, 0xFF, 0x74, 0x63, 0x4A, 0x3C, 0xB7, 0xA4, 100);
-
-//  Name:     System.Contact.PrimaryAddressPostalCode -- PKEY_Contact_PrimaryAddressPostalCode
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 18BBD425-ECFD-46EF-B612-7B4A6034EDA0, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryAddressPostalCode, 0x18BBD425, 0xECFD, 0x46EF, 0xB6, 0x12, 0x7B, 0x4A, 0x60, 0x34, 0xED, 0xA0, 100);
-
-//  Name:     System.Contact.PrimaryAddressPostOfficeBox -- PKEY_Contact_PrimaryAddressPostOfficeBox
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DE5EF3C7-46E1-484E-9999-62C5308394C1, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryAddressPostOfficeBox, 0xDE5EF3C7, 0x46E1, 0x484E, 0x99, 0x99, 0x62, 0xC5, 0x30, 0x83, 0x94, 0xC1, 100);
-
-//  Name:     System.Contact.PrimaryAddressState -- PKEY_Contact_PrimaryAddressState
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F1176DFE-7138-4640-8B4C-AE375DC70A6D, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryAddressState, 0xF1176DFE, 0x7138, 0x4640, 0x8B, 0x4C, 0xAE, 0x37, 0x5D, 0xC7, 0x0A, 0x6D, 100);
-
-//  Name:     System.Contact.PrimaryAddressStreet -- PKEY_Contact_PrimaryAddressStreet
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 63C25B20-96BE-488F-8788-C09C407AD812, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryAddressStreet, 0x63C25B20, 0x96BE, 0x488F, 0x87, 0x88, 0xC0, 0x9C, 0x40, 0x7A, 0xD8, 0x12, 100);
-
-//  Name:     System.Contact.PrimaryEmailAddress -- PKEY_Contact_PrimaryEmailAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 48
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryEmailAddress, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 48);
-
-//  Name:     System.Contact.PrimaryTelephone -- PKEY_Contact_PrimaryTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 25
-DEFINE_PROPERTYKEY(PKEY_Contact_PrimaryTelephone, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 25);
-
-//  Name:     System.Contact.Profession -- PKEY_Contact_Profession
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7268AF55-1CE4-4F6E-A41F-B6E4EF10E4A9, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_Profession, 0x7268AF55, 0x1CE4, 0x4F6E, 0xA4, 0x1F, 0xB6, 0xE4, 0xEF, 0x10, 0xE4, 0xA9, 100);
-
-//  Name:     System.Contact.SpouseName -- PKEY_Contact_SpouseName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 9D2408B6-3167-422B-82B0-F583B7A7CFE3, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_SpouseName, 0x9D2408B6, 0x3167, 0x422B, 0x82, 0xB0, 0xF5, 0x83, 0xB7, 0xA7, 0xCF, 0xE3, 100);
-
-//  Name:     System.Contact.Suffix -- PKEY_Contact_Suffix
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 176DC63C-2688-4E89-8143-A347800F25E9, 73
-DEFINE_PROPERTYKEY(PKEY_Contact_Suffix, 0x176DC63C, 0x2688, 0x4E89, 0x81, 0x43, 0xA3, 0x47, 0x80, 0x0F, 0x25, 0xE9, 73);
-
-//  Name:     System.Contact.TelexNumber -- PKEY_Contact_TelexNumber
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C554493C-C1F7-40C1-A76C-EF8C0614003E, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_TelexNumber, 0xC554493C, 0xC1F7, 0x40C1, 0xA7, 0x6C, 0xEF, 0x8C, 0x06, 0x14, 0x00, 0x3E, 100);
-
-//  Name:     System.Contact.TTYTDDTelephone -- PKEY_Contact_TTYTDDTelephone
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: AAF16BAC-2B55-45E6-9F6D-415EB94910DF, 100
-DEFINE_PROPERTYKEY(PKEY_Contact_TTYTDDTelephone, 0xAAF16BAC, 0x2B55, 0x45E6, 0x9F, 0x6D, 0x41, 0x5E, 0xB9, 0x49, 0x10, 0xDF, 100);
-
-//  Name:     System.Contact.WebPage -- PKEY_Contact_WebPage
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 18
-DEFINE_PROPERTYKEY(PKEY_Contact_WebPage, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 18);
- 
-//-----------------------------------------------------------------------------
-// Core properties
-
-
-
-//  Name:     System.AcquisitionID -- PKEY_AcquisitionID
-//  Type:     Int32 -- VT_I4
-//  FormatID: 65A98875-3C80-40AB-ABBC-EFDAF77DBEE2, 100
-//
-//  Hash to determine acquisition session.
-DEFINE_PROPERTYKEY(PKEY_AcquisitionID, 0x65A98875, 0x3C80, 0x40AB, 0xAB, 0xBC, 0xEF, 0xDA, 0xF7, 0x7D, 0xBE, 0xE2, 100);
-
-//  Name:     System.ApplicationName -- PKEY_ApplicationName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)  Legacy code may treat this as VT_LPSTR.
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 18 (PIDSI_APPNAME)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_ApplicationName, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 18);
-
-//  Name:     System.Author -- PKEY_Author
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)  Legacy code may treat this as VT_LPSTR.
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 4 (PIDSI_AUTHOR)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Author, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 4);
-
-//  Name:     System.Capacity -- PKEY_Capacity
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_Volume) 9B174B35-40FF-11D2-A27E-00C04FC30871, 3 (PID_VOLUME_CAPACITY)  (Filesystem Volume Properties)
-//
-//  The amount of total space in bytes.
-DEFINE_PROPERTYKEY(PKEY_Capacity, 0x9B174B35, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 3);
-
-//  Name:     System.Category -- PKEY_Category
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 2 (PIDDSI_CATEGORY)
-//
-//  Legacy code treats this as VT_LPSTR.
-DEFINE_PROPERTYKEY(PKEY_Category, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 2);
-
-//  Name:     System.Comment -- PKEY_Comment
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)  Legacy code may treat this as VT_LPSTR.
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 6 (PIDSI_COMMENTS)
-//
-//  Comments.
-DEFINE_PROPERTYKEY(PKEY_Comment, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 6);
-
-//  Name:     System.Company -- PKEY_Company
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 15 (PIDDSI_COMPANY)
-//
-//  The company or publisher.
-DEFINE_PROPERTYKEY(PKEY_Company, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 15);
-
-//  Name:     System.ComputerName -- PKEY_ComputerName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 5 (PID_COMPUTERNAME)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_ComputerName, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 5);
-
-//  Name:     System.ContainedItems -- PKEY_ContainedItems
-//  Type:     Multivalue Guid -- VT_VECTOR | VT_CLSID  (For variants: VT_ARRAY | VT_CLSID)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 29
-//  
-//  The list of type of items, this item contains. For example, this item contains urls, attachments etc.
-//  This is represented as a vector array of GUIDs where each GUID represents certain type.
-DEFINE_PROPERTYKEY(PKEY_ContainedItems, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 29);
-
-//  Name:     System.ContentStatus -- PKEY_ContentStatus
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 27
-DEFINE_PROPERTYKEY(PKEY_ContentStatus, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 27);
-
-//  Name:     System.ContentType -- PKEY_ContentType
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 26
-DEFINE_PROPERTYKEY(PKEY_ContentType, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 26);
-
-//  Name:     System.Copyright -- PKEY_Copyright
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 11 (PIDMSI_COPYRIGHT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Copyright, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 11);
-
-//  Name:     System.DateAccessed -- PKEY_DateAccessed
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 16 (PID_STG_ACCESSTIME)
-//
-//  The time of the last access to the item.  The Indexing Service friendly name is 'access'.
-DEFINE_PROPERTYKEY(PKEY_DateAccessed, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 16);
-
-//  Name:     System.DateAcquired -- PKEY_DateAcquired
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 2CBAA8F5-D81F-47CA-B17A-F8D822300131, 100
-//  
-//  The time the file entered the system via acquisition.  This is not the same as System.DateImported.
-//  Examples are when pictures are acquired from a camera, or when music is purchased online.
-DEFINE_PROPERTYKEY(PKEY_DateAcquired, 0x2CBAA8F5, 0xD81F, 0x47CA, 0xB1, 0x7A, 0xF8, 0xD8, 0x22, 0x30, 0x01, 0x31, 100);
-
-//  Name:     System.DateArchived -- PKEY_DateArchived
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 43F8D7B7-A444-4F87-9383-52271C9B915C, 100
-DEFINE_PROPERTYKEY(PKEY_DateArchived, 0x43F8D7B7, 0xA444, 0x4F87, 0x93, 0x83, 0x52, 0x27, 0x1C, 0x9B, 0x91, 0x5C, 100);
-
-//  Name:     System.DateCompleted -- PKEY_DateCompleted
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 72FAB781-ACDA-43E5-B155-B2434F85E678, 100
-DEFINE_PROPERTYKEY(PKEY_DateCompleted, 0x72FAB781, 0xACDA, 0x43E5, 0xB1, 0x55, 0xB2, 0x43, 0x4F, 0x85, 0xE6, 0x78, 100);
-
-//  Name:     System.DateCreated -- PKEY_DateCreated
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 15 (PID_STG_CREATETIME)
-//
-//  The date and time the item was created. The Indexing Service friendly name is 'create'.
-DEFINE_PROPERTYKEY(PKEY_DateCreated, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 15);
-
-//  Name:     System.DateImported -- PKEY_DateImported
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 18258
-//
-//  The time the file is imported into a separate database.  This is not the same as System.DateAcquired.  (Eg, 2003:05:22 13:55:04)
-DEFINE_PROPERTYKEY(PKEY_DateImported, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 18258);
-
-//  Name:     System.DateModified -- PKEY_DateModified
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 14 (PID_STG_WRITETIME)
-//
-//  The date and time of the last write to the item. The Indexing Service friendly name is 'write'.
-DEFINE_PROPERTYKEY(PKEY_DateModified, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 14);
-
-//  Name:     System.DueDate -- PKEY_DueDate
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 3F8472B5-E0AF-4DB2-8071-C53FE76AE7CE, 100
-DEFINE_PROPERTYKEY(PKEY_DueDate, 0x3F8472B5, 0xE0AF, 0x4DB2, 0x80, 0x71, 0xC5, 0x3F, 0xE7, 0x6A, 0xE7, 0xCE, 100);
-
-//  Name:     System.EndDate -- PKEY_EndDate
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: C75FAA05-96FD-49E7-9CB4-9F601082D553, 100
-DEFINE_PROPERTYKEY(PKEY_EndDate, 0xC75FAA05, 0x96FD, 0x49E7, 0x9C, 0xB4, 0x9F, 0x60, 0x10, 0x82, 0xD5, 0x53, 100);
-
-//  Name:     System.FileAllocationSize -- PKEY_FileAllocationSize
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 18 (PID_STG_ALLOCSIZE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_FileAllocationSize, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 18);
-
-//  Name:     System.FileAttributes -- PKEY_FileAttributes
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 13 (PID_STG_ATTRIBUTES)
-//  
-//  This is the WIN32_FIND_DATA dwFileAttributes for the file-based item.
-DEFINE_PROPERTYKEY(PKEY_FileAttributes, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 13);
-
-//  Name:     System.FileCount -- PKEY_FileCount
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 12
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_FileCount, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 12);
-
-//  Name:     System.FileDescription -- PKEY_FileDescription
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSFMTID_VERSION) 0CEF7D53-FA64-11D1-A203-0000F81FEDEE, 3 (PIDVSI_FileDescription)
-//  
-//  This is a user-friendly description of the file.
-DEFINE_PROPERTYKEY(PKEY_FileDescription, 0x0CEF7D53, 0xFA64, 0x11D1, 0xA2, 0x03, 0x00, 0x00, 0xF8, 0x1F, 0xED, 0xEE, 3);
-
-//  Name:     System.FileExtension -- PKEY_FileExtension
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E4F10A3C-49E6-405D-8288-A23BD4EEAA6C, 100
-//  
-//  This is the file extension of the file based item, including the leading period.  
-//  
-//  If System.FileName is VT_EMPTY, then this property should be too.  Otherwise, it should be derived
-//  appropriately by the data source from System.FileName.  If System.FileName does not have a file 
-//  extension, this value should be VT_EMPTY.
-//  
-//  To obtain the type of any item (including an item that is not a file), use System.ItemType.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                ".txt"
-//      "\\server\share\mydir\goodnews.doc"   ".doc"
-//      "\\server\share\numbers.xls"          ".xls"
-//      "\\server\share\folder"               VT_EMPTY
-//      "c:\foo\MyFolder"                     VT_EMPTY
-//      [desktop]                             VT_EMPTY
-DEFINE_PROPERTYKEY(PKEY_FileExtension, 0xE4F10A3C, 0x49E6, 0x405D, 0x82, 0x88, 0xA2, 0x3B, 0xD4, 0xEE, 0xAA, 0x6C, 100);
-
-//  Name:     System.FileFRN -- PKEY_FileFRN
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 21 (PID_STG_FRN)
-//  
-//  This is the unique file ID, also known as the File Reference Number. For a given file, this is the same value
-//  as is found in the structure variable FILE_ID_BOTH_DIR_INFO.FileId, via GetFileInformationByHandleEx().
-DEFINE_PROPERTYKEY(PKEY_FileFRN, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 21);
-
-//  Name:     System.FileName -- PKEY_FileName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 41CF5AE0-F75A-4806-BD87-59C7D9248EB9, 100
-//  
-//  This is the file name (including extension) of the file.
-//  
-//  It is possible that the item might not exist on a filesystem (ie, it may not be opened 
-//  using CreateFile).  Nonetheless, if the item is represented as a file from the logical sense 
-//  (and its name follows standard Win32 file-naming syntax), then the data source should emit this property.
-//  
-//  If an item is not a file, then the value for this property is VT_EMPTY.  See 
-//  System.ItemNameDisplay.
-//  
-//  This has the same value as System.ParsingName for items that are provided by the Shell's file folder.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "hello.txt"
-//      "\\server\share\mydir\goodnews.doc"   "goodnews.doc"
-//      "\\server\share\numbers.xls"          "numbers.xls"
-//      "c:\foo\MyFolder"                     "MyFolder"
-//      (email message)                       VT_EMPTY
-//      (song on portable device)             "song.wma"
-DEFINE_PROPERTYKEY(PKEY_FileName, 0x41CF5AE0, 0xF75A, 0x4806, 0xBD, 0x87, 0x59, 0xC7, 0xD9, 0x24, 0x8E, 0xB9, 100);
-
-//  Name:     System.FileOwner -- PKEY_FileOwner
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Misc) 9B174B34-40FF-11D2-A27E-00C04FC30871, 4 (PID_MISC_OWNER)
-//  
-//  This is the owner of the file, according to the file system.
-DEFINE_PROPERTYKEY(PKEY_FileOwner, 0x9B174B34, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 4);
-
-//  Name:     System.FileVersion -- PKEY_FileVersion
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSFMTID_VERSION) 0CEF7D53-FA64-11D1-A203-0000F81FEDEE, 4 (PIDVSI_FileVersion)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_FileVersion, 0x0CEF7D53, 0xFA64, 0x11D1, 0xA2, 0x03, 0x00, 0x00, 0xF8, 0x1F, 0xED, 0xEE, 4);
-
-//  Name:     System.FindData -- PKEY_FindData
-//  Type:     Buffer -- VT_VECTOR | VT_UI1  (For variants: VT_ARRAY | VT_UI1)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 0 (PID_FINDDATA)
-//
-//  WIN32_FIND_DATAW in buffer of bytes.
-DEFINE_PROPERTYKEY(PKEY_FindData, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 0);
-
-//  Name:     System.FlagColor -- PKEY_FlagColor
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: 67DF94DE-0CA7-4D6F-B792-053A3E4F03CF, 100
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_FlagColor, 0x67DF94DE, 0x0CA7, 0x4D6F, 0xB7, 0x92, 0x05, 0x3A, 0x3E, 0x4F, 0x03, 0xCF, 100);
-
-// Possible discrete values for PKEY_FlagColor are:
-#define FLAGCOLOR_PURPLE                    1u
-#define FLAGCOLOR_ORANGE                    2u
-#define FLAGCOLOR_GREEN                     3u
-#define FLAGCOLOR_YELLOW                    4u
-#define FLAGCOLOR_BLUE                      5u
-#define FLAGCOLOR_RED                       6u
-
-//  Name:     System.FlagColorText -- PKEY_FlagColorText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 45EAE747-8E2A-40AE-8CBF-CA52ABA6152A, 100
-//  
-//  This is the user-friendly form of System.FlagColor.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_FlagColorText, 0x45EAE747, 0x8E2A, 0x40AE, 0x8C, 0xBF, 0xCA, 0x52, 0xAB, 0xA6, 0x15, 0x2A, 100);
-
-//  Name:     System.FlagStatus -- PKEY_FlagStatus
-//  Type:     Int32 -- VT_I4
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 12
-//
-//  Status of Flag.  Values: (0=none 1=white 2=Red).  cdoPR_FLAG_STATUS
-DEFINE_PROPERTYKEY(PKEY_FlagStatus, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 12);
-
-// Possible discrete values for PKEY_FlagStatus are:
-#define FLAGSTATUS_NOTFLAGGED               0l
-#define FLAGSTATUS_COMPLETED                1l
-#define FLAGSTATUS_FOLLOWUP                 2l
-
-//  Name:     System.FlagStatusText -- PKEY_FlagStatusText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DC54FD2E-189D-4871-AA01-08C2F57A4ABC, 100
-//  
-//  This is the user-friendly form of System.FlagStatus.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_FlagStatusText, 0xDC54FD2E, 0x189D, 0x4871, 0xAA, 0x01, 0x08, 0xC2, 0xF5, 0x7A, 0x4A, 0xBC, 100);
-
-//  Name:     System.FreeSpace -- PKEY_FreeSpace
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_Volume) 9B174B35-40FF-11D2-A27E-00C04FC30871, 2 (PID_VOLUME_FREE)  (Filesystem Volume Properties)
-//
-//  The amount of free space in bytes.
-DEFINE_PROPERTYKEY(PKEY_FreeSpace, 0x9B174B35, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 2);
-
-//  Name:     System.Identity -- PKEY_Identity
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A26F4AFC-7346-4299-BE47-EB1AE613139F, 100
-DEFINE_PROPERTYKEY(PKEY_Identity, 0xA26F4AFC, 0x7346, 0x4299, 0xBE, 0x47, 0xEB, 0x1A, 0xE6, 0x13, 0x13, 0x9F, 100);
-
-//  Name:     System.Importance -- PKEY_Importance
-//  Type:     Int32 -- VT_I4
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 11
-DEFINE_PROPERTYKEY(PKEY_Importance, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 11);
-
-// Possible range of values for PKEY_Importance are:
-#define IMPORTANCE_LOW_MIN                  0l
-#define IMPORTANCE_LOW_SET                  1l
-#define IMPORTANCE_LOW_MAX                  1l
-
-#define IMPORTANCE_NORMAL_MIN               2l
-#define IMPORTANCE_NORMAL_SET               3l
-#define IMPORTANCE_NORMAL_MAX               4l
-
-#define IMPORTANCE_HIGH_MIN                 5l
-#define IMPORTANCE_HIGH_SET                 5l
-#define IMPORTANCE_HIGH_MAX                 5l
-
-
-//  Name:     System.ImportanceText -- PKEY_ImportanceText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A3B29791-7713-4E1D-BB40-17DB85F01831, 100
-//  
-//  This is the user-friendly form of System.Importance.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_ImportanceText, 0xA3B29791, 0x7713, 0x4E1D, 0xBB, 0x40, 0x17, 0xDB, 0x85, 0xF0, 0x18, 0x31, 100);
-
-//  Name:     System.IsAttachment -- PKEY_IsAttachment
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: F23F425C-71A1-4FA8-922F-678EA4A60408, 100
-//
-//  Identifies if this item is an attachment.
-DEFINE_PROPERTYKEY(PKEY_IsAttachment, 0xF23F425C, 0x71A1, 0x4FA8, 0x92, 0x2F, 0x67, 0x8E, 0xA4, 0xA6, 0x04, 0x08, 100);
-
-//  Name:     System.IsDeleted -- PKEY_IsDeleted
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 5CDA5FC8-33EE-4FF3-9094-AE7BD8868C4D, 100
-DEFINE_PROPERTYKEY(PKEY_IsDeleted, 0x5CDA5FC8, 0x33EE, 0x4FF3, 0x90, 0x94, 0xAE, 0x7B, 0xD8, 0x86, 0x8C, 0x4D, 100);
-
-//  Name:     System.IsFlagged -- PKEY_IsFlagged
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 5DA84765-E3FF-4278-86B0-A27967FBDD03, 100
-DEFINE_PROPERTYKEY(PKEY_IsFlagged, 0x5DA84765, 0xE3FF, 0x4278, 0x86, 0xB0, 0xA2, 0x79, 0x67, 0xFB, 0xDD, 0x03, 100);
-
-//  Name:     System.IsFlaggedComplete -- PKEY_IsFlaggedComplete
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: A6F360D2-55F9-48DE-B909-620E090A647C, 100
-DEFINE_PROPERTYKEY(PKEY_IsFlaggedComplete, 0xA6F360D2, 0x55F9, 0x48DE, 0xB9, 0x09, 0x62, 0x0E, 0x09, 0x0A, 0x64, 0x7C, 100);
-
-//  Name:     System.IsIncomplete -- PKEY_IsIncomplete
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 346C8BD1-2E6A-4C45-89A4-61B78E8E700F, 100
-//
-//  Identifies if the message was not completely received for some error condition.
-DEFINE_PROPERTYKEY(PKEY_IsIncomplete, 0x346C8BD1, 0x2E6A, 0x4C45, 0x89, 0xA4, 0x61, 0xB7, 0x8E, 0x8E, 0x70, 0x0F, 100);
-
-//  Name:     System.IsRead -- PKEY_IsRead
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 10
-//
-//  Has the item been read?
-DEFINE_PROPERTYKEY(PKEY_IsRead, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 10);
-
-//  Name:     System.IsSendToTarget -- PKEY_IsSendToTarget
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 33
-//
-//  Provided by certain shell folders. Return TRUE if the folder is a valid Send To target.
-DEFINE_PROPERTYKEY(PKEY_IsSendToTarget, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 33);
-
-//  Name:     System.IsShared -- PKEY_IsShared
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: EF884C5B-2BFE-41BB-AAE5-76EEDF4F9902, 100
-//
-//  Is this item shared?
-DEFINE_PROPERTYKEY(PKEY_IsShared, 0xEF884C5B, 0x2BFE, 0x41BB, 0xAA, 0xE5, 0x76, 0xEE, 0xDF, 0x4F, 0x99, 0x02, 100);
-
-//  Name:     System.ItemAuthors -- PKEY_ItemAuthors
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D0A04F0A-462A-48A4-BB2F-3706E88DBD7D, 100
-//  
-//  This is the generic list of authors associated with an item. 
-//  
-//  For example, the artist name for a track is the item author.
-DEFINE_PROPERTYKEY(PKEY_ItemAuthors, 0xD0A04F0A, 0x462A, 0x48A4, 0xBB, 0x2F, 0x37, 0x06, 0xE8, 0x8D, 0xBD, 0x7D, 100);
-
-//  Name:     System.ItemDate -- PKEY_ItemDate
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: F7DB74B4-4287-4103-AFBA-F1B13DCD75CF, 100
-//  
-//  This is the main date for an item. The date of interest. 
-//  
-//  For example, for photos this maps to System.Photo.DateTaken.
-DEFINE_PROPERTYKEY(PKEY_ItemDate, 0xF7DB74B4, 0x4287, 0x4103, 0xAF, 0xBA, 0xF1, 0xB1, 0x3D, 0xCD, 0x75, 0xCF, 100);
-
-//  Name:     System.ItemFolderNameDisplay -- PKEY_ItemFolderNameDisplay
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 2 (PID_STG_DIRECTORY)
-//  
-//  This is the user-friendly display name of the parent folder of an item.
-//  
-//  If System.ItemFolderPathDisplay is VT_EMPTY, then this property should be too.  Otherwise, it 
-//  should be derived appropriately by the data source from System.ItemFolderPathDisplay.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "bar"
-//      "\\server\share\mydir\goodnews.doc"   "mydir"
-//      "\\server\share\numbers.xls"          "share"
-//      "c:\foo\MyFolder"                     "foo"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "Inbox"
-DEFINE_PROPERTYKEY(PKEY_ItemFolderNameDisplay, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 2);
-
-//  Name:     System.ItemFolderPathDisplay -- PKEY_ItemFolderPathDisplay
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 6
-//  
-//  This is the user-friendly display path of the parent folder of an item.
-//  
-//  If System.ItemPathDisplay is VT_EMPTY, then this property should be too.  Otherwise, it should 
-//  be derived appropriately by the data source from System.ItemPathDisplay.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "c:\foo\bar"
-//      "\\server\share\mydir\goodnews.doc"   "\\server\share\mydir"
-//      "\\server\share\numbers.xls"          "\\server\share"
-//      "c:\foo\MyFolder"                     "c:\foo"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "/Mailbox Account/Inbox"
-DEFINE_PROPERTYKEY(PKEY_ItemFolderPathDisplay, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 6);
-
-//  Name:     System.ItemFolderPathDisplayNarrow -- PKEY_ItemFolderPathDisplayNarrow
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DABD30ED-0043-4789-A7F8-D013A4736622, 100
-//  
-//  This is the user-friendly display path of the parent folder of an item.  The format of the string
-//  should be tailored such that the folder name comes first, to optimize for a narrow viewing column.
-//  
-//  If the folder is a file folder, the value includes localized names if they are present.
-//  
-//  If System.ItemFolderPathDisplay is VT_EMPTY, then this property should be too.  Otherwise, it should
-//  be derived appropriately by the data source from System.ItemFolderPathDisplay.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "bar (c:\foo)"
-//      "\\server\share\mydir\goodnews.doc"   "mydir (\\server\share)"
-//      "\\server\share\numbers.xls"          "share (\\server)"
-//      "c:\foo\MyFolder"                     "foo (c:\)"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "Inbox (/Mailbox Account)"
-DEFINE_PROPERTYKEY(PKEY_ItemFolderPathDisplayNarrow, 0xDABD30ED, 0x0043, 0x4789, 0xA7, 0xF8, 0xD0, 0x13, 0xA4, 0x73, 0x66, 0x22, 100);
-
-//  Name:     System.ItemName -- PKEY_ItemName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6B8DA074-3B5C-43BC-886F-0A2CDCE00B6F, 100
-//  
-//  This is the base-name of the System.ItemNameDisplay.
-//  
-//  If the item is a file this property
-//  includes the extension in all cases, and will be localized if a localized name is available.
-//  
-//  If the item is a message, then the value of this property does not include the forwarding or
-//  reply prefixes (see System.ItemNamePrefix).
-DEFINE_PROPERTYKEY(PKEY_ItemName, 0x6B8DA074, 0x3B5C, 0x43BC, 0x88, 0x6F, 0x0A, 0x2C, 0xDC, 0xE0, 0x0B, 0x6F, 100);
-
-//  Name:     System.ItemNameDisplay -- PKEY_ItemNameDisplay
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 10 (PID_STG_NAME)
-//  
-//  This is the display name in "most complete" form.  This is the best effort unique representation
-//  of the name of an item that makes sense for end users to read.  It is the concatentation of
-//  System.ItemNamePrefix and System.ItemName.
-//  
-//  If the item is a file this property
-//  includes the extension in all cases, and will be localized if a localized name is available.
-//  
-//  There are acceptable cases when System.FileName is not VT_EMPTY, yet the value of this property 
-//  is completely different.  Email messages are a key example.  If the item is an email message, 
-//  the item name is likely the subject.  In that case, the value must be the concatenation of the
-//  System.ItemNamePrefix and System.ItemName.  Since the value of System.ItemNamePrefix excludes
-//  any trailing whitespace, the concatenation must include a whitespace when generating System.ItemNameDisplay.
-//  
-//  Note that this property is not guaranteed to be unique, but the idea is to promote the most likely
-//  candidate that can be unique and also makes sense for end users. For example, for documents, you
-//  might think about using System.Title as the System.ItemNameDisplay, but in practice the title of
-//  the documents may not be useful or unique enough to be of value as the sole System.ItemNameDisplay.  
-//  Instead, providing the value of System.FileName as the value of System.ItemNameDisplay is a better
-//  candidate.  In Windows Mail, the emails are stored in the file system as .eml files and the 
-//  System.FileName for those files are not human-friendly as they contain GUIDs. In this example, 
-//  promoting System.Subject as System.ItemNameDisplay makes more sense.
-//  
-//  Compatibility notes:
-//  
-//  Shell folder implementations on Vista: use PKEY_ItemNameDisplay for the name column when
-//  you want Explorer to call ISF::GetDisplayNameOf(SHGDN_NORMAL) to get the value of the name. Use
-//  another PKEY (like PKEY_ItemName) when you want Explorer to call either the folder's property store or
-//  ISF2::GetDetailsEx in order to get the value of the name.
-//  
-//  Shell folder implementations on XP: the first column needs to be the name column, and Explorer
-//  will call ISF::GetDisplayNameOf to get the value of the name.  The PKEY/SCID does not matter.
-//  
-//  Example values:
-//  
-//      File:          "hello.txt"
-//      Message:       "Re: Let's talk about Tom's argyle socks!"
-//      Device folder: "song.wma"
-//      Folder:        "Documents"
-DEFINE_PROPERTYKEY(PKEY_ItemNameDisplay, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 10);
-
-//  Name:     System.ItemNamePrefix -- PKEY_ItemNamePrefix
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: D7313FF1-A77A-401C-8C99-3DBDD68ADD36, 100
-//  
-//  This is the prefix of an item, used for email messages.
-//  where the subject begins with "Re:" which is the prefix.
-//  
-//  If the item is a file, then the value of this property is VT_EMPTY.
-//  
-//  If the item is a message, then the value of this property is the forwarding or reply 
-//  prefixes (including delimiting colon, but no whitespace), or VT_EMPTY if there is no prefix.
-//  
-//  Example values:
-//  
-//  System.ItemNamePrefix    System.ItemName      System.ItemNameDisplay
-//  ---------------------    -------------------  ----------------------
-//  VT_EMPTY                 "Great day"          "Great day"
-//  "Re:"                    "Great day"          "Re: Great day"
-//  "Fwd: "                  "Monthly budget"     "Fwd: Monthly budget"
-//  VT_EMPTY                 "accounts.xls"       "accounts.xls"
-DEFINE_PROPERTYKEY(PKEY_ItemNamePrefix, 0xD7313FF1, 0xA77A, 0x401C, 0x8C, 0x99, 0x3D, 0xBD, 0xD6, 0x8A, 0xDD, 0x36, 100);
-
-//  Name:     System.ItemParticipants -- PKEY_ItemParticipants
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D4D0AA16-9948-41A4-AA85-D97FF9646993, 100
-//  
-//  This is the generic list of people associated with an item and who contributed 
-//  to the item. 
-//  
-//  For example, this is the combination of people in the To list, Cc list and 
-//  sender of an email message.
-DEFINE_PROPERTYKEY(PKEY_ItemParticipants, 0xD4D0AA16, 0x9948, 0x41A4, 0xAA, 0x85, 0xD9, 0x7F, 0xF9, 0x64, 0x69, 0x93, 100);
-
-//  Name:     System.ItemPathDisplay -- PKEY_ItemPathDisplay
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 7
-//  
-//  This is the user-friendly display path to the item.
-//  
-//  If the item is a file or folder this property
-//  includes the extension in all cases, and will be localized if a localized name is available.
-//  
-//  For other items,this is the user-friendly equivalent, assuming the item exists in hierarchical storage.
-//  
-//  Unlike System.ItemUrl, this property value does not include the URL scheme.
-//  
-//  To parse an item path, use System.ItemUrl or System.ParsingPath.  To reference shell 
-//  namespace items using shell APIs, use System.ParsingPath.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "c:\foo\bar\hello.txt"
-//      "\\server\share\mydir\goodnews.doc"   "\\server\share\mydir\goodnews.doc"
-//      "\\server\share\numbers.xls"          "\\server\share\numbers.xls"
-//      "c:\foo\MyFolder"                     "c:\foo\MyFolder"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "/Mailbox Account/Inbox/'Re: Hello!'"
-DEFINE_PROPERTYKEY(PKEY_ItemPathDisplay, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 7);
-
-//  Name:     System.ItemPathDisplayNarrow -- PKEY_ItemPathDisplayNarrow
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 8
-//  
-//  This is the user-friendly display path to the item. The format of the string should be 
-//  tailored such that the name comes first, to optimize for a narrow viewing column.
-//  
-//  If the item is a file, the value excludes the file extension, and includes localized names if they are present.
-//  If the item is a message, the value includes the System.ItemNamePrefix.
-//  
-//  To parse an item path, use System.ItemUrl or System.ParsingPath.
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "hello (c:\foo\bar)"
-//      "\\server\share\mydir\goodnews.doc"   "goodnews (\\server\share\mydir)"
-//      "\\server\share\folder"               "folder (\\server\share)"
-//      "c:\foo\MyFolder"                     "MyFolder (c:\foo)"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "Re: Hello! (/Mailbox Account/Inbox)"
-DEFINE_PROPERTYKEY(PKEY_ItemPathDisplayNarrow, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 8);
-
-//  Name:     System.ItemType -- PKEY_ItemType
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 11
-//  
-//  This is the canonical type of the item and is intended to be programmatically
-//  parsed.
-//  
-//  If there is no canonical type, the value is VT_EMPTY.
-//  
-//  If the item is a file (ie, System.FileName is not VT_EMPTY), the value is the same as
-//  System.FileExtension.
-//  
-//  Use System.ItemTypeText when you want to display the type to end users in a view.  (If
-//   the item is a file, passing the System.ItemType value to PSFormatForDisplay will
-//   result in the same value as System.ItemTypeText.)
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                ".txt"
-//      "\\server\share\mydir\goodnews.doc"   ".doc"
-//      "\\server\share\folder"               "Directory"
-//      "c:\foo\MyFolder"                     "Directory"
-//      [desktop]                             "Folder"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "MAPI/IPM.Message"
-DEFINE_PROPERTYKEY(PKEY_ItemType, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 11);
-
-//  Name:     System.ItemTypeText -- PKEY_ItemTypeText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 4 (PID_STG_STORAGETYPE)
-//  
-//  This is the user friendly type name of the item.  This is not intended to be
-//  programmatically parsed.
-//  
-//  If System.ItemType is VT_EMPTY, the value of this property is also VT_EMPTY.
-//  
-//  If the item is a file, the value of this property is the same as if you passed the 
-//  file's System.ItemType value to PSFormatForDisplay.
-//  
-//  This property should not be confused with System.Kind, where System.Kind is a high-level
-//  user friendly kind name. For example, for a document, System.Kind = "Document" and 
-//  System.Item.Type = ".doc" and System.Item.TypeText = "Microsoft Word Document"
-//  
-//  Example values:
-//  
-//      If the path is...                     The property value is...
-//      -----------------                     ------------------------
-//      "c:\foo\bar\hello.txt"                "Text File"
-//      "\\server\share\mydir\goodnews.doc"   "Microsoft Word Document"
-//      "\\server\share\folder"               "File Folder"
-//      "c:\foo\MyFolder"                     "File Folder"
-//      "/Mailbox Account/Inbox/'Re: Hello!'" "Outlook E-Mail Message"
-DEFINE_PROPERTYKEY(PKEY_ItemTypeText, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 4);
-
-//  Name:     System.ItemUrl -- PKEY_ItemUrl
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Query) 49691C90-7E17-101A-A91C-08002B2ECDA9, 9 (PROPID_QUERY_VIRTUALPATH)
-//  
-//  This always represents a well formed URL that points to the item.  
-//  
-//  To reference shell namespace items using shell APIs, use System.ParsingPath.
-//  
-//  Example values:
-//  
-//      Files:    "file:///c:/foo/bar/hello.txt"
-//                "csc://{GUID}/..."
-//      Messages: "mapi://..."
-DEFINE_PROPERTYKEY(PKEY_ItemUrl, 0x49691C90, 0x7E17, 0x101A, 0xA9, 0x1C, 0x08, 0x00, 0x2B, 0x2E, 0xCD, 0xA9, 9);
-
-//  Name:     System.Keywords -- PKEY_Keywords
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)  Legacy code may treat this as VT_LPSTR.
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 5 (PIDSI_KEYWORDS)
-//
-//  The keywords for the item.  Also referred to as tags.
-DEFINE_PROPERTYKEY(PKEY_Keywords, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 5);
-
-//  Name:     System.Kind -- PKEY_Kind
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 1E3EE840-BC2B-476C-8237-2ACD1A839B22, 3
-//  
-//  System.Kind is used to map extensions to various .Search folders.
-//  Extensions are mapped to Kinds at HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\KindMap
-//  The list of kinds is not extensible.
-DEFINE_PROPERTYKEY(PKEY_Kind, 0x1E3EE840, 0xBC2B, 0x476C, 0x82, 0x37, 0x2A, 0xCD, 0x1A, 0x83, 0x9B, 0x22, 3);
-
-// Possible discrete values for PKEY_Kind are:
-#define KIND_CALENDAR                       L"calendar"
-#define KIND_COMMUNICATION                  L"communication"
-#define KIND_CONTACT                        L"contact"
-#define KIND_DOCUMENT                       L"document"
-#define KIND_EMAIL                          L"email"
-#define KIND_FEED                           L"feed"
-#define KIND_FOLDER                         L"folder"
-#define KIND_GAME                           L"game"
-#define KIND_INSTANTMESSAGE                 L"instantmessage"
-#define KIND_JOURNAL                        L"journal"
-#define KIND_LINK                           L"link"
-#define KIND_MOVIE                          L"movie"
-#define KIND_MUSIC                          L"music"
-#define KIND_NOTE                           L"note"
-#define KIND_PICTURE                        L"picture"
-#define KIND_PROGRAM                        L"program"
-#define KIND_RECORDEDTV                     L"recordedtv"
-#define KIND_SEARCHFOLDER                   L"searchfolder"
-#define KIND_TASK                           L"task"
-#define KIND_VIDEO                          L"video"
-#define KIND_WEBHISTORY                     L"webhistory"
-
-//  Name:     System.KindText -- PKEY_KindText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F04BEF95-C585-4197-A2B7-DF46FDC9EE6D, 100
-//  
-//  This is the user-friendly form of System.Kind.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_KindText, 0xF04BEF95, 0xC585, 0x4197, 0xA2, 0xB7, 0xDF, 0x46, 0xFD, 0xC9, 0xEE, 0x6D, 100);
-
-//  Name:     System.Language -- PKEY_Language
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 28
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Language, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 28);
-
-//  Name:     System.MileageInformation -- PKEY_MileageInformation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: FDF84370-031A-4ADD-9E91-0D775F1C6605, 100
-DEFINE_PROPERTYKEY(PKEY_MileageInformation, 0xFDF84370, 0x031A, 0x4ADD, 0x9E, 0x91, 0x0D, 0x77, 0x5F, 0x1C, 0x66, 0x05, 100);
-
-//  Name:     System.MIMEType -- PKEY_MIMEType
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 0B63E350-9CCC-11D0-BCDB-00805FCCCE04, 5
-//
-//  The MIME type.  Eg, for EML files: 'message/rfc822'.
-DEFINE_PROPERTYKEY(PKEY_MIMEType, 0x0B63E350, 0x9CCC, 0x11D0, 0xBC, 0xDB, 0x00, 0x80, 0x5F, 0xCC, 0xCE, 0x04, 5);
-
-//  Name:     System.Null -- PKEY_Null
-//  Type:     Null -- VT_NULL
-//  FormatID: 00000000-0000-0000-0000-000000000000, 0
-DEFINE_PROPERTYKEY(PKEY_Null, 0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0);
-
-//  Name:     System.OfflineAvailability -- PKEY_OfflineAvailability
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: A94688B6-7D9F-4570-A648-E3DFC0AB2B3F, 100
-DEFINE_PROPERTYKEY(PKEY_OfflineAvailability, 0xA94688B6, 0x7D9F, 0x4570, 0xA6, 0x48, 0xE3, 0xDF, 0xC0, 0xAB, 0x2B, 0x3F, 100);
-
-// Possible discrete values for PKEY_OfflineAvailability are:
-#define OFFLINEAVAILABILITY_NOT_AVAILABLE   0ul
-#define OFFLINEAVAILABILITY_AVAILABLE       1ul
-#define OFFLINEAVAILABILITY_ALWAYS_AVAILABLE 2ul
-
-//  Name:     System.OfflineStatus -- PKEY_OfflineStatus
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 6D24888F-4718-4BDA-AFED-EA0FB4386CD8, 100
-DEFINE_PROPERTYKEY(PKEY_OfflineStatus, 0x6D24888F, 0x4718, 0x4BDA, 0xAF, 0xED, 0xEA, 0x0F, 0xB4, 0x38, 0x6C, 0xD8, 100);
-
-// Possible discrete values for PKEY_OfflineStatus are:
-#define OFFLINESTATUS_ONLINE                0ul
-#define OFFLINESTATUS_OFFLINE               1ul
-#define OFFLINESTATUS_OFFLINE_FORCED        2ul
-#define OFFLINESTATUS_OFFLINE_SLOW          3ul
-#define OFFLINESTATUS_OFFLINE_ERROR         4ul
-#define OFFLINESTATUS_OFFLINE_ITEM_VERSION_CONFLICT 5ul
-#define OFFLINESTATUS_OFFLINE_SUSPENDED     6ul
-
-//  Name:     System.OriginalFileName -- PKEY_OriginalFileName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSFMTID_VERSION) 0CEF7D53-FA64-11D1-A203-0000F81FEDEE, 6
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_OriginalFileName, 0x0CEF7D53, 0xFA64, 0x11D1, 0xA2, 0x03, 0x00, 0x00, 0xF8, 0x1F, 0xED, 0xEE, 6);
-
-//  Name:     System.ParentalRating -- PKEY_ParentalRating
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 21 (PIDMSI_PARENTAL_RATING)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_ParentalRating, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 21);
-
-//  Name:     System.ParentalRatingReason -- PKEY_ParentalRatingReason
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 10984E0A-F9F2-4321-B7EF-BAF195AF4319, 100
-DEFINE_PROPERTYKEY(PKEY_ParentalRatingReason, 0x10984E0A, 0xF9F2, 0x4321, 0xB7, 0xEF, 0xBA, 0xF1, 0x95, 0xAF, 0x43, 0x19, 100);
-
-//  Name:     System.ParentalRatingsOrganization -- PKEY_ParentalRatingsOrganization
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A7FE0840-1344-46F0-8D37-52ED712A4BF9, 100
-DEFINE_PROPERTYKEY(PKEY_ParentalRatingsOrganization, 0xA7FE0840, 0x1344, 0x46F0, 0x8D, 0x37, 0x52, 0xED, 0x71, 0x2A, 0x4B, 0xF9, 100);
-
-//  Name:     System.ParsingBindContext -- PKEY_ParsingBindContext
-//  Type:     Any -- VT_NULL  Legacy code may treat this as VT_UNKNOWN.
-//  FormatID: DFB9A04D-362F-4CA3-B30B-0254B17B5B84, 100
-//  
-//  used to get the IBindCtx for an item for parsing
-DEFINE_PROPERTYKEY(PKEY_ParsingBindContext, 0xDFB9A04D, 0x362F, 0x4CA3, 0xB3, 0x0B, 0x02, 0x54, 0xB1, 0x7B, 0x5B, 0x84, 100);
-
-//  Name:     System.ParsingName -- PKEY_ParsingName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 24
-//  
-//  The shell namespace name of an item relative to a parent folder.  This name may be passed to 
-//  IShellFolder::ParseDisplayName() of the parent shell folder.
-DEFINE_PROPERTYKEY(PKEY_ParsingName, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 24);
-
-//  Name:     System.ParsingPath -- PKEY_ParsingPath
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 30
-//  
-//  This is the shell namespace path to the item.  This path may be passed to 
-//  SHParseDisplayName to parse the path to the correct shell folder.
-//  
-//  If the item is a file, the value is identical to System.ItemPathDisplay.
-//  
-//  If the item cannot be accessed through the shell namespace, this value is VT_EMPTY.
-DEFINE_PROPERTYKEY(PKEY_ParsingPath, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 30);
-
-//  Name:     System.PerceivedType -- PKEY_PerceivedType
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 9
-//
-//  The perceived type of a shell item, based upon its canonical type.
-DEFINE_PROPERTYKEY(PKEY_PerceivedType, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 9);
-
-// For the enumerated values of PKEY_PerceivedType, see the PERCEIVED_TYPE_* values in shtypes.idl.
-
-//  Name:     System.PercentFull -- PKEY_PercentFull
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_Volume) 9B174B35-40FF-11D2-A27E-00C04FC30871, 5  (Filesystem Volume Properties)
-//
-//  The amount filled as a percentage, multiplied by 100 (ie, the valid range is 0 through 100).
-DEFINE_PROPERTYKEY(PKEY_PercentFull, 0x9B174B35, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 5);
-
-//  Name:     System.Priority -- PKEY_Priority
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: 9C1FCF74-2D97-41BA-B4AE-CB2E3661A6E4, 5
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Priority, 0x9C1FCF74, 0x2D97, 0x41BA, 0xB4, 0xAE, 0xCB, 0x2E, 0x36, 0x61, 0xA6, 0xE4, 5);
-
-// Possible discrete values for PKEY_Priority are:
-#define PRIORITY_PROP_LOW                   0u
-#define PRIORITY_PROP_NORMAL                1u
-#define PRIORITY_PROP_HIGH                  2u
-
-//  Name:     System.PriorityText -- PKEY_PriorityText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: D98BE98B-B86B-4095-BF52-9D23B2E0A752, 100
-//  
-//  This is the user-friendly form of System.Priority.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_PriorityText, 0xD98BE98B, 0xB86B, 0x4095, 0xBF, 0x52, 0x9D, 0x23, 0xB2, 0xE0, 0xA7, 0x52, 100);
-
-//  Name:     System.Project -- PKEY_Project
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 39A7F922-477C-48DE-8BC8-B28441E342E3, 100
-DEFINE_PROPERTYKEY(PKEY_Project, 0x39A7F922, 0x477C, 0x48DE, 0x8B, 0xC8, 0xB2, 0x84, 0x41, 0xE3, 0x42, 0xE3, 100);
-
-//  Name:     System.ProviderItemID -- PKEY_ProviderItemID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F21D9941-81F0-471A-ADEE-4E74B49217ED, 100
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_ProviderItemID, 0xF21D9941, 0x81F0, 0x471A, 0xAD, 0xEE, 0x4E, 0x74, 0xB4, 0x92, 0x17, 0xED, 100);
-
-//  Name:     System.Rating -- PKEY_Rating
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 9 (PIDMSI_RATING)
-//  
-//  Indicates the users preference rating of an item on a scale of 0-99 (0 = unrated, 1-12 = One Star, 
-//  13-37 = Two Stars, 38-62 = Three Stars, 63-87 = Four Stars, 88-99 = Five Stars).
-DEFINE_PROPERTYKEY(PKEY_Rating, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 9);
-
-// Use the following constants to convert between visual stars and the ratings value:
-#define RATING_UNRATED_MIN                  0ul
-#define RATING_UNRATED_SET                  0ul
-#define RATING_UNRATED_MAX                  0ul
-
-#define RATING_ONE_STAR_MIN                 1ul
-#define RATING_ONE_STAR_SET                 1ul
-#define RATING_ONE_STAR_MAX                 12ul
-
-#define RATING_TWO_STARS_MIN                13ul
-#define RATING_TWO_STARS_SET                25ul
-#define RATING_TWO_STARS_MAX                37ul
-
-#define RATING_THREE_STARS_MIN              38ul
-#define RATING_THREE_STARS_SET              50ul
-#define RATING_THREE_STARS_MAX              62ul
-
-#define RATING_FOUR_STARS_MIN               63ul
-#define RATING_FOUR_STARS_SET               75ul
-#define RATING_FOUR_STARS_MAX               87ul
-
-#define RATING_FIVE_STARS_MIN               88ul
-#define RATING_FIVE_STARS_SET               99ul
-#define RATING_FIVE_STARS_MAX               99ul
-
-
-//  Name:     System.RatingText -- PKEY_RatingText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 90197CA7-FD8F-4E8C-9DA3-B57E1E609295, 100
-//  
-//  This is the user-friendly form of System.Rating.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_RatingText, 0x90197CA7, 0xFD8F, 0x4E8C, 0x9D, 0xA3, 0xB5, 0x7E, 0x1E, 0x60, 0x92, 0x95, 100);
-
-//  Name:     System.Sensitivity -- PKEY_Sensitivity
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: F8D3F6AC-4874-42CB-BE59-AB454B30716A, 100
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Sensitivity, 0xF8D3F6AC, 0x4874, 0x42CB, 0xBE, 0x59, 0xAB, 0x45, 0x4B, 0x30, 0x71, 0x6A, 100);
-
-// Possible discrete values for PKEY_Sensitivity are:
-#define SENSITIVITY_PROP_NORMAL             0u
-#define SENSITIVITY_PROP_PERSONAL           1u
-#define SENSITIVITY_PROP_PRIVATE            2u
-#define SENSITIVITY_PROP_CONFIDENTIAL       3u
-
-//  Name:     System.SensitivityText -- PKEY_SensitivityText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: D0C7F054-3F72-4725-8527-129A577CB269, 100
-//  
-//  This is the user-friendly form of System.Sensitivity.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_SensitivityText, 0xD0C7F054, 0x3F72, 0x4725, 0x85, 0x27, 0x12, 0x9A, 0x57, 0x7C, 0xB2, 0x69, 100);
-
-//  Name:     System.SFGAOFlags -- PKEY_SFGAOFlags
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 25
-//
-//  IShellFolder::GetAttributesOf flags, with SFGAO_PKEYSFGAOMASK attributes masked out.
-DEFINE_PROPERTYKEY(PKEY_SFGAOFlags, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 25);
-
-//  Name:     System.SharedWith -- PKEY_SharedWith
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: EF884C5B-2BFE-41BB-AAE5-76EEDF4F9902, 200
-//
-//  Who is the item shared with?
-DEFINE_PROPERTYKEY(PKEY_SharedWith, 0xEF884C5B, 0x2BFE, 0x41BB, 0xAA, 0xE5, 0x76, 0xEE, 0xDF, 0x4F, 0x99, 0x02, 200);
-
-//  Name:     System.ShareUserRating -- PKEY_ShareUserRating
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 12 (PIDMSI_SHARE_USER_RATING)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_ShareUserRating, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 12);
-
-//  Name:     System.Shell.OmitFromView -- PKEY_Shell_OmitFromView
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DE35258C-C695-4CBC-B982-38B0AD24CED0, 2
-//  
-//  Set this to a string value of 'True' to omit this item from shell views
-DEFINE_PROPERTYKEY(PKEY_Shell_OmitFromView, 0xDE35258C, 0xC695, 0x4CBC, 0xB9, 0x82, 0x38, 0xB0, 0xAD, 0x24, 0xCE, 0xD0, 2);
-
-//  Name:     System.SimpleRating -- PKEY_SimpleRating
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: A09F084E-AD41-489F-8076-AA5BE3082BCA, 100
-//  
-//  Indicates the users preference rating of an item on a scale of 0-5 (0=unrated, 1=One Star, 2=Two Stars, 3=Three Stars,
-//  4=Four Stars, 5=Five Stars)
-DEFINE_PROPERTYKEY(PKEY_SimpleRating, 0xA09F084E, 0xAD41, 0x489F, 0x80, 0x76, 0xAA, 0x5B, 0xE3, 0x08, 0x2B, 0xCA, 100);
-
-//  Name:     System.Size -- PKEY_Size
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 12 (PID_STG_SIZE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Size, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 12);
-
-//  Name:     System.SoftwareUsed -- PKEY_SoftwareUsed
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 305
-//
-//  PropertyTagSoftwareUsed
-DEFINE_PROPERTYKEY(PKEY_SoftwareUsed, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 305);
-
-//  Name:     System.SourceItem -- PKEY_SourceItem
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 668CDFA5-7A1B-4323-AE4B-E527393A1D81, 100
-DEFINE_PROPERTYKEY(PKEY_SourceItem, 0x668CDFA5, 0x7A1B, 0x4323, 0xAE, 0x4B, 0xE5, 0x27, 0x39, 0x3A, 0x1D, 0x81, 100);
-
-//  Name:     System.StartDate -- PKEY_StartDate
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 48FD6EC8-8A12-4CDF-A03E-4EC5A511EDDE, 100
-DEFINE_PROPERTYKEY(PKEY_StartDate, 0x48FD6EC8, 0x8A12, 0x4CDF, 0xA0, 0x3E, 0x4E, 0xC5, 0xA5, 0x11, 0xED, 0xDE, 100);
-
-//  Name:     System.Status -- PKEY_Status
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_IntSite) 000214A1-0000-0000-C000-000000000046, 9
-DEFINE_PROPERTYKEY(PKEY_Status, 0x000214A1, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 9);
-
-//  Name:     System.Subject -- PKEY_Subject
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 3 (PIDSI_SUBJECT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Subject, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 3);
-
-//  Name:     System.Thumbnail -- PKEY_Thumbnail
-//  Type:     Clipboard -- VT_CF
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 17 (PIDSI_THUMBNAIL)
-//
-//  A data that represents the thumbnail in VT_CF format.
-DEFINE_PROPERTYKEY(PKEY_Thumbnail, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 17);
-
-//  Name:     System.ThumbnailCacheId -- PKEY_ThumbnailCacheId
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: 446D16B1-8DAD-4870-A748-402EA43D788C, 100
-//  
-//  Unique value that can be used as a key to cache thumbnails. The value changes when the name, volume, or data modified 
-//  of an item changes.
-DEFINE_PROPERTYKEY(PKEY_ThumbnailCacheId, 0x446D16B1, 0x8DAD, 0x4870, 0xA7, 0x48, 0x40, 0x2E, 0xA4, 0x3D, 0x78, 0x8C, 100);
-
-//  Name:     System.ThumbnailStream -- PKEY_ThumbnailStream
-//  Type:     Stream -- VT_STREAM
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 27
-//
-//  Data that represents the thumbnail in VT_STREAM format that GDI+/WindowsCodecs supports (jpg, png, etc).
-DEFINE_PROPERTYKEY(PKEY_ThumbnailStream, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 27);
-
-//  Name:     System.Title -- PKEY_Title
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)  Legacy code may treat this as VT_LPSTR.
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 2 (PIDSI_TITLE)
-//
-//  Title of item.
-DEFINE_PROPERTYKEY(PKEY_Title, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 2);
-
-//  Name:     System.TotalFileSize -- PKEY_TotalFileSize
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 14
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_TotalFileSize, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 14);
-
-//  Name:     System.Trademarks -- PKEY_Trademarks
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSFMTID_VERSION) 0CEF7D53-FA64-11D1-A203-0000F81FEDEE, 9 (PIDVSI_Trademarks)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Trademarks, 0x0CEF7D53, 0xFA64, 0x11D1, 0xA2, 0x03, 0x00, 0x00, 0xF8, 0x1F, 0xED, 0xEE, 9);
- 
-//-----------------------------------------------------------------------------
-// Document properties
-
-
-
-//  Name:     System.Document.ByteCount -- PKEY_Document_ByteCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 4 (PIDDSI_BYTECOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_ByteCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 4);
-
-//  Name:     System.Document.CharacterCount -- PKEY_Document_CharacterCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 16 (PIDSI_CHARCOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_CharacterCount, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 16);
-
-//  Name:     System.Document.ClientID -- PKEY_Document_ClientID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 276D7BB0-5B34-4FB0-AA4B-158ED12A1809, 100
-DEFINE_PROPERTYKEY(PKEY_Document_ClientID, 0x276D7BB0, 0x5B34, 0x4FB0, 0xAA, 0x4B, 0x15, 0x8E, 0xD1, 0x2A, 0x18, 0x09, 100);
-
-//  Name:     System.Document.Contributor -- PKEY_Document_Contributor
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: F334115E-DA1B-4509-9B3D-119504DC7ABB, 100
-DEFINE_PROPERTYKEY(PKEY_Document_Contributor, 0xF334115E, 0xDA1B, 0x4509, 0x9B, 0x3D, 0x11, 0x95, 0x04, 0xDC, 0x7A, 0xBB, 100);
-
-//  Name:     System.Document.DateCreated -- PKEY_Document_DateCreated
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 12 (PIDSI_CREATE_DTM)
-//  
-//  This property is stored in the document, not obtained from the file system.
-DEFINE_PROPERTYKEY(PKEY_Document_DateCreated, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 12);
-
-//  Name:     System.Document.DatePrinted -- PKEY_Document_DatePrinted
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 11 (PIDSI_LASTPRINTED)
-//
-//  Legacy name: "DocLastPrinted".
-DEFINE_PROPERTYKEY(PKEY_Document_DatePrinted, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 11);
-
-//  Name:     System.Document.DateSaved -- PKEY_Document_DateSaved
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 13 (PIDSI_LASTSAVE_DTM)
-//
-//  Legacy name: "DocLastSavedTm".
-DEFINE_PROPERTYKEY(PKEY_Document_DateSaved, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 13);
-
-//  Name:     System.Document.Division -- PKEY_Document_Division
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 1E005EE6-BF27-428B-B01C-79676ACD2870, 100
-DEFINE_PROPERTYKEY(PKEY_Document_Division, 0x1E005EE6, 0xBF27, 0x428B, 0xB0, 0x1C, 0x79, 0x67, 0x6A, 0xCD, 0x28, 0x70, 100);
-
-//  Name:     System.Document.DocumentID -- PKEY_Document_DocumentID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E08805C8-E395-40DF-80D2-54F0D6C43154, 100
-DEFINE_PROPERTYKEY(PKEY_Document_DocumentID, 0xE08805C8, 0xE395, 0x40DF, 0x80, 0xD2, 0x54, 0xF0, 0xD6, 0xC4, 0x31, 0x54, 100);
-
-//  Name:     System.Document.HiddenSlideCount -- PKEY_Document_HiddenSlideCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 9 (PIDDSI_HIDDENCOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_HiddenSlideCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 9);
-
-//  Name:     System.Document.LastAuthor -- PKEY_Document_LastAuthor
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 8 (PIDSI_LASTAUTHOR)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_LastAuthor, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 8);
-
-//  Name:     System.Document.LineCount -- PKEY_Document_LineCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 5 (PIDDSI_LINECOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_LineCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 5);
-
-//  Name:     System.Document.Manager -- PKEY_Document_Manager
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 14 (PIDDSI_MANAGER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_Manager, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 14);
-
-//  Name:     System.Document.MultimediaClipCount -- PKEY_Document_MultimediaClipCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 10 (PIDDSI_MMCLIPCOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_MultimediaClipCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 10);
-
-//  Name:     System.Document.NoteCount -- PKEY_Document_NoteCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 8 (PIDDSI_NOTECOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_NoteCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 8);
-
-//  Name:     System.Document.PageCount -- PKEY_Document_PageCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 14 (PIDSI_PAGECOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_PageCount, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 14);
-
-//  Name:     System.Document.ParagraphCount -- PKEY_Document_ParagraphCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 6 (PIDDSI_PARCOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_ParagraphCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 6);
-
-//  Name:     System.Document.PresentationFormat -- PKEY_Document_PresentationFormat
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 3 (PIDDSI_PRESFORMAT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_PresentationFormat, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 3);
-
-//  Name:     System.Document.RevisionNumber -- PKEY_Document_RevisionNumber
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 9 (PIDSI_REVNUMBER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_RevisionNumber, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 9);
-
-//  Name:     System.Document.Security -- PKEY_Document_Security
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 19
-//
-//  Access control information, from SummaryInfo propset
-DEFINE_PROPERTYKEY(PKEY_Document_Security, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 19);
-
-//  Name:     System.Document.SlideCount -- PKEY_Document_SlideCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 7 (PIDDSI_SLIDECOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_SlideCount, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 7);
-
-//  Name:     System.Document.Template -- PKEY_Document_Template
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 7 (PIDSI_TEMPLATE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_Template, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 7);
-
-//  Name:     System.Document.TotalEditingTime -- PKEY_Document_TotalEditingTime
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 10 (PIDSI_EDITTIME)
-//
-//  100ns units, not milliseconds. VT_FILETIME for IPropertySetStorage handlers (legacy)
-DEFINE_PROPERTYKEY(PKEY_Document_TotalEditingTime, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 10);
-
-//  Name:     System.Document.Version -- PKEY_Document_Version
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DocumentSummaryInformation) D5CDD502-2E9C-101B-9397-08002B2CF9AE, 29
-DEFINE_PROPERTYKEY(PKEY_Document_Version, 0xD5CDD502, 0x2E9C, 0x101B, 0x93, 0x97, 0x08, 0x00, 0x2B, 0x2C, 0xF9, 0xAE, 29);
-
-//  Name:     System.Document.WordCount -- PKEY_Document_WordCount
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_SummaryInformation) F29F85E0-4FF9-1068-AB91-08002B27B3D9, 15 (PIDSI_WORDCOUNT)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Document_WordCount, 0xF29F85E0, 0x4FF9, 0x1068, 0xAB, 0x91, 0x08, 0x00, 0x2B, 0x27, 0xB3, 0xD9, 15);
-
- 
- 
-//-----------------------------------------------------------------------------
-// DRM properties
-
-//  Name:     System.DRM.DatePlayExpires -- PKEY_DRM_DatePlayExpires
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_DRM) AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED, 6 (PIDDRSI_PLAYEXPIRES)
-//
-//  Indicates when play expires for digital rights management.
-DEFINE_PROPERTYKEY(PKEY_DRM_DatePlayExpires, 0xAEAC19E4, 0x89AE, 0x4508, 0xB9, 0xB7, 0xBB, 0x86, 0x7A, 0xBE, 0xE2, 0xED, 6);
-
-//  Name:     System.DRM.DatePlayStarts -- PKEY_DRM_DatePlayStarts
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_DRM) AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED, 5 (PIDDRSI_PLAYSTARTS)
-//
-//  Indicates when play starts for digital rights management.
-DEFINE_PROPERTYKEY(PKEY_DRM_DatePlayStarts, 0xAEAC19E4, 0x89AE, 0x4508, 0xB9, 0xB7, 0xBB, 0x86, 0x7A, 0xBE, 0xE2, 0xED, 5);
-
-//  Name:     System.DRM.Description -- PKEY_DRM_Description
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_DRM) AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED, 3 (PIDDRSI_DESCRIPTION)
-//
-//  Displays the description for digital rights management.
-DEFINE_PROPERTYKEY(PKEY_DRM_Description, 0xAEAC19E4, 0x89AE, 0x4508, 0xB9, 0xB7, 0xBB, 0x86, 0x7A, 0xBE, 0xE2, 0xED, 3);
-
-//  Name:     System.DRM.IsProtected -- PKEY_DRM_IsProtected
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: (FMTID_DRM) AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED, 2 (PIDDRSI_PROTECTED)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_DRM_IsProtected, 0xAEAC19E4, 0x89AE, 0x4508, 0xB9, 0xB7, 0xBB, 0x86, 0x7A, 0xBE, 0xE2, 0xED, 2);
-
-//  Name:     System.DRM.PlayCount -- PKEY_DRM_PlayCount
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_DRM) AEAC19E4-89AE-4508-B9B7-BB867ABEE2ED, 4 (PIDDRSI_PLAYCOUNT)
-//
-//  Indicates the play count for digital rights management.
-DEFINE_PROPERTYKEY(PKEY_DRM_PlayCount, 0xAEAC19E4, 0x89AE, 0x4508, 0xB9, 0xB7, 0xBB, 0x86, 0x7A, 0xBE, 0xE2, 0xED, 4);
- 
-//-----------------------------------------------------------------------------
-// GPS properties
-
-//  Name:     System.GPS.Altitude -- PKEY_GPS_Altitude
-//  Type:     Double -- VT_R8
-//  FormatID: 827EDB4F-5B73-44A7-891D-FDFFABEA35CA, 100
-//  
-//  Indicates the altitude based on the reference in PKEY_GPS_AltitudeRef.  Calculated from PKEY_GPS_AltitudeNumerator and 
-//  PKEY_GPS_AltitudeDenominator
-DEFINE_PROPERTYKEY(PKEY_GPS_Altitude, 0x827EDB4F, 0x5B73, 0x44A7, 0x89, 0x1D, 0xFD, 0xFF, 0xAB, 0xEA, 0x35, 0xCA, 100);
-
-//  Name:     System.GPS.AltitudeDenominator -- PKEY_GPS_AltitudeDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 78342DCB-E358-4145-AE9A-6BFE4E0F9F51, 100
-//
-//  Denominator of PKEY_GPS_Altitude
-DEFINE_PROPERTYKEY(PKEY_GPS_AltitudeDenominator, 0x78342DCB, 0xE358, 0x4145, 0xAE, 0x9A, 0x6B, 0xFE, 0x4E, 0x0F, 0x9F, 0x51, 100);
-
-//  Name:     System.GPS.AltitudeNumerator -- PKEY_GPS_AltitudeNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 2DAD1EB7-816D-40D3-9EC3-C9773BE2AADE, 100
-//
-//  Numerator of PKEY_GPS_Altitude
-DEFINE_PROPERTYKEY(PKEY_GPS_AltitudeNumerator, 0x2DAD1EB7, 0x816D, 0x40D3, 0x9E, 0xC3, 0xC9, 0x77, 0x3B, 0xE2, 0xAA, 0xDE, 100);
-
-//  Name:     System.GPS.AltitudeRef -- PKEY_GPS_AltitudeRef
-//  Type:     Byte -- VT_UI1
-//  FormatID: 46AC629D-75EA-4515-867F-6DC4321C5844, 100
-//
-//  Indicates the reference for the altitude property. (eg: above sea level, below sea level, absolute value)
-DEFINE_PROPERTYKEY(PKEY_GPS_AltitudeRef, 0x46AC629D, 0x75EA, 0x4515, 0x86, 0x7F, 0x6D, 0xC4, 0x32, 0x1C, 0x58, 0x44, 100);
-
-//  Name:     System.GPS.AreaInformation -- PKEY_GPS_AreaInformation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 972E333E-AC7E-49F1-8ADF-A70D07A9BCAB, 100
-//
-//  Represents the name of the GPS area
-DEFINE_PROPERTYKEY(PKEY_GPS_AreaInformation, 0x972E333E, 0xAC7E, 0x49F1, 0x8A, 0xDF, 0xA7, 0x0D, 0x07, 0xA9, 0xBC, 0xAB, 100);
-
-//  Name:     System.GPS.Date -- PKEY_GPS_Date
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 3602C812-0F3B-45F0-85AD-603468D69423, 100
-//
-//  Date and time of the GPS record
-DEFINE_PROPERTYKEY(PKEY_GPS_Date, 0x3602C812, 0x0F3B, 0x45F0, 0x85, 0xAD, 0x60, 0x34, 0x68, 0xD6, 0x94, 0x23, 100);
-
-//  Name:     System.GPS.DestBearing -- PKEY_GPS_DestBearing
-//  Type:     Double -- VT_R8
-//  FormatID: C66D4B3C-E888-47CC-B99F-9DCA3EE34DEA, 100
-//  
-//  Indicates the bearing to the destination point.  Calculated from PKEY_GPS_DestBearingNumerator and 
-//  PKEY_GPS_DestBearingDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_DestBearing, 0xC66D4B3C, 0xE888, 0x47CC, 0xB9, 0x9F, 0x9D, 0xCA, 0x3E, 0xE3, 0x4D, 0xEA, 100);
-
-//  Name:     System.GPS.DestBearingDenominator -- PKEY_GPS_DestBearingDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 7ABCF4F8-7C3F-4988-AC91-8D2C2E97ECA5, 100
-//
-//  Denominator of PKEY_GPS_DestBearing
-DEFINE_PROPERTYKEY(PKEY_GPS_DestBearingDenominator, 0x7ABCF4F8, 0x7C3F, 0x4988, 0xAC, 0x91, 0x8D, 0x2C, 0x2E, 0x97, 0xEC, 0xA5, 100);
-
-//  Name:     System.GPS.DestBearingNumerator -- PKEY_GPS_DestBearingNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: BA3B1DA9-86EE-4B5D-A2A4-A271A429F0CF, 100
-//
-//  Numerator of PKEY_GPS_DestBearing
-DEFINE_PROPERTYKEY(PKEY_GPS_DestBearingNumerator, 0xBA3B1DA9, 0x86EE, 0x4B5D, 0xA2, 0xA4, 0xA2, 0x71, 0xA4, 0x29, 0xF0, 0xCF, 100);
-
-//  Name:     System.GPS.DestBearingRef -- PKEY_GPS_DestBearingRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 9AB84393-2A0F-4B75-BB22-7279786977CB, 100
-//
-//  Indicates the reference used for the giving the bearing to the destination point.  (eg: true direction, magnetic direction)
-DEFINE_PROPERTYKEY(PKEY_GPS_DestBearingRef, 0x9AB84393, 0x2A0F, 0x4B75, 0xBB, 0x22, 0x72, 0x79, 0x78, 0x69, 0x77, 0xCB, 100);
-
-//  Name:     System.GPS.DestDistance -- PKEY_GPS_DestDistance
-//  Type:     Double -- VT_R8
-//  FormatID: A93EAE04-6804-4F24-AC81-09B266452118, 100
-//  
-//  Indicates the distance to the destination point.  Calculated from PKEY_GPS_DestDistanceNumerator and 
-//  PKEY_GPS_DestDistanceDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_DestDistance, 0xA93EAE04, 0x6804, 0x4F24, 0xAC, 0x81, 0x09, 0xB2, 0x66, 0x45, 0x21, 0x18, 100);
-
-//  Name:     System.GPS.DestDistanceDenominator -- PKEY_GPS_DestDistanceDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 9BC2C99B-AC71-4127-9D1C-2596D0D7DCB7, 100
-//
-//  Denominator of PKEY_GPS_DestDistance
-DEFINE_PROPERTYKEY(PKEY_GPS_DestDistanceDenominator, 0x9BC2C99B, 0xAC71, 0x4127, 0x9D, 0x1C, 0x25, 0x96, 0xD0, 0xD7, 0xDC, 0xB7, 100);
-
-//  Name:     System.GPS.DestDistanceNumerator -- PKEY_GPS_DestDistanceNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 2BDA47DA-08C6-4FE1-80BC-A72FC517C5D0, 100
-//
-//  Numerator of PKEY_GPS_DestDistance
-DEFINE_PROPERTYKEY(PKEY_GPS_DestDistanceNumerator, 0x2BDA47DA, 0x08C6, 0x4FE1, 0x80, 0xBC, 0xA7, 0x2F, 0xC5, 0x17, 0xC5, 0xD0, 100);
-
-//  Name:     System.GPS.DestDistanceRef -- PKEY_GPS_DestDistanceRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: ED4DF2D3-8695-450B-856F-F5C1C53ACB66, 100
-//
-//  Indicates the unit used to express the distance to the destination.  (eg: kilometers, miles, knots)
-DEFINE_PROPERTYKEY(PKEY_GPS_DestDistanceRef, 0xED4DF2D3, 0x8695, 0x450B, 0x85, 0x6F, 0xF5, 0xC1, 0xC5, 0x3A, 0xCB, 0x66, 100);
-
-//  Name:     System.GPS.DestLatitude -- PKEY_GPS_DestLatitude
-//  Type:     Multivalue Double -- VT_VECTOR | VT_R8  (For variants: VT_ARRAY | VT_R8)
-//  FormatID: 9D1D7CC5-5C39-451C-86B3-928E2D18CC47, 100
-//  
-//  Indicates the latitude of the destination point.  This is an array of three values.  Index 0 is the degrees, index 1 
-//  is the minutes, index 2 is the seconds.  Each is calculated from the values in PKEY_GPS_DestLatitudeNumerator and 
-//  PKEY_GPS_DestLatitudeDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLatitude, 0x9D1D7CC5, 0x5C39, 0x451C, 0x86, 0xB3, 0x92, 0x8E, 0x2D, 0x18, 0xCC, 0x47, 100);
-
-//  Name:     System.GPS.DestLatitudeDenominator -- PKEY_GPS_DestLatitudeDenominator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: 3A372292-7FCA-49A7-99D5-E47BB2D4E7AB, 100
-//
-//  Denominator of PKEY_GPS_DestLatitude
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLatitudeDenominator, 0x3A372292, 0x7FCA, 0x49A7, 0x99, 0xD5, 0xE4, 0x7B, 0xB2, 0xD4, 0xE7, 0xAB, 100);
-
-//  Name:     System.GPS.DestLatitudeNumerator -- PKEY_GPS_DestLatitudeNumerator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: ECF4B6F6-D5A6-433C-BB92-4076650FC890, 100
-//
-//  Numerator of PKEY_GPS_DestLatitude
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLatitudeNumerator, 0xECF4B6F6, 0xD5A6, 0x433C, 0xBB, 0x92, 0x40, 0x76, 0x65, 0x0F, 0xC8, 0x90, 100);
-
-//  Name:     System.GPS.DestLatitudeRef -- PKEY_GPS_DestLatitudeRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CEA820B9-CE61-4885-A128-005D9087C192, 100
-//
-//  Indicates whether the latitude destination point is north or south latitude
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLatitudeRef, 0xCEA820B9, 0xCE61, 0x4885, 0xA1, 0x28, 0x00, 0x5D, 0x90, 0x87, 0xC1, 0x92, 100);
-
-//  Name:     System.GPS.DestLongitude -- PKEY_GPS_DestLongitude
-//  Type:     Multivalue Double -- VT_VECTOR | VT_R8  (For variants: VT_ARRAY | VT_R8)
-//  FormatID: 47A96261-CB4C-4807-8AD3-40B9D9DBC6BC, 100
-//  
-//  Indicates the latitude of the destination point.  This is an array of three values.  Index 0 is the degrees, index 1 
-//  is the minutes, index 2 is the seconds.  Each is calculated from the values in PKEY_GPS_DestLongitudeNumerator and 
-//  PKEY_GPS_DestLongitudeDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLongitude, 0x47A96261, 0xCB4C, 0x4807, 0x8A, 0xD3, 0x40, 0xB9, 0xD9, 0xDB, 0xC6, 0xBC, 100);
-
-//  Name:     System.GPS.DestLongitudeDenominator -- PKEY_GPS_DestLongitudeDenominator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: 425D69E5-48AD-4900-8D80-6EB6B8D0AC86, 100
-//
-//  Denominator of PKEY_GPS_DestLongitude
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLongitudeDenominator, 0x425D69E5, 0x48AD, 0x4900, 0x8D, 0x80, 0x6E, 0xB6, 0xB8, 0xD0, 0xAC, 0x86, 100);
-
-//  Name:     System.GPS.DestLongitudeNumerator -- PKEY_GPS_DestLongitudeNumerator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: A3250282-FB6D-48D5-9A89-DBCACE75CCCF, 100
-//
-//  Numerator of PKEY_GPS_DestLongitude
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLongitudeNumerator, 0xA3250282, 0xFB6D, 0x48D5, 0x9A, 0x89, 0xDB, 0xCA, 0xCE, 0x75, 0xCC, 0xCF, 100);
-
-//  Name:     System.GPS.DestLongitudeRef -- PKEY_GPS_DestLongitudeRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 182C1EA6-7C1C-4083-AB4B-AC6C9F4ED128, 100
-//
-//  Indicates whether the longitude destination point is east or west longitude
-DEFINE_PROPERTYKEY(PKEY_GPS_DestLongitudeRef, 0x182C1EA6, 0x7C1C, 0x4083, 0xAB, 0x4B, 0xAC, 0x6C, 0x9F, 0x4E, 0xD1, 0x28, 100);
-
-//  Name:     System.GPS.Differential -- PKEY_GPS_Differential
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: AAF4EE25-BD3B-4DD7-BFC4-47F77BB00F6D, 100
-//
-//  Indicates whether differential correction was applied to the GPS receiver
-DEFINE_PROPERTYKEY(PKEY_GPS_Differential, 0xAAF4EE25, 0xBD3B, 0x4DD7, 0xBF, 0xC4, 0x47, 0xF7, 0x7B, 0xB0, 0x0F, 0x6D, 100);
-
-//  Name:     System.GPS.DOP -- PKEY_GPS_DOP
-//  Type:     Double -- VT_R8
-//  FormatID: 0CF8FB02-1837-42F1-A697-A7017AA289B9, 100
-//
-//  Indicates the GPS DOP (data degree of precision).  Calculated from PKEY_GPS_DOPNumerator and PKEY_GPS_DOPDenominator
-DEFINE_PROPERTYKEY(PKEY_GPS_DOP, 0x0CF8FB02, 0x1837, 0x42F1, 0xA6, 0x97, 0xA7, 0x01, 0x7A, 0xA2, 0x89, 0xB9, 100);
-
-//  Name:     System.GPS.DOPDenominator -- PKEY_GPS_DOPDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: A0BE94C5-50BA-487B-BD35-0654BE8881ED, 100
-//
-//  Denominator of PKEY_GPS_DOP
-DEFINE_PROPERTYKEY(PKEY_GPS_DOPDenominator, 0xA0BE94C5, 0x50BA, 0x487B, 0xBD, 0x35, 0x06, 0x54, 0xBE, 0x88, 0x81, 0xED, 100);
-
-//  Name:     System.GPS.DOPNumerator -- PKEY_GPS_DOPNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 47166B16-364F-4AA0-9F31-E2AB3DF449C3, 100
-//
-//  Numerator of PKEY_GPS_DOP
-DEFINE_PROPERTYKEY(PKEY_GPS_DOPNumerator, 0x47166B16, 0x364F, 0x4AA0, 0x9F, 0x31, 0xE2, 0xAB, 0x3D, 0xF4, 0x49, 0xC3, 100);
-
-//  Name:     System.GPS.ImgDirection -- PKEY_GPS_ImgDirection
-//  Type:     Double -- VT_R8
-//  FormatID: 16473C91-D017-4ED9-BA4D-B6BAA55DBCF8, 100
-//  
-//  Indicates direction of the image when it was captured.  Calculated from PKEY_GPS_ImgDirectionNumerator and 
-//  PKEY_GPS_ImgDirectionDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_ImgDirection, 0x16473C91, 0xD017, 0x4ED9, 0xBA, 0x4D, 0xB6, 0xBA, 0xA5, 0x5D, 0xBC, 0xF8, 100);
-
-//  Name:     System.GPS.ImgDirectionDenominator -- PKEY_GPS_ImgDirectionDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 10B24595-41A2-4E20-93C2-5761C1395F32, 100
-//
-//  Denominator of PKEY_GPS_ImgDirection
-DEFINE_PROPERTYKEY(PKEY_GPS_ImgDirectionDenominator, 0x10B24595, 0x41A2, 0x4E20, 0x93, 0xC2, 0x57, 0x61, 0xC1, 0x39, 0x5F, 0x32, 100);
-
-//  Name:     System.GPS.ImgDirectionNumerator -- PKEY_GPS_ImgDirectionNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: DC5877C7-225F-45F7-BAC7-E81334B6130A, 100
-//
-//  Numerator of PKEY_GPS_ImgDirection
-DEFINE_PROPERTYKEY(PKEY_GPS_ImgDirectionNumerator, 0xDC5877C7, 0x225F, 0x45F7, 0xBA, 0xC7, 0xE8, 0x13, 0x34, 0xB6, 0x13, 0x0A, 100);
-
-//  Name:     System.GPS.ImgDirectionRef -- PKEY_GPS_ImgDirectionRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A4AAA5B7-1AD0-445F-811A-0F8F6E67F6B5, 100
-//
-//  Indicates reference for giving the direction of the image when it was captured.  (eg: true direction, magnetic direction)
-DEFINE_PROPERTYKEY(PKEY_GPS_ImgDirectionRef, 0xA4AAA5B7, 0x1AD0, 0x445F, 0x81, 0x1A, 0x0F, 0x8F, 0x6E, 0x67, 0xF6, 0xB5, 100);
-
-//  Name:     System.GPS.Latitude -- PKEY_GPS_Latitude
-//  Type:     Multivalue Double -- VT_VECTOR | VT_R8  (For variants: VT_ARRAY | VT_R8)
-//  FormatID: 8727CFFF-4868-4EC6-AD5B-81B98521D1AB, 100
-//  
-//  Indicates the latitude.  This is an array of three values.  Index 0 is the degrees, index 1 is the minutes, index 2 
-//  is the seconds.  Each is calculated from the values in PKEY_GPS_LatitudeNumerator and PKEY_GPS_LatitudeDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_Latitude, 0x8727CFFF, 0x4868, 0x4EC6, 0xAD, 0x5B, 0x81, 0xB9, 0x85, 0x21, 0xD1, 0xAB, 100);
-
-//  Name:     System.GPS.LatitudeDenominator -- PKEY_GPS_LatitudeDenominator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: 16E634EE-2BFF-497B-BD8A-4341AD39EEB9, 100
-//
-//  Denominator of PKEY_GPS_Latitude
-DEFINE_PROPERTYKEY(PKEY_GPS_LatitudeDenominator, 0x16E634EE, 0x2BFF, 0x497B, 0xBD, 0x8A, 0x43, 0x41, 0xAD, 0x39, 0xEE, 0xB9, 100);
-
-//  Name:     System.GPS.LatitudeNumerator -- PKEY_GPS_LatitudeNumerator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: 7DDAAAD1-CCC8-41AE-B750-B2CB8031AEA2, 100
-//
-//  Numerator of PKEY_GPS_Latitude
-DEFINE_PROPERTYKEY(PKEY_GPS_LatitudeNumerator, 0x7DDAAAD1, 0xCCC8, 0x41AE, 0xB7, 0x50, 0xB2, 0xCB, 0x80, 0x31, 0xAE, 0xA2, 100);
-
-//  Name:     System.GPS.LatitudeRef -- PKEY_GPS_LatitudeRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 029C0252-5B86-46C7-ACA0-2769FFC8E3D4, 100
-//
-//  Indicates whether latitude is north or south latitude 
-DEFINE_PROPERTYKEY(PKEY_GPS_LatitudeRef, 0x029C0252, 0x5B86, 0x46C7, 0xAC, 0xA0, 0x27, 0x69, 0xFF, 0xC8, 0xE3, 0xD4, 100);
-
-//  Name:     System.GPS.Longitude -- PKEY_GPS_Longitude
-//  Type:     Multivalue Double -- VT_VECTOR | VT_R8  (For variants: VT_ARRAY | VT_R8)
-//  FormatID: C4C4DBB2-B593-466B-BBDA-D03D27D5E43A, 100
-//  
-//  Indicates the longitude.  This is an array of three values.  Index 0 is the degrees, index 1 is the minutes, index 2 
-//  is the seconds.  Each is calculated from the values in PKEY_GPS_LongitudeNumerator and PKEY_GPS_LongitudeDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_Longitude, 0xC4C4DBB2, 0xB593, 0x466B, 0xBB, 0xDA, 0xD0, 0x3D, 0x27, 0xD5, 0xE4, 0x3A, 100);
-
-//  Name:     System.GPS.LongitudeDenominator -- PKEY_GPS_LongitudeDenominator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: BE6E176C-4534-4D2C-ACE5-31DEDAC1606B, 100
-//
-//  Denominator of PKEY_GPS_Longitude
-DEFINE_PROPERTYKEY(PKEY_GPS_LongitudeDenominator, 0xBE6E176C, 0x4534, 0x4D2C, 0xAC, 0xE5, 0x31, 0xDE, 0xDA, 0xC1, 0x60, 0x6B, 100);
-
-//  Name:     System.GPS.LongitudeNumerator -- PKEY_GPS_LongitudeNumerator
-//  Type:     Multivalue UInt32 -- VT_VECTOR | VT_UI4  (For variants: VT_ARRAY | VT_UI4)
-//  FormatID: 02B0F689-A914-4E45-821D-1DDA452ED2C4, 100
-//
-//  Numerator of PKEY_GPS_Longitude
-DEFINE_PROPERTYKEY(PKEY_GPS_LongitudeNumerator, 0x02B0F689, 0xA914, 0x4E45, 0x82, 0x1D, 0x1D, 0xDA, 0x45, 0x2E, 0xD2, 0xC4, 100);
-
-//  Name:     System.GPS.LongitudeRef -- PKEY_GPS_LongitudeRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 33DCF22B-28D5-464C-8035-1EE9EFD25278, 100
-//
-//  Indicates whether longitude is east or west longitude
-DEFINE_PROPERTYKEY(PKEY_GPS_LongitudeRef, 0x33DCF22B, 0x28D5, 0x464C, 0x80, 0x35, 0x1E, 0xE9, 0xEF, 0xD2, 0x52, 0x78, 100);
-
-//  Name:     System.GPS.MapDatum -- PKEY_GPS_MapDatum
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 2CA2DAE6-EDDC-407D-BEF1-773942ABFA95, 100
-//
-//  Indicates the geodetic survey data used by the GPS receiver
-DEFINE_PROPERTYKEY(PKEY_GPS_MapDatum, 0x2CA2DAE6, 0xEDDC, 0x407D, 0xBE, 0xF1, 0x77, 0x39, 0x42, 0xAB, 0xFA, 0x95, 100);
-
-//  Name:     System.GPS.MeasureMode -- PKEY_GPS_MeasureMode
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A015ED5D-AAEA-4D58-8A86-3C586920EA0B, 100
-//
-//  Indicates the GPS measurement mode.  (eg: 2-dimensional, 3-dimensional)
-DEFINE_PROPERTYKEY(PKEY_GPS_MeasureMode, 0xA015ED5D, 0xAAEA, 0x4D58, 0x8A, 0x86, 0x3C, 0x58, 0x69, 0x20, 0xEA, 0x0B, 100);
-
-//  Name:     System.GPS.ProcessingMethod -- PKEY_GPS_ProcessingMethod
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 59D49E61-840F-4AA9-A939-E2099B7F6399, 100
-//
-//  Indicates the name of the method used for location finding
-DEFINE_PROPERTYKEY(PKEY_GPS_ProcessingMethod, 0x59D49E61, 0x840F, 0x4AA9, 0xA9, 0x39, 0xE2, 0x09, 0x9B, 0x7F, 0x63, 0x99, 100);
-
-//  Name:     System.GPS.Satellites -- PKEY_GPS_Satellites
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 467EE575-1F25-4557-AD4E-B8B58B0D9C15, 100
-//
-//  Indicates the GPS satellites used for measurements
-DEFINE_PROPERTYKEY(PKEY_GPS_Satellites, 0x467EE575, 0x1F25, 0x4557, 0xAD, 0x4E, 0xB8, 0xB5, 0x8B, 0x0D, 0x9C, 0x15, 100);
-
-//  Name:     System.GPS.Speed -- PKEY_GPS_Speed
-//  Type:     Double -- VT_R8
-//  FormatID: DA5D0862-6E76-4E1B-BABD-70021BD25494, 100
-//  
-//  Indicates the speed of the GPS receiver movement.  Calculated from PKEY_GPS_SpeedNumerator and 
-//  PKEY_GPS_SpeedDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_Speed, 0xDA5D0862, 0x6E76, 0x4E1B, 0xBA, 0xBD, 0x70, 0x02, 0x1B, 0xD2, 0x54, 0x94, 100);
-
-//  Name:     System.GPS.SpeedDenominator -- PKEY_GPS_SpeedDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 7D122D5A-AE5E-4335-8841-D71E7CE72F53, 100
-//
-//  Denominator of PKEY_GPS_Speed
-DEFINE_PROPERTYKEY(PKEY_GPS_SpeedDenominator, 0x7D122D5A, 0xAE5E, 0x4335, 0x88, 0x41, 0xD7, 0x1E, 0x7C, 0xE7, 0x2F, 0x53, 100);
-
-//  Name:     System.GPS.SpeedNumerator -- PKEY_GPS_SpeedNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: ACC9CE3D-C213-4942-8B48-6D0820F21C6D, 100
-//
-//  Numerator of PKEY_GPS_Speed
-DEFINE_PROPERTYKEY(PKEY_GPS_SpeedNumerator, 0xACC9CE3D, 0xC213, 0x4942, 0x8B, 0x48, 0x6D, 0x08, 0x20, 0xF2, 0x1C, 0x6D, 100);
-
-//  Name:     System.GPS.SpeedRef -- PKEY_GPS_SpeedRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: ECF7F4C9-544F-4D6D-9D98-8AD79ADAF453, 100
-//  
-//  Indicates the unit used to express the speed of the GPS receiver movement.  (eg: kilometers per hour, 
-//  miles per hour, knots).
-DEFINE_PROPERTYKEY(PKEY_GPS_SpeedRef, 0xECF7F4C9, 0x544F, 0x4D6D, 0x9D, 0x98, 0x8A, 0xD7, 0x9A, 0xDA, 0xF4, 0x53, 100);
-
-//  Name:     System.GPS.Status -- PKEY_GPS_Status
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 125491F4-818F-46B2-91B5-D537753617B2, 100
-//  
-//  Indicates the status of the GPS receiver when the image was recorded.  (eg: measurement in progress, 
-//  measurement interoperability).
-DEFINE_PROPERTYKEY(PKEY_GPS_Status, 0x125491F4, 0x818F, 0x46B2, 0x91, 0xB5, 0xD5, 0x37, 0x75, 0x36, 0x17, 0xB2, 100);
-
-//  Name:     System.GPS.Track -- PKEY_GPS_Track
-//  Type:     Double -- VT_R8
-//  FormatID: 76C09943-7C33-49E3-9E7E-CDBA872CFADA, 100
-//  
-//  Indicates the direction of the GPS receiver movement.  Calculated from PKEY_GPS_TrackNumerator and 
-//  PKEY_GPS_TrackDenominator.
-DEFINE_PROPERTYKEY(PKEY_GPS_Track, 0x76C09943, 0x7C33, 0x49E3, 0x9E, 0x7E, 0xCD, 0xBA, 0x87, 0x2C, 0xFA, 0xDA, 100);
-
-//  Name:     System.GPS.TrackDenominator -- PKEY_GPS_TrackDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: C8D1920C-01F6-40C0-AC86-2F3A4AD00770, 100
-//
-//  Denominator of PKEY_GPS_Track
-DEFINE_PROPERTYKEY(PKEY_GPS_TrackDenominator, 0xC8D1920C, 0x01F6, 0x40C0, 0xAC, 0x86, 0x2F, 0x3A, 0x4A, 0xD0, 0x07, 0x70, 100);
-
-//  Name:     System.GPS.TrackNumerator -- PKEY_GPS_TrackNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 702926F4-44A6-43E1-AE71-45627116893B, 100
-//
-//  Numerator of PKEY_GPS_Track
-DEFINE_PROPERTYKEY(PKEY_GPS_TrackNumerator, 0x702926F4, 0x44A6, 0x43E1, 0xAE, 0x71, 0x45, 0x62, 0x71, 0x16, 0x89, 0x3B, 100);
-
-//  Name:     System.GPS.TrackRef -- PKEY_GPS_TrackRef
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 35DBE6FE-44C3-4400-AAAE-D2C799C407E8, 100
-//
-//  Indicates reference for the direction of the GPS receiver movement.  (eg: true direction, magnetic direction)
-DEFINE_PROPERTYKEY(PKEY_GPS_TrackRef, 0x35DBE6FE, 0x44C3, 0x4400, 0xAA, 0xAE, 0xD2, 0xC7, 0x99, 0xC4, 0x07, 0xE8, 100);
-
-//  Name:     System.GPS.VersionID -- PKEY_GPS_VersionID
-//  Type:     Buffer -- VT_VECTOR | VT_UI1  (For variants: VT_ARRAY | VT_UI1)
-//  FormatID: 22704DA4-C6B2-4A99-8E56-F16DF8C92599, 100
-//
-//  Indicates the version of the GPS information
-DEFINE_PROPERTYKEY(PKEY_GPS_VersionID, 0x22704DA4, 0xC6B2, 0x4A99, 0x8E, 0x56, 0xF1, 0x6D, 0xF8, 0xC9, 0x25, 0x99, 100);
- 
-//-----------------------------------------------------------------------------
-// Image properties
-
-
-
-//  Name:     System.Image.BitDepth -- PKEY_Image_BitDepth
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 7 (PIDISI_BITDEPTH)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Image_BitDepth, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 7);
-
-//  Name:     System.Image.ColorSpace -- PKEY_Image_ColorSpace
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 40961
-//
-//  PropertyTagExifColorSpace
-DEFINE_PROPERTYKEY(PKEY_Image_ColorSpace, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 40961);
-
-// Possible discrete values for PKEY_Image_ColorSpace are:
-#define IMAGE_COLORSPACE_SRGB               1u
-#define IMAGE_COLORSPACE_UNCALIBRATED       0xFFFFu
-
-//  Name:     System.Image.CompressedBitsPerPixel -- PKEY_Image_CompressedBitsPerPixel
-//  Type:     Double -- VT_R8
-//  FormatID: 364B6FA9-37AB-482A-BE2B-AE02F60D4318, 100
-//
-//  Calculated from PKEY_Image_CompressedBitsPerPixelNumerator and PKEY_Image_CompressedBitsPerPixelDenominator.
-DEFINE_PROPERTYKEY(PKEY_Image_CompressedBitsPerPixel, 0x364B6FA9, 0x37AB, 0x482A, 0xBE, 0x2B, 0xAE, 0x02, 0xF6, 0x0D, 0x43, 0x18, 100);
-
-//  Name:     System.Image.CompressedBitsPerPixelDenominator -- PKEY_Image_CompressedBitsPerPixelDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 1F8844E1-24AD-4508-9DFD-5326A415CE02, 100
-//
-//  Denominator of PKEY_Image_CompressedBitsPerPixel.
-DEFINE_PROPERTYKEY(PKEY_Image_CompressedBitsPerPixelDenominator, 0x1F8844E1, 0x24AD, 0x4508, 0x9D, 0xFD, 0x53, 0x26, 0xA4, 0x15, 0xCE, 0x02, 100);
-
-//  Name:     System.Image.CompressedBitsPerPixelNumerator -- PKEY_Image_CompressedBitsPerPixelNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: D21A7148-D32C-4624-8900-277210F79C0F, 100
-//
-//  Numerator of PKEY_Image_CompressedBitsPerPixel.
-DEFINE_PROPERTYKEY(PKEY_Image_CompressedBitsPerPixelNumerator, 0xD21A7148, 0xD32C, 0x4624, 0x89, 0x00, 0x27, 0x72, 0x10, 0xF7, 0x9C, 0x0F, 100);
-
-//  Name:     System.Image.Compression -- PKEY_Image_Compression
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 259
-//
-//  Indicates the image compression level.  PropertyTagCompression.
-DEFINE_PROPERTYKEY(PKEY_Image_Compression, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 259);
-
-// Possible discrete values for PKEY_Image_Compression are:
-#define IMAGE_COMPRESSION_UNCOMPRESSED      1u
-#define IMAGE_COMPRESSION_CCITT_T3          2u
-#define IMAGE_COMPRESSION_CCITT_T4          3u
-#define IMAGE_COMPRESSION_CCITT_T6          4u
-#define IMAGE_COMPRESSION_LZW               5u
-#define IMAGE_COMPRESSION_JPEG              6u
-#define IMAGE_COMPRESSION_PACKBITS          32773u
-
-//  Name:     System.Image.CompressionText -- PKEY_Image_CompressionText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 3F08E66F-2F44-4BB9-A682-AC35D2562322, 100
-//  
-//  This is the user-friendly form of System.Image.Compression.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Image_CompressionText, 0x3F08E66F, 0x2F44, 0x4BB9, 0xA6, 0x82, 0xAC, 0x35, 0xD2, 0x56, 0x23, 0x22, 100);
-
-//  Name:     System.Image.Dimensions -- PKEY_Image_Dimensions
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 13 (PIDISI_DIMENSIONS)
-//
-//  Indicates the dimensions of the image.
-DEFINE_PROPERTYKEY(PKEY_Image_Dimensions, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 13);
-
-//  Name:     System.Image.HorizontalResolution -- PKEY_Image_HorizontalResolution
-//  Type:     Double -- VT_R8
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 5 (PIDISI_RESOLUTIONX)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Image_HorizontalResolution, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 5);
-
-//  Name:     System.Image.HorizontalSize -- PKEY_Image_HorizontalSize
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 3 (PIDISI_CX)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Image_HorizontalSize, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 3);
-
-//  Name:     System.Image.ImageID -- PKEY_Image_ImageID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 10DABE05-32AA-4C29-BF1A-63E2D220587F, 100
-DEFINE_PROPERTYKEY(PKEY_Image_ImageID, 0x10DABE05, 0x32AA, 0x4C29, 0xBF, 0x1A, 0x63, 0xE2, 0xD2, 0x20, 0x58, 0x7F, 100);
-
-//  Name:     System.Image.ResolutionUnit -- PKEY_Image_ResolutionUnit
-//  Type:     Int16 -- VT_I2
-//  FormatID: 19B51FA6-1F92-4A5C-AB48-7DF0ABD67444, 100
-DEFINE_PROPERTYKEY(PKEY_Image_ResolutionUnit, 0x19B51FA6, 0x1F92, 0x4A5C, 0xAB, 0x48, 0x7D, 0xF0, 0xAB, 0xD6, 0x74, 0x44, 100);
-
-//  Name:     System.Image.VerticalResolution -- PKEY_Image_VerticalResolution
-//  Type:     Double -- VT_R8
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 6 (PIDISI_RESOLUTIONY)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Image_VerticalResolution, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 6);
-
-//  Name:     System.Image.VerticalSize -- PKEY_Image_VerticalSize
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 4 (PIDISI_CY)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Image_VerticalSize, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 4);
-
- 
- 
-//-----------------------------------------------------------------------------
-// Journal properties
-
-//  Name:     System.Journal.Contacts -- PKEY_Journal_Contacts
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: DEA7C82C-1D89-4A66-9427-A4E3DEBABCB1, 100
-DEFINE_PROPERTYKEY(PKEY_Journal_Contacts, 0xDEA7C82C, 0x1D89, 0x4A66, 0x94, 0x27, 0xA4, 0xE3, 0xDE, 0xBA, 0xBC, 0xB1, 100);
-
-//  Name:     System.Journal.EntryType -- PKEY_Journal_EntryType
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 95BEB1FC-326D-4644-B396-CD3ED90E6DDF, 100
-DEFINE_PROPERTYKEY(PKEY_Journal_EntryType, 0x95BEB1FC, 0x326D, 0x4644, 0xB3, 0x96, 0xCD, 0x3E, 0xD9, 0x0E, 0x6D, 0xDF, 100);
- 
-//-----------------------------------------------------------------------------
-// Link properties
-
-
-
-//  Name:     System.Link.Comment -- PKEY_Link_Comment
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_LINK) B9B4B3FC-2B51-4A42-B5D8-324146AFCF25, 5
-DEFINE_PROPERTYKEY(PKEY_Link_Comment, 0xB9B4B3FC, 0x2B51, 0x4A42, 0xB5, 0xD8, 0x32, 0x41, 0x46, 0xAF, 0xCF, 0x25, 5);
-
-//  Name:     System.Link.DateVisited -- PKEY_Link_DateVisited
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 5CBF2787-48CF-4208-B90E-EE5E5D420294, 23  (PKEYs relating to URLs.  Used by IE History.)
-DEFINE_PROPERTYKEY(PKEY_Link_DateVisited, 0x5CBF2787, 0x48CF, 0x4208, 0xB9, 0x0E, 0xEE, 0x5E, 0x5D, 0x42, 0x02, 0x94, 23);
-
-//  Name:     System.Link.Description -- PKEY_Link_Description
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 5CBF2787-48CF-4208-B90E-EE5E5D420294, 21  (PKEYs relating to URLs.  Used by IE History.)
-DEFINE_PROPERTYKEY(PKEY_Link_Description, 0x5CBF2787, 0x48CF, 0x4208, 0xB9, 0x0E, 0xEE, 0x5E, 0x5D, 0x42, 0x02, 0x94, 21);
-
-//  Name:     System.Link.Status -- PKEY_Link_Status
-//  Type:     Int32 -- VT_I4
-//  FormatID: (PSGUID_LINK) B9B4B3FC-2B51-4A42-B5D8-324146AFCF25, 3 (PID_LINK_TARGET_TYPE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Link_Status, 0xB9B4B3FC, 0x2B51, 0x4A42, 0xB5, 0xD8, 0x32, 0x41, 0x46, 0xAF, 0xCF, 0x25, 3);
-
-// Possible discrete values for PKEY_Link_Status are:
-#define LINK_STATUS_RESOLVED                1l
-#define LINK_STATUS_BROKEN                  2l
-
-//  Name:     System.Link.TargetExtension -- PKEY_Link_TargetExtension
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: 7A7D76F4-B630-4BD7-95FF-37CC51A975C9, 2
-//
-//  The file extension of the link target.  See System.File.Extension
-DEFINE_PROPERTYKEY(PKEY_Link_TargetExtension, 0x7A7D76F4, 0xB630, 0x4BD7, 0x95, 0xFF, 0x37, 0xCC, 0x51, 0xA9, 0x75, 0xC9, 2);
-
-//  Name:     System.Link.TargetParsingPath -- PKEY_Link_TargetParsingPath
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_LINK) B9B4B3FC-2B51-4A42-B5D8-324146AFCF25, 2 (PID_LINK_TARGET)
-//  
-//  This is the shell namespace path to the target of the link item.  This path may be passed to 
-//  SHParseDisplayName to parse the path to the correct shell folder.
-//  
-//  If the target item is a file, the value is identical to System.ItemPathDisplay.
-//  
-//  If the target item cannot be accessed through the shell namespace, this value is VT_EMPTY.
-DEFINE_PROPERTYKEY(PKEY_Link_TargetParsingPath, 0xB9B4B3FC, 0x2B51, 0x4A42, 0xB5, 0xD8, 0x32, 0x41, 0x46, 0xAF, 0xCF, 0x25, 2);
-
-//  Name:     System.Link.TargetSFGAOFlags -- PKEY_Link_TargetSFGAOFlags
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_LINK) B9B4B3FC-2B51-4A42-B5D8-324146AFCF25, 8
-//  
-//  IShellFolder::GetAttributesOf flags for the target of a link, with SFGAO_PKEYSFGAOMASK 
-//  attributes masked out.
-DEFINE_PROPERTYKEY(PKEY_Link_TargetSFGAOFlags, 0xB9B4B3FC, 0x2B51, 0x4A42, 0xB5, 0xD8, 0x32, 0x41, 0x46, 0xAF, 0xCF, 0x25, 8);
- 
-//-----------------------------------------------------------------------------
-// Media properties
-
-
-
-//  Name:     System.Media.AuthorUrl -- PKEY_Media_AuthorUrl
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 32 (PIDMSI_AUTHOR_URL)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_AuthorUrl, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 32);
-
-//  Name:     System.Media.AverageLevel -- PKEY_Media_AverageLevel
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 09EDD5B6-B301-43C5-9990-D00302EFFD46, 100
-DEFINE_PROPERTYKEY(PKEY_Media_AverageLevel, 0x09EDD5B6, 0xB301, 0x43C5, 0x99, 0x90, 0xD0, 0x03, 0x02, 0xEF, 0xFD, 0x46, 100);
-
-//  Name:     System.Media.ClassPrimaryID -- PKEY_Media_ClassPrimaryID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 13 (PIDMSI_CLASS_PRIMARY_ID)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_ClassPrimaryID, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 13);
-
-//  Name:     System.Media.ClassSecondaryID -- PKEY_Media_ClassSecondaryID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 14 (PIDMSI_CLASS_SECONDARY_ID)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_ClassSecondaryID, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 14);
-
-//  Name:     System.Media.CollectionGroupID -- PKEY_Media_CollectionGroupID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 24 (PIDMSI_COLLECTION_GROUP_ID)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_CollectionGroupID, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 24);
-
-//  Name:     System.Media.CollectionID -- PKEY_Media_CollectionID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 25 (PIDMSI_COLLECTION_ID)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_CollectionID, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 25);
-
-//  Name:     System.Media.ContentDistributor -- PKEY_Media_ContentDistributor
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 18 (PIDMSI_CONTENTDISTRIBUTOR)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_ContentDistributor, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 18);
-
-//  Name:     System.Media.ContentID -- PKEY_Media_ContentID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 26 (PIDMSI_CONTENT_ID)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_ContentID, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 26);
-
-//  Name:     System.Media.CreatorApplication -- PKEY_Media_CreatorApplication
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 27 (PIDMSI_TOOL_NAME)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_CreatorApplication, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 27);
-
-//  Name:     System.Media.CreatorApplicationVersion -- PKEY_Media_CreatorApplicationVersion
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 28 (PIDMSI_TOOL_VERSION)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_CreatorApplicationVersion, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 28);
-
-//  Name:     System.Media.DateEncoded -- PKEY_Media_DateEncoded
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 2E4B640D-5019-46D8-8881-55414CC5CAA0, 100
-//
-//  DateTime is in UTC (in the doc, not file system).
-DEFINE_PROPERTYKEY(PKEY_Media_DateEncoded, 0x2E4B640D, 0x5019, 0x46D8, 0x88, 0x81, 0x55, 0x41, 0x4C, 0xC5, 0xCA, 0xA0, 100);
-
-//  Name:     System.Media.DateReleased -- PKEY_Media_DateReleased
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DE41CC29-6971-4290-B472-F59F2E2F31E2, 100
-DEFINE_PROPERTYKEY(PKEY_Media_DateReleased, 0xDE41CC29, 0x6971, 0x4290, 0xB4, 0x72, 0xF5, 0x9F, 0x2E, 0x2F, 0x31, 0xE2, 100);
-
-//  Name:     System.Media.Duration -- PKEY_Media_Duration
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: (FMTID_AudioSummaryInformation) 64440490-4C8B-11D1-8B70-080036B11A03, 3 (PIDASI_TIMELENGTH)
-//
-//  100ns units, not milliseconds
-DEFINE_PROPERTYKEY(PKEY_Media_Duration, 0x64440490, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 3);
-
-//  Name:     System.Media.DVDID -- PKEY_Media_DVDID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 15 (PIDMSI_DVDID)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_DVDID, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 15);
-
-//  Name:     System.Media.EncodedBy -- PKEY_Media_EncodedBy
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 36 (PIDMSI_ENCODED_BY)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_EncodedBy, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 36);
-
-//  Name:     System.Media.EncodingSettings -- PKEY_Media_EncodingSettings
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 37 (PIDMSI_ENCODING_SETTINGS)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_EncodingSettings, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 37);
-
-//  Name:     System.Media.FrameCount -- PKEY_Media_FrameCount
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (PSGUID_IMAGESUMMARYINFORMATION) 6444048F-4C8B-11D1-8B70-080036B11A03, 12 (PIDISI_FRAMECOUNT)
-//
-//  Indicates the frame count for the image.
-DEFINE_PROPERTYKEY(PKEY_Media_FrameCount, 0x6444048F, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 12);
-
-//  Name:     System.Media.MCDI -- PKEY_Media_MCDI
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 16 (PIDMSI_MCDI)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_MCDI, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 16);
-
-//  Name:     System.Media.MetadataContentProvider -- PKEY_Media_MetadataContentProvider
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 17 (PIDMSI_PROVIDER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_MetadataContentProvider, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 17);
-
-//  Name:     System.Media.Producer -- PKEY_Media_Producer
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 22 (PIDMSI_PRODUCER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_Producer, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 22);
-
-//  Name:     System.Media.PromotionUrl -- PKEY_Media_PromotionUrl
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 33 (PIDMSI_PROMOTION_URL)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_PromotionUrl, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 33);
-
-//  Name:     System.Media.ProtectionType -- PKEY_Media_ProtectionType
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 38
-//  
-//  If media is protected, how is it protected?
-DEFINE_PROPERTYKEY(PKEY_Media_ProtectionType, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 38);
-
-//  Name:     System.Media.ProviderRating -- PKEY_Media_ProviderRating
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 39
-//  
-//  Rating (0 - 99) supplied by metadata provider
-DEFINE_PROPERTYKEY(PKEY_Media_ProviderRating, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 39);
-
-//  Name:     System.Media.ProviderStyle -- PKEY_Media_ProviderStyle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 40
-//  
-//  Style of music or video, supplied by metadata provider
-DEFINE_PROPERTYKEY(PKEY_Media_ProviderStyle, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 40);
-
-//  Name:     System.Media.Publisher -- PKEY_Media_Publisher
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 30 (PIDMSI_PUBLISHER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_Publisher, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 30);
-
-//  Name:     System.Media.SubscriptionContentId -- PKEY_Media_SubscriptionContentId
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 9AEBAE7A-9644-487D-A92C-657585ED751A, 100
-DEFINE_PROPERTYKEY(PKEY_Media_SubscriptionContentId, 0x9AEBAE7A, 0x9644, 0x487D, 0xA9, 0x2C, 0x65, 0x75, 0x85, 0xED, 0x75, 0x1A, 100);
-
-//  Name:     System.Media.SubTitle -- PKEY_Media_SubTitle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 38 (PIDSI_MUSIC_SUB_TITLE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_SubTitle, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 38);
-
-//  Name:     System.Media.UniqueFileIdentifier -- PKEY_Media_UniqueFileIdentifier
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 35 (PIDMSI_UNIQUE_FILE_IDENTIFIER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_UniqueFileIdentifier, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 35);
-
-//  Name:     System.Media.UserNoAutoInfo -- PKEY_Media_UserNoAutoInfo
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 41
-//  
-//  If true, do NOT alter this file's metadata. Set by user.
-DEFINE_PROPERTYKEY(PKEY_Media_UserNoAutoInfo, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 41);
-
-//  Name:     System.Media.UserWebUrl -- PKEY_Media_UserWebUrl
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 34 (PIDMSI_USER_WEB_URL)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_UserWebUrl, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 34);
-
-//  Name:     System.Media.Writer -- PKEY_Media_Writer
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 23 (PIDMSI_WRITER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_Writer, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 23);
-
-//  Name:     System.Media.Year -- PKEY_Media_Year
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 5 (PIDSI_MUSIC_YEAR)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Media_Year, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 5);
- 
-//-----------------------------------------------------------------------------
-// Message properties
-
-
-
-//  Name:     System.Message.AttachmentContents -- PKEY_Message_AttachmentContents
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 3143BF7C-80A8-4854-8880-E2E40189BDD0, 100
-DEFINE_PROPERTYKEY(PKEY_Message_AttachmentContents, 0x3143BF7C, 0x80A8, 0x4854, 0x88, 0x80, 0xE2, 0xE4, 0x01, 0x89, 0xBD, 0xD0, 100);
-
-//  Name:     System.Message.AttachmentNames -- PKEY_Message_AttachmentNames
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 21
-//
-//  The names of the attachments in a message
-DEFINE_PROPERTYKEY(PKEY_Message_AttachmentNames, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 21);
-
-//  Name:     System.Message.BccAddress -- PKEY_Message_BccAddress
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 2
-//
-//  Addresses in Bcc: field
-DEFINE_PROPERTYKEY(PKEY_Message_BccAddress, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 2);
-
-//  Name:     System.Message.BccName -- PKEY_Message_BccName
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 3
-//
-//  person names in Bcc: field
-DEFINE_PROPERTYKEY(PKEY_Message_BccName, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 3);
-
-//  Name:     System.Message.CcAddress -- PKEY_Message_CcAddress
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 4
-//
-//  Addresses in Cc: field
-DEFINE_PROPERTYKEY(PKEY_Message_CcAddress, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 4);
-
-//  Name:     System.Message.CcName -- PKEY_Message_CcName
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 5
-//
-//  person names in Cc: field
-DEFINE_PROPERTYKEY(PKEY_Message_CcName, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 5);
-
-//  Name:     System.Message.ConversationID -- PKEY_Message_ConversationID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: DC8F80BD-AF1E-4289-85B6-3DFC1B493992, 100
-DEFINE_PROPERTYKEY(PKEY_Message_ConversationID, 0xDC8F80BD, 0xAF1E, 0x4289, 0x85, 0xB6, 0x3D, 0xFC, 0x1B, 0x49, 0x39, 0x92, 100);
-
-//  Name:     System.Message.ConversationIndex -- PKEY_Message_ConversationIndex
-//  Type:     Buffer -- VT_VECTOR | VT_UI1  (For variants: VT_ARRAY | VT_UI1)
-//  FormatID: DC8F80BD-AF1E-4289-85B6-3DFC1B493992, 101
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Message_ConversationIndex, 0xDC8F80BD, 0xAF1E, 0x4289, 0x85, 0xB6, 0x3D, 0xFC, 0x1B, 0x49, 0x39, 0x92, 101);
-
-//  Name:     System.Message.DateReceived -- PKEY_Message_DateReceived
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 20
-//
-//  Date and Time communication was received
-DEFINE_PROPERTYKEY(PKEY_Message_DateReceived, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 20);
-
-//  Name:     System.Message.DateSent -- PKEY_Message_DateSent
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 19
-//
-//  Date and Time communication was sent
-DEFINE_PROPERTYKEY(PKEY_Message_DateSent, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 19);
-
-//  Name:     System.Message.FromAddress -- PKEY_Message_FromAddress
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 13
-DEFINE_PROPERTYKEY(PKEY_Message_FromAddress, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 13);
-
-//  Name:     System.Message.FromName -- PKEY_Message_FromName
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 14
-//
-//  Address in from field as person name
-DEFINE_PROPERTYKEY(PKEY_Message_FromName, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 14);
-
-//  Name:     System.Message.HasAttachments -- PKEY_Message_HasAttachments
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 9C1FCF74-2D97-41BA-B4AE-CB2E3661A6E4, 8
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Message_HasAttachments, 0x9C1FCF74, 0x2D97, 0x41BA, 0xB4, 0xAE, 0xCB, 0x2E, 0x36, 0x61, 0xA6, 0xE4, 8);
-
-//  Name:     System.Message.IsFwdOrReply -- PKEY_Message_IsFwdOrReply
-//  Type:     Int32 -- VT_I4
-//  FormatID: 9A9BC088-4F6D-469E-9919-E705412040F9, 100
-DEFINE_PROPERTYKEY(PKEY_Message_IsFwdOrReply, 0x9A9BC088, 0x4F6D, 0x469E, 0x99, 0x19, 0xE7, 0x05, 0x41, 0x20, 0x40, 0xF9, 100);
-
-//  Name:     System.Message.MessageClass -- PKEY_Message_MessageClass
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CD9ED458-08CE-418F-A70E-F912C7BB9C5C, 103
-//  
-//  What type of outlook msg this is (meeting, task, mail, etc.)
-DEFINE_PROPERTYKEY(PKEY_Message_MessageClass, 0xCD9ED458, 0x08CE, 0x418F, 0xA7, 0x0E, 0xF9, 0x12, 0xC7, 0xBB, 0x9C, 0x5C, 103);
-
-//  Name:     System.Message.SenderAddress -- PKEY_Message_SenderAddress
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 0BE1C8E7-1981-4676-AE14-FDD78F05A6E7, 100
-DEFINE_PROPERTYKEY(PKEY_Message_SenderAddress, 0x0BE1C8E7, 0x1981, 0x4676, 0xAE, 0x14, 0xFD, 0xD7, 0x8F, 0x05, 0xA6, 0xE7, 100);
-
-//  Name:     System.Message.SenderName -- PKEY_Message_SenderName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 0DA41CFA-D224-4A18-AE2F-596158DB4B3A, 100
-DEFINE_PROPERTYKEY(PKEY_Message_SenderName, 0x0DA41CFA, 0xD224, 0x4A18, 0xAE, 0x2F, 0x59, 0x61, 0x58, 0xDB, 0x4B, 0x3A, 100);
-
-//  Name:     System.Message.Store -- PKEY_Message_Store
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 15
-//
-//  The store (aka protocol handler) FILE, MAIL, OUTLOOKEXPRESS
-DEFINE_PROPERTYKEY(PKEY_Message_Store, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 15);
-
-//  Name:     System.Message.ToAddress -- PKEY_Message_ToAddress
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 16
-//
-//  Addresses in To: field
-DEFINE_PROPERTYKEY(PKEY_Message_ToAddress, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 16);
-
-//  Name:     System.Message.ToDoTitle -- PKEY_Message_ToDoTitle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: BCCC8A3C-8CEF-42E5-9B1C-C69079398BC7, 100
-DEFINE_PROPERTYKEY(PKEY_Message_ToDoTitle, 0xBCCC8A3C, 0x8CEF, 0x42E5, 0x9B, 0x1C, 0xC6, 0x90, 0x79, 0x39, 0x8B, 0xC7, 100);
-
-//  Name:     System.Message.ToName -- PKEY_Message_ToName
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: E3E0584C-B788-4A5A-BB20-7F5A44C9ACDD, 17
-//
-//  Person names in To: field
-DEFINE_PROPERTYKEY(PKEY_Message_ToName, 0xE3E0584C, 0xB788, 0x4A5A, 0xBB, 0x20, 0x7F, 0x5A, 0x44, 0xC9, 0xAC, 0xDD, 17);
- 
-//-----------------------------------------------------------------------------
-// Music properties
-
-//  Name:     System.Music.AlbumArtist -- PKEY_Music_AlbumArtist
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 13 (PIDSI_MUSIC_ALBUM_ARTIST)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_AlbumArtist, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 13);
-
-//  Name:     System.Music.AlbumTitle -- PKEY_Music_AlbumTitle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 4 (PIDSI_MUSIC_ALBUM)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_AlbumTitle, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 4);
-
-//  Name:     System.Music.Artist -- PKEY_Music_Artist
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 2 (PIDSI_MUSIC_ARTIST)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Artist, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 2);
-
-//  Name:     System.Music.BeatsPerMinute -- PKEY_Music_BeatsPerMinute
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 35 (PIDSI_MUSIC_BEATS_PER_MINUTE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_BeatsPerMinute, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 35);
-
-//  Name:     System.Music.Composer -- PKEY_Music_Composer
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 19 (PIDMSI_COMPOSER)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Composer, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 19);
-
-//  Name:     System.Music.Conductor -- PKEY_Music_Conductor
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 36 (PIDSI_MUSIC_CONDUCTOR)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Conductor, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 36);
-
-//  Name:     System.Music.ContentGroupDescription -- PKEY_Music_ContentGroupDescription
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 33 (PIDSI_MUSIC_CONTENT_GROUP_DESCRIPTION)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_ContentGroupDescription, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 33);
-
-//  Name:     System.Music.Genre -- PKEY_Music_Genre
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 11 (PIDSI_MUSIC_GENRE)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Genre, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 11);
-
-//  Name:     System.Music.InitialKey -- PKEY_Music_InitialKey
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 34 (PIDSI_MUSIC_INITIAL_KEY)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_InitialKey, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 34);
-
-//  Name:     System.Music.Lyrics -- PKEY_Music_Lyrics
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 12 (PIDSI_MUSIC_LYRICS)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Lyrics, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 12);
-
-//  Name:     System.Music.Mood -- PKEY_Music_Mood
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 39 (PIDSI_MUSIC_MOOD)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Mood, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 39);
-
-//  Name:     System.Music.PartOfSet -- PKEY_Music_PartOfSet
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 37 (PIDSI_MUSIC_PART_OF_SET)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_PartOfSet, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 37);
-
-//  Name:     System.Music.Period -- PKEY_Music_Period
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 31 (PIDMSI_PERIOD)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_Period, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 31);
-
-//  Name:     System.Music.SynchronizedLyrics -- PKEY_Music_SynchronizedLyrics
-//  Type:     Blob -- VT_BLOB
-//  FormatID: 6B223B6A-162E-4AA9-B39F-05D678FC6D77, 100
-DEFINE_PROPERTYKEY(PKEY_Music_SynchronizedLyrics, 0x6B223B6A, 0x162E, 0x4AA9, 0xB3, 0x9F, 0x05, 0xD6, 0x78, 0xFC, 0x6D, 0x77, 100);
-
-//  Name:     System.Music.TrackNumber -- PKEY_Music_TrackNumber
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_MUSIC) 56A3372E-CE9C-11D2-9F0E-006097C686F6, 7 (PIDSI_MUSIC_TRACK)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Music_TrackNumber, 0x56A3372E, 0xCE9C, 0x11D2, 0x9F, 0x0E, 0x00, 0x60, 0x97, 0xC6, 0x86, 0xF6, 7);
-
- 
- 
-//-----------------------------------------------------------------------------
-// Note properties
-
-//  Name:     System.Note.Color -- PKEY_Note_Color
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: 4776CAFA-BCE4-4CB1-A23E-265E76D8EB11, 100
-DEFINE_PROPERTYKEY(PKEY_Note_Color, 0x4776CAFA, 0xBCE4, 0x4CB1, 0xA2, 0x3E, 0x26, 0x5E, 0x76, 0xD8, 0xEB, 0x11, 100);
-
-// Possible discrete values for PKEY_Note_Color are:
-#define NOTE_COLOR_BLUE                     0u
-#define NOTE_COLOR_GREEN                    1u
-#define NOTE_COLOR_PINK                     2u
-#define NOTE_COLOR_YELLOW                   3u
-#define NOTE_COLOR_WHITE                    4u
-#define NOTE_COLOR_LIGHTGREEN               5u
-
-//  Name:     System.Note.ColorText -- PKEY_Note_ColorText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 46B4E8DE-CDB2-440D-885C-1658EB65B914, 100
-//  
-//  This is the user-friendly form of System.Note.Color.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Note_ColorText, 0x46B4E8DE, 0xCDB2, 0x440D, 0x88, 0x5C, 0x16, 0x58, 0xEB, 0x65, 0xB9, 0x14, 100);
- 
-//-----------------------------------------------------------------------------
-// Photo properties
-
-
-
-//  Name:     System.Photo.Aperture -- PKEY_Photo_Aperture
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37378
-//
-//  PropertyTagExifAperture.  Calculated from PKEY_Photo_ApertureNumerator and PKEY_Photo_ApertureDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_Aperture, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37378);
-
-//  Name:     System.Photo.ApertureDenominator -- PKEY_Photo_ApertureDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: E1A9A38B-6685-46BD-875E-570DC7AD7320, 100
-//
-//  Denominator of PKEY_Photo_Aperture
-DEFINE_PROPERTYKEY(PKEY_Photo_ApertureDenominator, 0xE1A9A38B, 0x6685, 0x46BD, 0x87, 0x5E, 0x57, 0x0D, 0xC7, 0xAD, 0x73, 0x20, 100);
-
-//  Name:     System.Photo.ApertureNumerator -- PKEY_Photo_ApertureNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 0337ECEC-39FB-4581-A0BD-4C4CC51E9914, 100
-//
-//  Numerator of PKEY_Photo_Aperture
-DEFINE_PROPERTYKEY(PKEY_Photo_ApertureNumerator, 0x0337ECEC, 0x39FB, 0x4581, 0xA0, 0xBD, 0x4C, 0x4C, 0xC5, 0x1E, 0x99, 0x14, 100);
-
-//  Name:     System.Photo.Brightness -- PKEY_Photo_Brightness
-//  Type:     Double -- VT_R8
-//  FormatID: 1A701BF6-478C-4361-83AB-3701BB053C58, 100 (PropertyTagExifBrightness)
-//  
-//  This is the brightness of the photo.
-//  
-//  Calculated from PKEY_Photo_BrightnessNumerator and PKEY_Photo_BrightnessDenominator.
-//  
-//  The units are "APEX", normally in the range of -99.99 to 99.99. If the numerator of 
-//  the recorded value is FFFFFFFF.H, "Unknown" should be indicated.
-DEFINE_PROPERTYKEY(PKEY_Photo_Brightness, 0x1A701BF6, 0x478C, 0x4361, 0x83, 0xAB, 0x37, 0x01, 0xBB, 0x05, 0x3C, 0x58, 100);
-
-//  Name:     System.Photo.BrightnessDenominator -- PKEY_Photo_BrightnessDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 6EBE6946-2321-440A-90F0-C043EFD32476, 100
-//
-//  Denominator of PKEY_Photo_Brightness
-DEFINE_PROPERTYKEY(PKEY_Photo_BrightnessDenominator, 0x6EBE6946, 0x2321, 0x440A, 0x90, 0xF0, 0xC0, 0x43, 0xEF, 0xD3, 0x24, 0x76, 100);
-
-//  Name:     System.Photo.BrightnessNumerator -- PKEY_Photo_BrightnessNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 9E7D118F-B314-45A0-8CFB-D654B917C9E9, 100
-//
-//  Numerator of PKEY_Photo_Brightness
-DEFINE_PROPERTYKEY(PKEY_Photo_BrightnessNumerator, 0x9E7D118F, 0xB314, 0x45A0, 0x8C, 0xFB, 0xD6, 0x54, 0xB9, 0x17, 0xC9, 0xE9, 100);
-
-//  Name:     System.Photo.CameraManufacturer -- PKEY_Photo_CameraManufacturer
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 271 (PropertyTagEquipMake)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Photo_CameraManufacturer, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 271);
-
-//  Name:     System.Photo.CameraModel -- PKEY_Photo_CameraModel
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 272 (PropertyTagEquipModel)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Photo_CameraModel, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 272);
-
-//  Name:     System.Photo.CameraSerialNumber -- PKEY_Photo_CameraSerialNumber
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 273
-//
-//  Serial number of camera that produced this photo
-DEFINE_PROPERTYKEY(PKEY_Photo_CameraSerialNumber, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 273);
-
-//  Name:     System.Photo.Contrast -- PKEY_Photo_Contrast
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 2A785BA9-8D23-4DED-82E6-60A350C86A10, 100
-//  
-//  This indicates the direction of contrast processing applied by the camera 
-//  when the image was shot.
-DEFINE_PROPERTYKEY(PKEY_Photo_Contrast, 0x2A785BA9, 0x8D23, 0x4DED, 0x82, 0xE6, 0x60, 0xA3, 0x50, 0xC8, 0x6A, 0x10, 100);
-
-// Possible discrete values for PKEY_Photo_Contrast are:
-#define PHOTO_CONTRAST_NORMAL               0ul
-#define PHOTO_CONTRAST_SOFT                 1ul
-#define PHOTO_CONTRAST_HARD                 2ul
-
-//  Name:     System.Photo.ContrastText -- PKEY_Photo_ContrastText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 59DDE9F2-5253-40EA-9A8B-479E96C6249A, 100
-//  
-//  This is the user-friendly form of System.Photo.Contrast.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_ContrastText, 0x59DDE9F2, 0x5253, 0x40EA, 0x9A, 0x8B, 0x47, 0x9E, 0x96, 0xC6, 0x24, 0x9A, 100);
-
-//  Name:     System.Photo.DateTaken -- PKEY_Photo_DateTaken
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 36867
-//
-//  PropertyTagExifDTOrig
-DEFINE_PROPERTYKEY(PKEY_Photo_DateTaken, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 36867);
-
-//  Name:     System.Photo.DigitalZoom -- PKEY_Photo_DigitalZoom
-//  Type:     Double -- VT_R8
-//  FormatID: F85BF840-A925-4BC2-B0C4-8E36B598679E, 100
-//
-//  PropertyTagExifDigitalZoom.  Calculated from PKEY_Photo_DigitalZoomNumerator and PKEY_Photo_DigitalZoomDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_DigitalZoom, 0xF85BF840, 0xA925, 0x4BC2, 0xB0, 0xC4, 0x8E, 0x36, 0xB5, 0x98, 0x67, 0x9E, 100);
-
-//  Name:     System.Photo.DigitalZoomDenominator -- PKEY_Photo_DigitalZoomDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 745BAF0E-E5C1-4CFB-8A1B-D031A0A52393, 100
-//
-//  Denominator of PKEY_Photo_DigitalZoom
-DEFINE_PROPERTYKEY(PKEY_Photo_DigitalZoomDenominator, 0x745BAF0E, 0xE5C1, 0x4CFB, 0x8A, 0x1B, 0xD0, 0x31, 0xA0, 0xA5, 0x23, 0x93, 100);
-
-//  Name:     System.Photo.DigitalZoomNumerator -- PKEY_Photo_DigitalZoomNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 16CBB924-6500-473B-A5BE-F1599BCBE413, 100
-//
-//  Numerator of PKEY_Photo_DigitalZoom
-DEFINE_PROPERTYKEY(PKEY_Photo_DigitalZoomNumerator, 0x16CBB924, 0x6500, 0x473B, 0xA5, 0xBE, 0xF1, 0x59, 0x9B, 0xCB, 0xE4, 0x13, 100);
-
-//  Name:     System.Photo.Event -- PKEY_Photo_Event
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 18248
-//
-//  The event at which the photo was taken
-DEFINE_PROPERTYKEY(PKEY_Photo_Event, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 18248);
-
-//  Name:     System.Photo.EXIFVersion -- PKEY_Photo_EXIFVersion
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: D35F743A-EB2E-47F2-A286-844132CB1427, 100
-//
-//  The EXIF version.
-DEFINE_PROPERTYKEY(PKEY_Photo_EXIFVersion, 0xD35F743A, 0xEB2E, 0x47F2, 0xA2, 0x86, 0x84, 0x41, 0x32, 0xCB, 0x14, 0x27, 100);
-
-//  Name:     System.Photo.ExposureBias -- PKEY_Photo_ExposureBias
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37380
-//
-//  PropertyTagExifExposureBias.  Calculated from PKEY_Photo_ExposureBiasNumerator and PKEY_Photo_ExposureBiasDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureBias, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37380);
-
-//  Name:     System.Photo.ExposureBiasDenominator -- PKEY_Photo_ExposureBiasDenominator
-//  Type:     Int32 -- VT_I4
-//  FormatID: AB205E50-04B7-461C-A18C-2F233836E627, 100
-//
-//  Denominator of PKEY_Photo_ExposureBias
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureBiasDenominator, 0xAB205E50, 0x04B7, 0x461C, 0xA1, 0x8C, 0x2F, 0x23, 0x38, 0x36, 0xE6, 0x27, 100);
-
-//  Name:     System.Photo.ExposureBiasNumerator -- PKEY_Photo_ExposureBiasNumerator
-//  Type:     Int32 -- VT_I4
-//  FormatID: 738BF284-1D87-420B-92CF-5834BF6EF9ED, 100
-//
-//  Numerator of PKEY_Photo_ExposureBias
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureBiasNumerator, 0x738BF284, 0x1D87, 0x420B, 0x92, 0xCF, 0x58, 0x34, 0xBF, 0x6E, 0xF9, 0xED, 100);
-
-//  Name:     System.Photo.ExposureIndex -- PKEY_Photo_ExposureIndex
-//  Type:     Double -- VT_R8
-//  FormatID: 967B5AF8-995A-46ED-9E11-35B3C5B9782D, 100
-//
-//  PropertyTagExifExposureIndex.  Calculated from PKEY_Photo_ExposureIndexNumerator and PKEY_Photo_ExposureIndexDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureIndex, 0x967B5AF8, 0x995A, 0x46ED, 0x9E, 0x11, 0x35, 0xB3, 0xC5, 0xB9, 0x78, 0x2D, 100);
-
-//  Name:     System.Photo.ExposureIndexDenominator -- PKEY_Photo_ExposureIndexDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 93112F89-C28B-492F-8A9D-4BE2062CEE8A, 100
-//
-//  Denominator of PKEY_Photo_ExposureIndex
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureIndexDenominator, 0x93112F89, 0xC28B, 0x492F, 0x8A, 0x9D, 0x4B, 0xE2, 0x06, 0x2C, 0xEE, 0x8A, 100);
-
-//  Name:     System.Photo.ExposureIndexNumerator -- PKEY_Photo_ExposureIndexNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: CDEDCF30-8919-44DF-8F4C-4EB2FFDB8D89, 100
-//
-//  Numerator of PKEY_Photo_ExposureIndex
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureIndexNumerator, 0xCDEDCF30, 0x8919, 0x44DF, 0x8F, 0x4C, 0x4E, 0xB2, 0xFF, 0xDB, 0x8D, 0x89, 100);
-
-//  Name:     System.Photo.ExposureProgram -- PKEY_Photo_ExposureProgram
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 34850 (PropertyTagExifExposureProg)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureProgram, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 34850);
-
-// Possible discrete values for PKEY_Photo_ExposureProgram are:
-#define PHOTO_EXPOSUREPROGRAM_UNKNOWN       0ul
-#define PHOTO_EXPOSUREPROGRAM_MANUAL        1ul
-#define PHOTO_EXPOSUREPROGRAM_NORMAL        2ul
-#define PHOTO_EXPOSUREPROGRAM_APERTURE      3ul
-#define PHOTO_EXPOSUREPROGRAM_SHUTTER       4ul
-#define PHOTO_EXPOSUREPROGRAM_CREATIVE      5ul
-#define PHOTO_EXPOSUREPROGRAM_ACTION        6ul
-#define PHOTO_EXPOSUREPROGRAM_PORTRAIT      7ul
-#define PHOTO_EXPOSUREPROGRAM_LANDSCAPE     8ul
-
-//  Name:     System.Photo.ExposureProgramText -- PKEY_Photo_ExposureProgramText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: FEC690B7-5F30-4646-AE47-4CAAFBA884A3, 100
-//  
-//  This is the user-friendly form of System.Photo.ExposureProgram.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureProgramText, 0xFEC690B7, 0x5F30, 0x4646, 0xAE, 0x47, 0x4C, 0xAA, 0xFB, 0xA8, 0x84, 0xA3, 100);
-
-//  Name:     System.Photo.ExposureTime -- PKEY_Photo_ExposureTime
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 33434
-//
-//  PropertyTagExifExposureTime.  Calculated from  PKEY_Photo_ExposureTimeNumerator and PKEY_Photo_ExposureTimeDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureTime, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 33434);
-
-//  Name:     System.Photo.ExposureTimeDenominator -- PKEY_Photo_ExposureTimeDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 55E98597-AD16-42E0-B624-21599A199838, 100
-//
-//  Denominator of PKEY_Photo_ExposureTime
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureTimeDenominator, 0x55E98597, 0xAD16, 0x42E0, 0xB6, 0x24, 0x21, 0x59, 0x9A, 0x19, 0x98, 0x38, 100);
-
-//  Name:     System.Photo.ExposureTimeNumerator -- PKEY_Photo_ExposureTimeNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 257E44E2-9031-4323-AC38-85C552871B2E, 100
-//
-//  Numerator of PKEY_Photo_ExposureTime
-DEFINE_PROPERTYKEY(PKEY_Photo_ExposureTimeNumerator, 0x257E44E2, 0x9031, 0x4323, 0xAC, 0x38, 0x85, 0xC5, 0x52, 0x87, 0x1B, 0x2E, 100);
-
-//  Name:     System.Photo.Flash -- PKEY_Photo_Flash
-//  Type:     Byte -- VT_UI1
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37385
-//
-//  PropertyTagExifFlash
-DEFINE_PROPERTYKEY(PKEY_Photo_Flash, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37385);
-
-// Possible discrete values for PKEY_Photo_Flash are:
-#define PHOTO_FLASH_NONE                    0
-#define PHOTO_FLASH_FLASH                   1
-#define PHOTO_FLASH_WITHOUTSTROBE           5
-#define PHOTO_FLASH_WITHSTROBE              7
-
-//  Name:     System.Photo.FlashEnergy -- PKEY_Photo_FlashEnergy
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 41483
-//
-//  PropertyTagExifFlashEnergy.  Calculated from PKEY_Photo_FlashEnergyNumerator and PKEY_Photo_FlashEnergyDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_FlashEnergy, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 41483);
-
-//  Name:     System.Photo.FlashEnergyDenominator -- PKEY_Photo_FlashEnergyDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: D7B61C70-6323-49CD-A5FC-C84277162C97, 100
-//
-//  Denominator of PKEY_Photo_FlashEnergy
-DEFINE_PROPERTYKEY(PKEY_Photo_FlashEnergyDenominator, 0xD7B61C70, 0x6323, 0x49CD, 0xA5, 0xFC, 0xC8, 0x42, 0x77, 0x16, 0x2C, 0x97, 100);
-
-//  Name:     System.Photo.FlashEnergyNumerator -- PKEY_Photo_FlashEnergyNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: FCAD3D3D-0858-400F-AAA3-2F66CCE2A6BC, 100
-//
-//  Numerator of PKEY_Photo_FlashEnergy
-DEFINE_PROPERTYKEY(PKEY_Photo_FlashEnergyNumerator, 0xFCAD3D3D, 0x0858, 0x400F, 0xAA, 0xA3, 0x2F, 0x66, 0xCC, 0xE2, 0xA6, 0xBC, 100);
-
-//  Name:     System.Photo.FlashManufacturer -- PKEY_Photo_FlashManufacturer
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: AABAF6C9-E0C5-4719-8585-57B103E584FE, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_FlashManufacturer, 0xAABAF6C9, 0xE0C5, 0x4719, 0x85, 0x85, 0x57, 0xB1, 0x03, 0xE5, 0x84, 0xFE, 100);
-
-//  Name:     System.Photo.FlashModel -- PKEY_Photo_FlashModel
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: FE83BB35-4D1A-42E2-916B-06F3E1AF719E, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_FlashModel, 0xFE83BB35, 0x4D1A, 0x42E2, 0x91, 0x6B, 0x06, 0xF3, 0xE1, 0xAF, 0x71, 0x9E, 100);
-
-//  Name:     System.Photo.FlashText -- PKEY_Photo_FlashText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6B8B68F6-200B-47EA-8D25-D8050F57339F, 100
-//  
-//  This is the user-friendly form of System.Photo.Flash.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_FlashText, 0x6B8B68F6, 0x200B, 0x47EA, 0x8D, 0x25, 0xD8, 0x05, 0x0F, 0x57, 0x33, 0x9F, 100);
-
-//  Name:     System.Photo.FNumber -- PKEY_Photo_FNumber
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 33437
-//
-//  PropertyTagExifFNumber.  Calculated from PKEY_Photo_FNumberNumerator and PKEY_Photo_FNumberDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_FNumber, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 33437);
-
-//  Name:     System.Photo.FNumberDenominator -- PKEY_Photo_FNumberDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: E92A2496-223B-4463-A4E3-30EABBA79D80, 100
-//
-//  Denominator of PKEY_Photo_FNumber
-DEFINE_PROPERTYKEY(PKEY_Photo_FNumberDenominator, 0xE92A2496, 0x223B, 0x4463, 0xA4, 0xE3, 0x30, 0xEA, 0xBB, 0xA7, 0x9D, 0x80, 100);
-
-//  Name:     System.Photo.FNumberNumerator -- PKEY_Photo_FNumberNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 1B97738A-FDFC-462F-9D93-1957E08BE90C, 100
-//
-//  Numerator of PKEY_Photo_FNumber
-DEFINE_PROPERTYKEY(PKEY_Photo_FNumberNumerator, 0x1B97738A, 0xFDFC, 0x462F, 0x9D, 0x93, 0x19, 0x57, 0xE0, 0x8B, 0xE9, 0x0C, 100);
-
-//  Name:     System.Photo.FocalLength -- PKEY_Photo_FocalLength
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37386
-//
-//  PropertyTagExifFocalLength.  Calculated from PKEY_Photo_FocalLengthNumerator and PKEY_Photo_FocalLengthDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalLength, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37386);
-
-//  Name:     System.Photo.FocalLengthDenominator -- PKEY_Photo_FocalLengthDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 305BC615-DCA1-44A5-9FD4-10C0BA79412E, 100
-//
-//  Denominator of PKEY_Photo_FocalLength
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalLengthDenominator, 0x305BC615, 0xDCA1, 0x44A5, 0x9F, 0xD4, 0x10, 0xC0, 0xBA, 0x79, 0x41, 0x2E, 100);
-
-//  Name:     System.Photo.FocalLengthInFilm -- PKEY_Photo_FocalLengthInFilm
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: A0E74609-B84D-4F49-B860-462BD9971F98, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalLengthInFilm, 0xA0E74609, 0xB84D, 0x4F49, 0xB8, 0x60, 0x46, 0x2B, 0xD9, 0x97, 0x1F, 0x98, 100);
-
-//  Name:     System.Photo.FocalLengthNumerator -- PKEY_Photo_FocalLengthNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 776B6B3B-1E3D-4B0C-9A0E-8FBAF2A8492A, 100
-//
-//  Numerator of PKEY_Photo_FocalLength
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalLengthNumerator, 0x776B6B3B, 0x1E3D, 0x4B0C, 0x9A, 0x0E, 0x8F, 0xBA, 0xF2, 0xA8, 0x49, 0x2A, 100);
-
-//  Name:     System.Photo.FocalPlaneXResolution -- PKEY_Photo_FocalPlaneXResolution
-//  Type:     Double -- VT_R8
-//  FormatID: CFC08D97-C6F7-4484-89DD-EBEF4356FE76, 100
-//  
-//  PropertyTagExifFocalXRes.  Calculated from PKEY_Photo_FocalPlaneXResolutionNumerator and 
-//  PKEY_Photo_FocalPlaneXResolutionDenominator.
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalPlaneXResolution, 0xCFC08D97, 0xC6F7, 0x4484, 0x89, 0xDD, 0xEB, 0xEF, 0x43, 0x56, 0xFE, 0x76, 100);
-
-//  Name:     System.Photo.FocalPlaneXResolutionDenominator -- PKEY_Photo_FocalPlaneXResolutionDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 0933F3F5-4786-4F46-A8E8-D64DD37FA521, 100
-//
-//  Denominator of PKEY_Photo_FocalPlaneXResolution
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalPlaneXResolutionDenominator, 0x0933F3F5, 0x4786, 0x4F46, 0xA8, 0xE8, 0xD6, 0x4D, 0xD3, 0x7F, 0xA5, 0x21, 100);
-
-//  Name:     System.Photo.FocalPlaneXResolutionNumerator -- PKEY_Photo_FocalPlaneXResolutionNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: DCCB10AF-B4E2-4B88-95F9-031B4D5AB490, 100
-//
-//  Numerator of PKEY_Photo_FocalPlaneXResolution
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalPlaneXResolutionNumerator, 0xDCCB10AF, 0xB4E2, 0x4B88, 0x95, 0xF9, 0x03, 0x1B, 0x4D, 0x5A, 0xB4, 0x90, 100);
-
-//  Name:     System.Photo.FocalPlaneYResolution -- PKEY_Photo_FocalPlaneYResolution
-//  Type:     Double -- VT_R8
-//  FormatID: 4FFFE4D0-914F-4AC4-8D6F-C9C61DE169B1, 100
-//  
-//  PropertyTagExifFocalYRes.  Calculated from PKEY_Photo_FocalPlaneYResolutionNumerator and 
-//  PKEY_Photo_FocalPlaneYResolutionDenominator.
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalPlaneYResolution, 0x4FFFE4D0, 0x914F, 0x4AC4, 0x8D, 0x6F, 0xC9, 0xC6, 0x1D, 0xE1, 0x69, 0xB1, 100);
-
-//  Name:     System.Photo.FocalPlaneYResolutionDenominator -- PKEY_Photo_FocalPlaneYResolutionDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 1D6179A6-A876-4031-B013-3347B2B64DC8, 100
-//
-//  Denominator of PKEY_Photo_FocalPlaneYResolution
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalPlaneYResolutionDenominator, 0x1D6179A6, 0xA876, 0x4031, 0xB0, 0x13, 0x33, 0x47, 0xB2, 0xB6, 0x4D, 0xC8, 100);
-
-//  Name:     System.Photo.FocalPlaneYResolutionNumerator -- PKEY_Photo_FocalPlaneYResolutionNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: A2E541C5-4440-4BA8-867E-75CFC06828CD, 100
-//
-//  Numerator of PKEY_Photo_FocalPlaneYResolution
-DEFINE_PROPERTYKEY(PKEY_Photo_FocalPlaneYResolutionNumerator, 0xA2E541C5, 0x4440, 0x4BA8, 0x86, 0x7E, 0x75, 0xCF, 0xC0, 0x68, 0x28, 0xCD, 100);
-
-//  Name:     System.Photo.GainControl -- PKEY_Photo_GainControl
-//  Type:     Double -- VT_R8
-//  FormatID: FA304789-00C7-4D80-904A-1E4DCC7265AA, 100 (PropertyTagExifGainControl)
-//  
-//  This indicates the degree of overall image gain adjustment.
-//  
-//  Calculated from PKEY_Photo_GainControlNumerator and PKEY_Photo_GainControlDenominator.
-DEFINE_PROPERTYKEY(PKEY_Photo_GainControl, 0xFA304789, 0x00C7, 0x4D80, 0x90, 0x4A, 0x1E, 0x4D, 0xCC, 0x72, 0x65, 0xAA, 100);
-
-// Possible discrete values for PKEY_Photo_GainControl are:
-#define PHOTO_GAINCONTROL_NONE              0.0
-#define PHOTO_GAINCONTROL_LOWGAINUP         1.0
-#define PHOTO_GAINCONTROL_HIGHGAINUP        2.0
-#define PHOTO_GAINCONTROL_LOWGAINDOWN       3.0
-#define PHOTO_GAINCONTROL_HIGHGAINDOWN      4.0
-
-//  Name:     System.Photo.GainControlDenominator -- PKEY_Photo_GainControlDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 42864DFD-9DA4-4F77-BDED-4AAD7B256735, 100
-//
-//  Denominator of PKEY_Photo_GainControl
-DEFINE_PROPERTYKEY(PKEY_Photo_GainControlDenominator, 0x42864DFD, 0x9DA4, 0x4F77, 0xBD, 0xED, 0x4A, 0xAD, 0x7B, 0x25, 0x67, 0x35, 100);
-
-//  Name:     System.Photo.GainControlNumerator -- PKEY_Photo_GainControlNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 8E8ECF7C-B7B8-4EB8-A63F-0EE715C96F9E, 100
-//
-//  Numerator of PKEY_Photo_GainControl
-DEFINE_PROPERTYKEY(PKEY_Photo_GainControlNumerator, 0x8E8ECF7C, 0xB7B8, 0x4EB8, 0xA6, 0x3F, 0x0E, 0xE7, 0x15, 0xC9, 0x6F, 0x9E, 100);
-
-//  Name:     System.Photo.GainControlText -- PKEY_Photo_GainControlText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C06238B2-0BF9-4279-A723-25856715CB9D, 100
-//  
-//  This is the user-friendly form of System.Photo.GainControl.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_GainControlText, 0xC06238B2, 0x0BF9, 0x4279, 0xA7, 0x23, 0x25, 0x85, 0x67, 0x15, 0xCB, 0x9D, 100);
-
-//  Name:     System.Photo.ISOSpeed -- PKEY_Photo_ISOSpeed
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 34855
-//
-//  PropertyTagExifISOSpeed
-DEFINE_PROPERTYKEY(PKEY_Photo_ISOSpeed, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 34855);
-
-//  Name:     System.Photo.LensManufacturer -- PKEY_Photo_LensManufacturer
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E6DDCAF7-29C5-4F0A-9A68-D19412EC7090, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_LensManufacturer, 0xE6DDCAF7, 0x29C5, 0x4F0A, 0x9A, 0x68, 0xD1, 0x94, 0x12, 0xEC, 0x70, 0x90, 100);
-
-//  Name:     System.Photo.LensModel -- PKEY_Photo_LensModel
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: E1277516-2B5F-4869-89B1-2E585BD38B7A, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_LensModel, 0xE1277516, 0x2B5F, 0x4869, 0x89, 0xB1, 0x2E, 0x58, 0x5B, 0xD3, 0x8B, 0x7A, 100);
-
-//  Name:     System.Photo.LightSource -- PKEY_Photo_LightSource
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37384
-//
-//  PropertyTagExifLightSource
-DEFINE_PROPERTYKEY(PKEY_Photo_LightSource, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37384);
-
-// Possible discrete values for PKEY_Photo_LightSource are:
-#define PHOTO_LIGHTSOURCE_UNKNOWN           0ul
-#define PHOTO_LIGHTSOURCE_DAYLIGHT          1ul
-#define PHOTO_LIGHTSOURCE_FLUORESCENT       2ul
-#define PHOTO_LIGHTSOURCE_TUNGSTEN          3ul
-#define PHOTO_LIGHTSOURCE_STANDARD_A        17ul
-#define PHOTO_LIGHTSOURCE_STANDARD_B        18ul
-#define PHOTO_LIGHTSOURCE_STANDARD_C        19ul
-#define PHOTO_LIGHTSOURCE_D55               20ul
-#define PHOTO_LIGHTSOURCE_D65               21ul
-#define PHOTO_LIGHTSOURCE_D75               22ul
-
-//  Name:     System.Photo.MakerNote -- PKEY_Photo_MakerNote
-//  Type:     Buffer -- VT_VECTOR | VT_UI1  (For variants: VT_ARRAY | VT_UI1)
-//  FormatID: FA303353-B659-4052-85E9-BCAC79549B84, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_MakerNote, 0xFA303353, 0xB659, 0x4052, 0x85, 0xE9, 0xBC, 0xAC, 0x79, 0x54, 0x9B, 0x84, 100);
-
-//  Name:     System.Photo.MakerNoteOffset -- PKEY_Photo_MakerNoteOffset
-//  Type:     UInt64 -- VT_UI8
-//  FormatID: 813F4124-34E6-4D17-AB3E-6B1F3C2247A1, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_MakerNoteOffset, 0x813F4124, 0x34E6, 0x4D17, 0xAB, 0x3E, 0x6B, 0x1F, 0x3C, 0x22, 0x47, 0xA1, 100);
-
-//  Name:     System.Photo.MaxAperture -- PKEY_Photo_MaxAperture
-//  Type:     Double -- VT_R8
-//  FormatID: 08F6D7C2-E3F2-44FC-AF1E-5AA5C81A2D3E, 100
-//
-//  Calculated from PKEY_Photo_MaxApertureNumerator and PKEY_Photo_MaxApertureDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_MaxAperture, 0x08F6D7C2, 0xE3F2, 0x44FC, 0xAF, 0x1E, 0x5A, 0xA5, 0xC8, 0x1A, 0x2D, 0x3E, 100);
-
-//  Name:     System.Photo.MaxApertureDenominator -- PKEY_Photo_MaxApertureDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: C77724D4-601F-46C5-9B89-C53F93BCEB77, 100
-//
-//  Denominator of PKEY_Photo_MaxAperture
-DEFINE_PROPERTYKEY(PKEY_Photo_MaxApertureDenominator, 0xC77724D4, 0x601F, 0x46C5, 0x9B, 0x89, 0xC5, 0x3F, 0x93, 0xBC, 0xEB, 0x77, 100);
-
-//  Name:     System.Photo.MaxApertureNumerator -- PKEY_Photo_MaxApertureNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: C107E191-A459-44C5-9AE6-B952AD4B906D, 100
-//
-//  Numerator of PKEY_Photo_MaxAperture
-DEFINE_PROPERTYKEY(PKEY_Photo_MaxApertureNumerator, 0xC107E191, 0xA459, 0x44C5, 0x9A, 0xE6, 0xB9, 0x52, 0xAD, 0x4B, 0x90, 0x6D, 100);
-
-//  Name:     System.Photo.MeteringMode -- PKEY_Photo_MeteringMode
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37383
-//
-//  PropertyTagExifMeteringMode
-DEFINE_PROPERTYKEY(PKEY_Photo_MeteringMode, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37383);
-
-// Possible discrete values for PKEY_Photo_MeteringMode are:
-#define PHOTO_METERINGMODE_UNKNOWN          0u
-#define PHOTO_METERINGMODE_AVERAGE          1u
-#define PHOTO_METERINGMODE_CENTER           2u
-#define PHOTO_METERINGMODE_SPOT             3u
-#define PHOTO_METERINGMODE_MULTISPOT        4u
-#define PHOTO_METERINGMODE_PATTERN          5u
-#define PHOTO_METERINGMODE_PARTIAL          6u
-
-//  Name:     System.Photo.MeteringModeText -- PKEY_Photo_MeteringModeText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: F628FD8C-7BA8-465A-A65B-C5AA79263A9E, 100
-//  
-//  This is the user-friendly form of System.Photo.MeteringMode.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_MeteringModeText, 0xF628FD8C, 0x7BA8, 0x465A, 0xA6, 0x5B, 0xC5, 0xAA, 0x79, 0x26, 0x3A, 0x9E, 100);
-
-//  Name:     System.Photo.Orientation -- PKEY_Photo_Orientation
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 274 (PropertyTagOrientation)
-//  
-//  This is the image orientation viewed in terms of rows and columns.
-DEFINE_PROPERTYKEY(PKEY_Photo_Orientation, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 274);
-
-// Possible discrete values for PKEY_Photo_Orientation are:
-#define PHOTO_ORIENTATION_NORMAL            1u
-#define PHOTO_ORIENTATION_FLIPHORIZONTAL    2u
-#define PHOTO_ORIENTATION_ROTATE180         3u
-#define PHOTO_ORIENTATION_FLIPVERTICAL      4u
-#define PHOTO_ORIENTATION_TRANSPOSE         5u
-#define PHOTO_ORIENTATION_ROTATE270         6u
-#define PHOTO_ORIENTATION_TRANSVERSE        7u
-#define PHOTO_ORIENTATION_ROTATE90          8u
-
-//  Name:     System.Photo.OrientationText -- PKEY_Photo_OrientationText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A9EA193C-C511-498A-A06B-58E2776DCC28, 100
-//  
-//  This is the user-friendly form of System.Photo.Orientation.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_OrientationText, 0xA9EA193C, 0xC511, 0x498A, 0xA0, 0x6B, 0x58, 0xE2, 0x77, 0x6D, 0xCC, 0x28, 100);
-
-//  Name:     System.Photo.PhotometricInterpretation -- PKEY_Photo_PhotometricInterpretation
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: 341796F1-1DF9-4B1C-A564-91BDEFA43877, 100
-//  
-//  This is the pixel composition. In JPEG compressed data, a JPEG marker is used 
-//  instead of this property.
-DEFINE_PROPERTYKEY(PKEY_Photo_PhotometricInterpretation, 0x341796F1, 0x1DF9, 0x4B1C, 0xA5, 0x64, 0x91, 0xBD, 0xEF, 0xA4, 0x38, 0x77, 100);
-
-// Possible discrete values for PKEY_Photo_PhotometricInterpretation are:
-#define PHOTO_PHOTOMETRIC_RGB               2u
-#define PHOTO_PHOTOMETRIC_YCBCR             6u
-
-//  Name:     System.Photo.PhotometricInterpretationText -- PKEY_Photo_PhotometricInterpretationText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 821437D6-9EAB-4765-A589-3B1CBBD22A61, 100
-//  
-//  This is the user-friendly form of System.Photo.PhotometricInterpretation.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_PhotometricInterpretationText, 0x821437D6, 0x9EAB, 0x4765, 0xA5, 0x89, 0x3B, 0x1C, 0xBB, 0xD2, 0x2A, 0x61, 100);
-
-//  Name:     System.Photo.ProgramMode -- PKEY_Photo_ProgramMode
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 6D217F6D-3F6A-4825-B470-5F03CA2FBE9B, 100
-//  
-//  This is the class of the program used by the camera to set exposure when the 
-//  picture is taken.
-DEFINE_PROPERTYKEY(PKEY_Photo_ProgramMode, 0x6D217F6D, 0x3F6A, 0x4825, 0xB4, 0x70, 0x5F, 0x03, 0xCA, 0x2F, 0xBE, 0x9B, 100);
-
-// Possible discrete values for PKEY_Photo_ProgramMode are:
-#define PHOTO_PROGRAMMODE_NOTDEFINED        0ul
-#define PHOTO_PROGRAMMODE_MANUAL            1ul
-#define PHOTO_PROGRAMMODE_NORMAL            2ul
-#define PHOTO_PROGRAMMODE_APERTURE          3ul
-#define PHOTO_PROGRAMMODE_SHUTTER           4ul
-#define PHOTO_PROGRAMMODE_CREATIVE          5ul
-#define PHOTO_PROGRAMMODE_ACTION            6ul
-#define PHOTO_PROGRAMMODE_PORTRAIT          7ul
-#define PHOTO_PROGRAMMODE_LANDSCAPE         8ul
-
-//  Name:     System.Photo.ProgramModeText -- PKEY_Photo_ProgramModeText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7FE3AA27-2648-42F3-89B0-454E5CB150C3, 100
-//  
-//  This is the user-friendly form of System.Photo.ProgramMode.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_ProgramModeText, 0x7FE3AA27, 0x2648, 0x42F3, 0x89, 0xB0, 0x45, 0x4E, 0x5C, 0xB1, 0x50, 0xC3, 100);
-
-//  Name:     System.Photo.RelatedSoundFile -- PKEY_Photo_RelatedSoundFile
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 318A6B45-087F-4DC2-B8CC-05359551FC9E, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_RelatedSoundFile, 0x318A6B45, 0x087F, 0x4DC2, 0xB8, 0xCC, 0x05, 0x35, 0x95, 0x51, 0xFC, 0x9E, 100);
-
-//  Name:     System.Photo.Saturation -- PKEY_Photo_Saturation
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 49237325-A95A-4F67-B211-816B2D45D2E0, 100
-//  
-//  This indicates the direction of saturation processing applied by the camera when 
-//  the image was shot.
-DEFINE_PROPERTYKEY(PKEY_Photo_Saturation, 0x49237325, 0xA95A, 0x4F67, 0xB2, 0x11, 0x81, 0x6B, 0x2D, 0x45, 0xD2, 0xE0, 100);
-
-// Possible discrete values for PKEY_Photo_Saturation are:
-#define PHOTO_SATURATION_NORMAL             0ul
-#define PHOTO_SATURATION_LOW                1ul
-#define PHOTO_SATURATION_HIGH               2ul
-
-//  Name:     System.Photo.SaturationText -- PKEY_Photo_SaturationText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 61478C08-B600-4A84-BBE4-E99C45F0A072, 100
-//  
-//  This is the user-friendly form of System.Photo.Saturation.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_SaturationText, 0x61478C08, 0xB600, 0x4A84, 0xBB, 0xE4, 0xE9, 0x9C, 0x45, 0xF0, 0xA0, 0x72, 100);
-
-//  Name:     System.Photo.Sharpness -- PKEY_Photo_Sharpness
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: FC6976DB-8349-4970-AE97-B3C5316A08F0, 100
-//  
-//  This indicates the direction of sharpness processing applied by the camera when 
-//  the image was shot.
-DEFINE_PROPERTYKEY(PKEY_Photo_Sharpness, 0xFC6976DB, 0x8349, 0x4970, 0xAE, 0x97, 0xB3, 0xC5, 0x31, 0x6A, 0x08, 0xF0, 100);
-
-// Possible discrete values for PKEY_Photo_Sharpness are:
-#define PHOTO_SHARPNESS_NORMAL              0ul
-#define PHOTO_SHARPNESS_SOFT                1ul
-#define PHOTO_SHARPNESS_HARD                2ul
-
-//  Name:     System.Photo.SharpnessText -- PKEY_Photo_SharpnessText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 51EC3F47-DD50-421D-8769-334F50424B1E, 100
-//  
-//  This is the user-friendly form of System.Photo.Sharpness.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_SharpnessText, 0x51EC3F47, 0xDD50, 0x421D, 0x87, 0x69, 0x33, 0x4F, 0x50, 0x42, 0x4B, 0x1E, 100);
-
-//  Name:     System.Photo.ShutterSpeed -- PKEY_Photo_ShutterSpeed
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37377
-//
-//  PropertyTagExifShutterSpeed.  Calculated from PKEY_Photo_ShutterSpeedNumerator and PKEY_Photo_ShutterSpeedDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_ShutterSpeed, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37377);
-
-//  Name:     System.Photo.ShutterSpeedDenominator -- PKEY_Photo_ShutterSpeedDenominator
-//  Type:     Int32 -- VT_I4
-//  FormatID: E13D8975-81C7-4948-AE3F-37CAE11E8FF7, 100
-//
-//  Denominator of PKEY_Photo_ShutterSpeed
-DEFINE_PROPERTYKEY(PKEY_Photo_ShutterSpeedDenominator, 0xE13D8975, 0x81C7, 0x4948, 0xAE, 0x3F, 0x37, 0xCA, 0xE1, 0x1E, 0x8F, 0xF7, 100);
-
-//  Name:     System.Photo.ShutterSpeedNumerator -- PKEY_Photo_ShutterSpeedNumerator
-//  Type:     Int32 -- VT_I4
-//  FormatID: 16EA4042-D6F4-4BCA-8349-7C78D30FB333, 100
-//
-//  Numerator of PKEY_Photo_ShutterSpeed
-DEFINE_PROPERTYKEY(PKEY_Photo_ShutterSpeedNumerator, 0x16EA4042, 0xD6F4, 0x4BCA, 0x83, 0x49, 0x7C, 0x78, 0xD3, 0x0F, 0xB3, 0x33, 100);
-
-//  Name:     System.Photo.SubjectDistance -- PKEY_Photo_SubjectDistance
-//  Type:     Double -- VT_R8
-//  FormatID: (FMTID_ImageProperties) 14B81DA1-0135-4D31-96D9-6CBFC9671A99, 37382
-//
-//  PropertyTagExifSubjectDist.  Calculated from PKEY_Photo_SubjectDistanceNumerator and PKEY_Photo_SubjectDistanceDenominator
-DEFINE_PROPERTYKEY(PKEY_Photo_SubjectDistance, 0x14B81DA1, 0x0135, 0x4D31, 0x96, 0xD9, 0x6C, 0xBF, 0xC9, 0x67, 0x1A, 0x99, 37382);
-
-//  Name:     System.Photo.SubjectDistanceDenominator -- PKEY_Photo_SubjectDistanceDenominator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 0C840A88-B043-466D-9766-D4B26DA3FA77, 100
-//
-//  Denominator of PKEY_Photo_SubjectDistance
-DEFINE_PROPERTYKEY(PKEY_Photo_SubjectDistanceDenominator, 0x0C840A88, 0xB043, 0x466D, 0x97, 0x66, 0xD4, 0xB2, 0x6D, 0xA3, 0xFA, 0x77, 100);
-
-//  Name:     System.Photo.SubjectDistanceNumerator -- PKEY_Photo_SubjectDistanceNumerator
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 8AF4961C-F526-43E5-AA81-DB768219178D, 100
-//
-//  Numerator of PKEY_Photo_SubjectDistance
-DEFINE_PROPERTYKEY(PKEY_Photo_SubjectDistanceNumerator, 0x8AF4961C, 0xF526, 0x43E5, 0xAA, 0x81, 0xDB, 0x76, 0x82, 0x19, 0x17, 0x8D, 100);
-
-//  Name:     System.Photo.TranscodedForSync -- PKEY_Photo_TranscodedForSync
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 9A8EBB75-6458-4E82-BACB-35C0095B03BB, 100
-DEFINE_PROPERTYKEY(PKEY_Photo_TranscodedForSync, 0x9A8EBB75, 0x6458, 0x4E82, 0xBA, 0xCB, 0x35, 0xC0, 0x09, 0x5B, 0x03, 0xBB, 100);
-
-//  Name:     System.Photo.WhiteBalance -- PKEY_Photo_WhiteBalance
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: EE3D3D8A-5381-4CFA-B13B-AAF66B5F4EC9, 100
-//  
-//  This indicates the white balance mode set when the image was shot.
-DEFINE_PROPERTYKEY(PKEY_Photo_WhiteBalance, 0xEE3D3D8A, 0x5381, 0x4CFA, 0xB1, 0x3B, 0xAA, 0xF6, 0x6B, 0x5F, 0x4E, 0xC9, 100);
-
-// Possible discrete values for PKEY_Photo_WhiteBalance are:
-#define PHOTO_WHITEBALANCE_AUTO             0ul
-#define PHOTO_WHITEBALANCE_MANUAL           1ul
-
-//  Name:     System.Photo.WhiteBalanceText -- PKEY_Photo_WhiteBalanceText
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6336B95E-C7A7-426D-86FD-7AE3D39C84B4, 100
-//  
-//  This is the user-friendly form of System.Photo.WhiteBalance.  Not intended to be parsed 
-//  programmatically.
-DEFINE_PROPERTYKEY(PKEY_Photo_WhiteBalanceText, 0x6336B95E, 0xC7A7, 0x426D, 0x86, 0xFD, 0x7A, 0xE3, 0xD3, 0x9C, 0x84, 0xB4, 100);
- 
-//-----------------------------------------------------------------------------
-// PropGroup properties
-
-//  Name:     System.PropGroup.Advanced -- PKEY_PropGroup_Advanced
-//  Type:     Null -- VT_NULL
-//  FormatID: 900A403B-097B-4B95-8AE2-071FDAEEB118, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Advanced, 0x900A403B, 0x097B, 0x4B95, 0x8A, 0xE2, 0x07, 0x1F, 0xDA, 0xEE, 0xB1, 0x18, 100);
-
-//  Name:     System.PropGroup.Audio -- PKEY_PropGroup_Audio
-//  Type:     Null -- VT_NULL
-//  FormatID: 2804D469-788F-48AA-8570-71B9C187E138, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Audio, 0x2804D469, 0x788F, 0x48AA, 0x85, 0x70, 0x71, 0xB9, 0xC1, 0x87, 0xE1, 0x38, 100);
-
-//  Name:     System.PropGroup.Calendar -- PKEY_PropGroup_Calendar
-//  Type:     Null -- VT_NULL
-//  FormatID: 9973D2B5-BFD8-438A-BA94-5349B293181A, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Calendar, 0x9973D2B5, 0xBFD8, 0x438A, 0xBA, 0x94, 0x53, 0x49, 0xB2, 0x93, 0x18, 0x1A, 100);
-
-//  Name:     System.PropGroup.Camera -- PKEY_PropGroup_Camera
-//  Type:     Null -- VT_NULL
-//  FormatID: DE00DE32-547E-4981-AD4B-542F2E9007D8, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Camera, 0xDE00DE32, 0x547E, 0x4981, 0xAD, 0x4B, 0x54, 0x2F, 0x2E, 0x90, 0x07, 0xD8, 100);
-
-//  Name:     System.PropGroup.Contact -- PKEY_PropGroup_Contact
-//  Type:     Null -- VT_NULL
-//  FormatID: DF975FD3-250A-4004-858F-34E29A3E37AA, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Contact, 0xDF975FD3, 0x250A, 0x4004, 0x85, 0x8F, 0x34, 0xE2, 0x9A, 0x3E, 0x37, 0xAA, 100);
-
-//  Name:     System.PropGroup.Content -- PKEY_PropGroup_Content
-//  Type:     Null -- VT_NULL
-//  FormatID: D0DAB0BA-368A-4050-A882-6C010FD19A4F, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Content, 0xD0DAB0BA, 0x368A, 0x4050, 0xA8, 0x82, 0x6C, 0x01, 0x0F, 0xD1, 0x9A, 0x4F, 100);
-
-//  Name:     System.PropGroup.Description -- PKEY_PropGroup_Description
-//  Type:     Null -- VT_NULL
-//  FormatID: 8969B275-9475-4E00-A887-FF93B8B41E44, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Description, 0x8969B275, 0x9475, 0x4E00, 0xA8, 0x87, 0xFF, 0x93, 0xB8, 0xB4, 0x1E, 0x44, 100);
-
-//  Name:     System.PropGroup.FileSystem -- PKEY_PropGroup_FileSystem
-//  Type:     Null -- VT_NULL
-//  FormatID: E3A7D2C1-80FC-4B40-8F34-30EA111BDC2E, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_FileSystem, 0xE3A7D2C1, 0x80FC, 0x4B40, 0x8F, 0x34, 0x30, 0xEA, 0x11, 0x1B, 0xDC, 0x2E, 100);
-
-//  Name:     System.PropGroup.General -- PKEY_PropGroup_General
-//  Type:     Null -- VT_NULL
-//  FormatID: CC301630-B192-4C22-B372-9F4C6D338E07, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_General, 0xCC301630, 0xB192, 0x4C22, 0xB3, 0x72, 0x9F, 0x4C, 0x6D, 0x33, 0x8E, 0x07, 100);
-
-//  Name:     System.PropGroup.GPS -- PKEY_PropGroup_GPS
-//  Type:     Null -- VT_NULL
-//  FormatID: F3713ADA-90E3-4E11-AAE5-FDC17685B9BE, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_GPS, 0xF3713ADA, 0x90E3, 0x4E11, 0xAA, 0xE5, 0xFD, 0xC1, 0x76, 0x85, 0xB9, 0xBE, 100);
-
-//  Name:     System.PropGroup.Image -- PKEY_PropGroup_Image
-//  Type:     Null -- VT_NULL
-//  FormatID: E3690A87-0FA8-4A2A-9A9F-FCE8827055AC, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Image, 0xE3690A87, 0x0FA8, 0x4A2A, 0x9A, 0x9F, 0xFC, 0xE8, 0x82, 0x70, 0x55, 0xAC, 100);
-
-//  Name:     System.PropGroup.Media -- PKEY_PropGroup_Media
-//  Type:     Null -- VT_NULL
-//  FormatID: 61872CF7-6B5E-4B4B-AC2D-59DA84459248, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Media, 0x61872CF7, 0x6B5E, 0x4B4B, 0xAC, 0x2D, 0x59, 0xDA, 0x84, 0x45, 0x92, 0x48, 100);
-
-//  Name:     System.PropGroup.MediaAdvanced -- PKEY_PropGroup_MediaAdvanced
-//  Type:     Null -- VT_NULL
-//  FormatID: 8859A284-DE7E-4642-99BA-D431D044B1EC, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_MediaAdvanced, 0x8859A284, 0xDE7E, 0x4642, 0x99, 0xBA, 0xD4, 0x31, 0xD0, 0x44, 0xB1, 0xEC, 100);
-
-//  Name:     System.PropGroup.Message -- PKEY_PropGroup_Message
-//  Type:     Null -- VT_NULL
-//  FormatID: 7FD7259D-16B4-4135-9F97-7C96ECD2FA9E, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Message, 0x7FD7259D, 0x16B4, 0x4135, 0x9F, 0x97, 0x7C, 0x96, 0xEC, 0xD2, 0xFA, 0x9E, 100);
-
-//  Name:     System.PropGroup.Music -- PKEY_PropGroup_Music
-//  Type:     Null -- VT_NULL
-//  FormatID: 68DD6094-7216-40F1-A029-43FE7127043F, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Music, 0x68DD6094, 0x7216, 0x40F1, 0xA0, 0x29, 0x43, 0xFE, 0x71, 0x27, 0x04, 0x3F, 100);
-
-//  Name:     System.PropGroup.Origin -- PKEY_PropGroup_Origin
-//  Type:     Null -- VT_NULL
-//  FormatID: 2598D2FB-5569-4367-95DF-5CD3A177E1A5, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Origin, 0x2598D2FB, 0x5569, 0x4367, 0x95, 0xDF, 0x5C, 0xD3, 0xA1, 0x77, 0xE1, 0xA5, 100);
-
-//  Name:     System.PropGroup.PhotoAdvanced -- PKEY_PropGroup_PhotoAdvanced
-//  Type:     Null -- VT_NULL
-//  FormatID: 0CB2BF5A-9EE7-4A86-8222-F01E07FDADAF, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_PhotoAdvanced, 0x0CB2BF5A, 0x9EE7, 0x4A86, 0x82, 0x22, 0xF0, 0x1E, 0x07, 0xFD, 0xAD, 0xAF, 100);
-
-//  Name:     System.PropGroup.RecordedTV -- PKEY_PropGroup_RecordedTV
-//  Type:     Null -- VT_NULL
-//  FormatID: E7B33238-6584-4170-A5C0-AC25EFD9DA56, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_RecordedTV, 0xE7B33238, 0x6584, 0x4170, 0xA5, 0xC0, 0xAC, 0x25, 0xEF, 0xD9, 0xDA, 0x56, 100);
-
-//  Name:     System.PropGroup.Video -- PKEY_PropGroup_Video
-//  Type:     Null -- VT_NULL
-//  FormatID: BEBE0920-7671-4C54-A3EB-49FDDFC191EE, 100
-DEFINE_PROPERTYKEY(PKEY_PropGroup_Video, 0xBEBE0920, 0x7671, 0x4C54, 0xA3, 0xEB, 0x49, 0xFD, 0xDF, 0xC1, 0x91, 0xEE, 100);
- 
-//-----------------------------------------------------------------------------
-// PropList properties
-
-
-
-//  Name:     System.PropList.ConflictPrompt -- PKEY_PropList_ConflictPrompt
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 11
-//  
-//  The list of properties to show in the file operation conflict resolution dialog. Properties with empty 
-//  values will not be displayed. Register under the regvalue of "ConflictPrompt".
-DEFINE_PROPERTYKEY(PKEY_PropList_ConflictPrompt, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 11);
-
-//  Name:     System.PropList.ExtendedTileInfo -- PKEY_PropList_ExtendedTileInfo
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 9
-//  
-//  The list of properties to show in the listview on extended tiles. Register under the regvalue of 
-//  "ExtendedTileInfo".
-DEFINE_PROPERTYKEY(PKEY_PropList_ExtendedTileInfo, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 9);
-
-//  Name:     System.PropList.FileOperationPrompt -- PKEY_PropList_FileOperationPrompt
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 10
-//  
-//  The list of properties to show in the file operation confirmation dialog. Properties with empty values 
-//  will not be displayed. If this list is not specified, then the InfoTip property list is used instead. 
-//  Register under the regvalue of "FileOperationPrompt".
-DEFINE_PROPERTYKEY(PKEY_PropList_FileOperationPrompt, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 10);
-
-//  Name:     System.PropList.FullDetails -- PKEY_PropList_FullDetails
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 2
-//  
-//  The list of all the properties to show in the details page.  Property groups can be included in this list 
-//  in order to more easily organize the UI.  Register under the regvalue of "FullDetails".
-DEFINE_PROPERTYKEY(PKEY_PropList_FullDetails, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 2);
-
-//  Name:     System.PropList.InfoTip -- PKEY_PropList_InfoTip
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 4 (PID_PROPLIST_INFOTIP)
-//  
-//  The list of properties to show in the infotip. Properties with empty values will not be displayed. Register 
-//  under the regvalue of "InfoTip".
-DEFINE_PROPERTYKEY(PKEY_PropList_InfoTip, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 4);
-
-//  Name:     System.PropList.NonPersonal -- PKEY_PropList_NonPersonal
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 49D1091F-082E-493F-B23F-D2308AA9668C, 100
-//  
-//  The list of properties that are considered 'non-personal'. When told to remove all non-personal properties 
-//  from a given file, the system will leave these particular properties untouched. Register under the regvalue 
-//  of "NonPersonal".
-DEFINE_PROPERTYKEY(PKEY_PropList_NonPersonal, 0x49D1091F, 0x082E, 0x493F, 0xB2, 0x3F, 0xD2, 0x30, 0x8A, 0xA9, 0x66, 0x8C, 100);
-
-//  Name:     System.PropList.PreviewDetails -- PKEY_PropList_PreviewDetails
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 8
-//
-//  The list of properties to display in the preview pane.  Register under the regvalue of "PreviewDetails".
-DEFINE_PROPERTYKEY(PKEY_PropList_PreviewDetails, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 8);
-
-//  Name:     System.PropList.PreviewTitle -- PKEY_PropList_PreviewTitle
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 6
-//  
-//  The one or two properties to display in the preview pane title section.  The optional second property is 
-//  displayed as a subtitle.  Register under the regvalue of "PreviewTitle".
-DEFINE_PROPERTYKEY(PKEY_PropList_PreviewTitle, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 6);
-
-//  Name:     System.PropList.QuickTip -- PKEY_PropList_QuickTip
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 5 (PID_PROPLIST_QUICKTIP)
-//  
-//  The list of properties to show in the infotip when the item is on a slow network. Properties with empty 
-//  values will not be displayed. Register under the regvalue of "QuickTip".
-DEFINE_PROPERTYKEY(PKEY_PropList_QuickTip, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 5);
-
-//  Name:     System.PropList.TileInfo -- PKEY_PropList_TileInfo
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: C9944A21-A406-48FE-8225-AEC7E24C211B, 3 (PID_PROPLIST_TILEINFO)
-//  
-//  The list of properties to show in the listview on tiles. Register under the regvalue of "TileInfo".
-DEFINE_PROPERTYKEY(PKEY_PropList_TileInfo, 0xC9944A21, 0xA406, 0x48FE, 0x82, 0x25, 0xAE, 0xC7, 0xE2, 0x4C, 0x21, 0x1B, 3);
-
-//  Name:     System.PropList.XPDetailsPanel -- PKEY_PropList_XPDetailsPanel
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_WebView) F2275480-F782-4291-BD94-F13693513AEC, 0 (PID_DISPLAY_PROPERTIES)
-//
-//  The list of properties to display in the XP webview details panel. Obsolete.
-DEFINE_PROPERTYKEY(PKEY_PropList_XPDetailsPanel, 0xF2275480, 0xF782, 0x4291, 0xBD, 0x94, 0xF1, 0x36, 0x93, 0x51, 0x3A, 0xEC, 0);
- 
-//-----------------------------------------------------------------------------
-// RecordedTV properties
-
-
-
-//  Name:     System.RecordedTV.ChannelNumber -- PKEY_RecordedTV_ChannelNumber
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 7
-//
-//  Example: 42
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_ChannelNumber, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 7);
-
-//  Name:     System.RecordedTV.Credits -- PKEY_RecordedTV_Credits
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 4
-//
-//  Example: "Don Messick/Frank Welker/Casey Kasem/Heather North/Nicole Jaffe;;;"
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_Credits, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 4);
-
-//  Name:     System.RecordedTV.DateContentExpires -- PKEY_RecordedTV_DateContentExpires
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 15
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_DateContentExpires, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 15);
-
-//  Name:     System.RecordedTV.EpisodeName -- PKEY_RecordedTV_EpisodeName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 2
-//
-//  Example: "Nowhere to Hyde"
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_EpisodeName, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 2);
-
-//  Name:     System.RecordedTV.IsATSCContent -- PKEY_RecordedTV_IsATSCContent
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 16
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_IsATSCContent, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 16);
-
-//  Name:     System.RecordedTV.IsClosedCaptioningAvailable -- PKEY_RecordedTV_IsClosedCaptioningAvailable
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 12
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_IsClosedCaptioningAvailable, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 12);
-
-//  Name:     System.RecordedTV.IsDTVContent -- PKEY_RecordedTV_IsDTVContent
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 17
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_IsDTVContent, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 17);
-
-//  Name:     System.RecordedTV.IsHDContent -- PKEY_RecordedTV_IsHDContent
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 18
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_IsHDContent, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 18);
-
-//  Name:     System.RecordedTV.IsRepeatBroadcast -- PKEY_RecordedTV_IsRepeatBroadcast
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 13
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_IsRepeatBroadcast, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 13);
-
-//  Name:     System.RecordedTV.IsSAP -- PKEY_RecordedTV_IsSAP
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 14
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_IsSAP, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 14);
-
-//  Name:     System.RecordedTV.NetworkAffiliation -- PKEY_RecordedTV_NetworkAffiliation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 2C53C813-FB63-4E22-A1AB-0B331CA1E273, 100
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_NetworkAffiliation, 0x2C53C813, 0xFB63, 0x4E22, 0xA1, 0xAB, 0x0B, 0x33, 0x1C, 0xA1, 0xE2, 0x73, 100);
-
-//  Name:     System.RecordedTV.OriginalBroadcastDate -- PKEY_RecordedTV_OriginalBroadcastDate
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 4684FE97-8765-4842-9C13-F006447B178C, 100
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_OriginalBroadcastDate, 0x4684FE97, 0x8765, 0x4842, 0x9C, 0x13, 0xF0, 0x06, 0x44, 0x7B, 0x17, 0x8C, 100);
-
-//  Name:     System.RecordedTV.ProgramDescription -- PKEY_RecordedTV_ProgramDescription
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 3
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_ProgramDescription, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 3);
-
-//  Name:     System.RecordedTV.RecordingTime -- PKEY_RecordedTV_RecordingTime
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: A5477F61-7A82-4ECA-9DDE-98B69B2479B3, 100
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_RecordingTime, 0xA5477F61, 0x7A82, 0x4ECA, 0x9D, 0xDE, 0x98, 0xB6, 0x9B, 0x24, 0x79, 0xB3, 100);
-
-//  Name:     System.RecordedTV.StationCallSign -- PKEY_RecordedTV_StationCallSign
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 6D748DE2-8D38-4CC3-AC60-F009B057C557, 5
-//
-//  Example: "TOONP"
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_StationCallSign, 0x6D748DE2, 0x8D38, 0x4CC3, 0xAC, 0x60, 0xF0, 0x09, 0xB0, 0x57, 0xC5, 0x57, 5);
-
-//  Name:     System.RecordedTV.StationName -- PKEY_RecordedTV_StationName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 1B5439E7-EBA1-4AF8-BDD7-7AF1D4549493, 100
-DEFINE_PROPERTYKEY(PKEY_RecordedTV_StationName, 0x1B5439E7, 0xEBA1, 0x4AF8, 0xBD, 0xD7, 0x7A, 0xF1, 0xD4, 0x54, 0x94, 0x93, 100);
- 
-//-----------------------------------------------------------------------------
-// Search properties
-
-
-
-//  Name:     System.Search.AutoSummary -- PKEY_Search_AutoSummary
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 560C36C0-503A-11CF-BAA1-00004C752A9A, 2
-//
-//  General Summary of the document.
-DEFINE_PROPERTYKEY(PKEY_Search_AutoSummary, 0x560C36C0, 0x503A, 0x11CF, 0xBA, 0xA1, 0x00, 0x00, 0x4C, 0x75, 0x2A, 0x9A, 2);
-
-//  Name:     System.Search.ContainerHash -- PKEY_Search_ContainerHash
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: BCEEE283-35DF-4D53-826A-F36A3EEFC6BE, 100
-//
-//  Hash code used to identify attachments to be deleted based on a common container url
-DEFINE_PROPERTYKEY(PKEY_Search_ContainerHash, 0xBCEEE283, 0x35DF, 0x4D53, 0x82, 0x6A, 0xF3, 0x6A, 0x3E, 0xEF, 0xC6, 0xBE, 100);
-
-//  Name:     System.Search.Contents -- PKEY_Search_Contents
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Storage) B725F130-47EF-101A-A5F1-02608C9EEBAC, 19 (PID_STG_CONTENTS)
-//  
-//  The contents of the item. This property is for query restrictions only; it cannot be retrieved in a 
-//  query result. The Indexing Service friendly name is 'contents'.
-DEFINE_PROPERTYKEY(PKEY_Search_Contents, 0xB725F130, 0x47EF, 0x101A, 0xA5, 0xF1, 0x02, 0x60, 0x8C, 0x9E, 0xEB, 0xAC, 19);
-
-//  Name:     System.Search.EntryID -- PKEY_Search_EntryID
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_Query) 49691C90-7E17-101A-A91C-08002B2ECDA9, 5 (PROPID_QUERY_WORKID)
-//  
-//  The entry ID for an item within a given catalog in the Windows Search Index.
-//  This value may be recycled, and therefore is not considered unique over time.
-DEFINE_PROPERTYKEY(PKEY_Search_EntryID, 0x49691C90, 0x7E17, 0x101A, 0xA9, 0x1C, 0x08, 0x00, 0x2B, 0x2E, 0xCD, 0xA9, 5);
-
-//  Name:     System.Search.GatherTime -- PKEY_Search_GatherTime
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 0B63E350-9CCC-11D0-BCDB-00805FCCCE04, 8
-//
-//  The Datetime that the Windows Search Gatherer process last pushed properties of this document to the Windows Search Gatherer Plugins.
-DEFINE_PROPERTYKEY(PKEY_Search_GatherTime, 0x0B63E350, 0x9CCC, 0x11D0, 0xBC, 0xDB, 0x00, 0x80, 0x5F, 0xCC, 0xCE, 0x04, 8);
-
-//  Name:     System.Search.IsClosedDirectory -- PKEY_Search_IsClosedDirectory
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 0B63E343-9CCC-11D0-BCDB-00805FCCCE04, 23
-//
-//  If this property is emitted with a value of TRUE, then it indicates that this URL's last modified time applies to all of it's children, and if this URL is deleted then all of it's children are deleted as well.  For example, this would be emitted as TRUE when emitting the URL of an email so that all attachments are tied to the last modified time of that email.
-DEFINE_PROPERTYKEY(PKEY_Search_IsClosedDirectory, 0x0B63E343, 0x9CCC, 0x11D0, 0xBC, 0xDB, 0x00, 0x80, 0x5F, 0xCC, 0xCE, 0x04, 23);
-
-//  Name:     System.Search.IsFullyContained -- PKEY_Search_IsFullyContained
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 0B63E343-9CCC-11D0-BCDB-00805FCCCE04, 24
-//
-//  Any child URL of a URL which has System.Search.IsClosedDirectory=TRUE must emit System.Search.IsFullyContained=TRUE.  This ensures that the URL is not deleted at the end of a crawl because it hasn't been visited (which is the normal mechanism for detecting deletes).  For example an email attachment would emit this property
-DEFINE_PROPERTYKEY(PKEY_Search_IsFullyContained, 0x0B63E343, 0x9CCC, 0x11D0, 0xBC, 0xDB, 0x00, 0x80, 0x5F, 0xCC, 0xCE, 0x04, 24);
-
-//  Name:     System.Search.QueryFocusedSummary -- PKEY_Search_QueryFocusedSummary
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 560C36C0-503A-11CF-BAA1-00004C752A9A, 3
-//
-//  Query Focused Summary of the document.
-DEFINE_PROPERTYKEY(PKEY_Search_QueryFocusedSummary, 0x560C36C0, 0x503A, 0x11CF, 0xBA, 0xA1, 0x00, 0x00, 0x4C, 0x75, 0x2A, 0x9A, 3);
-
-//  Name:     System.Search.Rank -- PKEY_Search_Rank
-//  Type:     Int32 -- VT_I4
-//  FormatID: (FMTID_Query) 49691C90-7E17-101A-A91C-08002B2ECDA9, 3 (PROPID_QUERY_RANK)
-//  
-//  Relevance rank of row. Ranges from 0-1000. Larger numbers = better matches.  Query-time only, not 
-//  defined in Search schema, retrievable but not searchable.
-DEFINE_PROPERTYKEY(PKEY_Search_Rank, 0x49691C90, 0x7E17, 0x101A, 0xA9, 0x1C, 0x08, 0x00, 0x2B, 0x2E, 0xCD, 0xA9, 3);
-
-//  Name:     System.Search.Store -- PKEY_Search_Store
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: A06992B3-8CAF-4ED7-A547-B259E32AC9FC, 100
-//
-//  The identifier for the protocol handler that produced this item. (E.g. MAPI, CSC, FILE etc.)
-DEFINE_PROPERTYKEY(PKEY_Search_Store, 0xA06992B3, 0x8CAF, 0x4ED7, 0xA5, 0x47, 0xB2, 0x59, 0xE3, 0x2A, 0xC9, 0xFC, 100);
-
-//  Name:     System.Search.UrlToIndex -- PKEY_Search_UrlToIndex
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 0B63E343-9CCC-11D0-BCDB-00805FCCCE04, 2
-//
-//  This property should be emitted by a container IFilter for each child URL within the container.  The children will eventually be crawled by the indexer if they are within scope.
-DEFINE_PROPERTYKEY(PKEY_Search_UrlToIndex, 0x0B63E343, 0x9CCC, 0x11D0, 0xBC, 0xDB, 0x00, 0x80, 0x5F, 0xCC, 0xCE, 0x04, 2);
-
-//  Name:     System.Search.UrlToIndexWithModificationTime -- PKEY_Search_UrlToIndexWithModificationTime
-//  Type:     Multivalue Any -- VT_VECTOR | VT_NULL  (For variants: VT_ARRAY | VT_NULL)
-//  FormatID: 0B63E343-9CCC-11D0-BCDB-00805FCCCE04, 12
-//
-//  This property is the same as System.Search.UrlToIndex except that it includes the time the URL was last modified.  This is an optimization for the indexer as it doesn't have to call back into the protocol handler to ask for this information to determine if the content needs to be indexed again.  The property is a vector with two elements, a VT_LPWSTR with the URL and a VT_FILETIME for the last modified time.
-DEFINE_PROPERTYKEY(PKEY_Search_UrlToIndexWithModificationTime, 0x0B63E343, 0x9CCC, 0x11D0, 0xBC, 0xDB, 0x00, 0x80, 0x5F, 0xCC, 0xCE, 0x04, 12);
- 
-//-----------------------------------------------------------------------------
-// Shell properties
-
-
-
-//  Name:     System.DescriptionID -- PKEY_DescriptionID
-//  Type:     Buffer -- VT_VECTOR | VT_UI1  (For variants: VT_ARRAY | VT_UI1)
-//  FormatID: (FMTID_ShellDetails) 28636AA6-953D-11D2-B5D6-00C04FD918D0, 2 (PID_DESCRIPTIONID)
-//
-//  The contents of a SHDESCRIPTIONID structure as a buffer of bytes.
-DEFINE_PROPERTYKEY(PKEY_DescriptionID, 0x28636AA6, 0x953D, 0x11D2, 0xB5, 0xD6, 0x00, 0xC0, 0x4F, 0xD9, 0x18, 0xD0, 2);
-
-//  Name:     System.Link.TargetSFGAOFlagsStrings -- PKEY_Link_TargetSFGAOFlagsStrings
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D6942081-D53B-443D-AD47-5E059D9CD27A, 3
-//  
-//  Expresses the SFGAO flags of a link as string values and is used as a query optimization.  See 
-//  PKEY_Shell_SFGAOFlagsStrings for possible values of this.
-DEFINE_PROPERTYKEY(PKEY_Link_TargetSFGAOFlagsStrings, 0xD6942081, 0xD53B, 0x443D, 0xAD, 0x47, 0x5E, 0x05, 0x9D, 0x9C, 0xD2, 0x7A, 3);
-
-//  Name:     System.Link.TargetUrl -- PKEY_Link_TargetUrl
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 5CBF2787-48CF-4208-B90E-EE5E5D420294, 2  (PKEYs relating to URLs.  Used by IE History.)
-DEFINE_PROPERTYKEY(PKEY_Link_TargetUrl, 0x5CBF2787, 0x48CF, 0x4208, 0xB9, 0x0E, 0xEE, 0x5E, 0x5D, 0x42, 0x02, 0x94, 2);
-
-//  Name:     System.Shell.SFGAOFlagsStrings -- PKEY_Shell_SFGAOFlagsStrings
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: D6942081-D53B-443D-AD47-5E059D9CD27A, 2
-//
-//  Expresses the SFGAO flags as string values and is used as a query optimization.
-DEFINE_PROPERTYKEY(PKEY_Shell_SFGAOFlagsStrings, 0xD6942081, 0xD53B, 0x443D, 0xAD, 0x47, 0x5E, 0x05, 0x9D, 0x9C, 0xD2, 0x7A, 2);
-
-// Possible discrete values for PKEY_Shell_SFGAOFlagsStrings are:
-#define SFGAOSTR_FILESYS                    L"filesys"               // SFGAO_FILESYSTEM
-#define SFGAOSTR_FILEANC                    L"fileanc"               // SFGAO_FILESYSANCESTOR
-#define SFGAOSTR_STORAGEANC                 L"storageanc"               // SFGAO_STORAGEANCESTOR
-#define SFGAOSTR_STREAM                     L"stream"               // SFGAO_STREAM
-#define SFGAOSTR_LINK                       L"link"               // SFGAO_LINK
-#define SFGAOSTR_HIDDEN                     L"hidden"               // SFGAO_HIDDEN
-#define SFGAOSTR_FOLDER                     L"folder"               // SFGAO_FOLDER
-#define SFGAOSTR_NONENUM                    L"nonenum"               // SFGAO_NONENUMERATED
-#define SFGAOSTR_BROWSABLE                  L"browsable"               // SFGAO_BROWSABLE
- 
-//-----------------------------------------------------------------------------
-// Software properties
-
-
-
-//  Name:     System.Software.DateLastUsed -- PKEY_Software_DateLastUsed
-//  Type:     DateTime -- VT_FILETIME  (For variants: VT_DATE)
-//  FormatID: 841E4F90-FF59-4D16-8947-E81BBFFAB36D, 16
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Software_DateLastUsed, 0x841E4F90, 0xFF59, 0x4D16, 0x89, 0x47, 0xE8, 0x1B, 0xBF, 0xFA, 0xB3, 0x6D, 16);
-
-//  Name:     System.Software.ProductName -- PKEY_Software_ProductName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (PSFMTID_VERSION) 0CEF7D53-FA64-11D1-A203-0000F81FEDEE, 7
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Software_ProductName, 0x0CEF7D53, 0xFA64, 0x11D1, 0xA2, 0x03, 0x00, 0x00, 0xF8, 0x1F, 0xED, 0xEE, 7);
- 
-//-----------------------------------------------------------------------------
-// Sync properties
-
-
-
-//  Name:     System.Sync.Comments -- PKEY_Sync_Comments
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7BD5533E-AF15-44DB-B8C8-BD6624E1D032, 13
-DEFINE_PROPERTYKEY(PKEY_Sync_Comments, 0x7BD5533E, 0xAF15, 0x44DB, 0xB8, 0xC8, 0xBD, 0x66, 0x24, 0xE1, 0xD0, 0x32, 13);
-
-//  Name:     System.Sync.ConflictDescription -- PKEY_Sync_ConflictDescription
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CE50C159-2FB8-41FD-BE68-D3E042E274BC, 4
-DEFINE_PROPERTYKEY(PKEY_Sync_ConflictDescription, 0xCE50C159, 0x2FB8, 0x41FD, 0xBE, 0x68, 0xD3, 0xE0, 0x42, 0xE2, 0x74, 0xBC, 4);
-
-//  Name:     System.Sync.ConflictFirstLocation -- PKEY_Sync_ConflictFirstLocation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CE50C159-2FB8-41FD-BE68-D3E042E274BC, 6
-DEFINE_PROPERTYKEY(PKEY_Sync_ConflictFirstLocation, 0xCE50C159, 0x2FB8, 0x41FD, 0xBE, 0x68, 0xD3, 0xE0, 0x42, 0xE2, 0x74, 0xBC, 6);
-
-//  Name:     System.Sync.ConflictSecondLocation -- PKEY_Sync_ConflictSecondLocation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CE50C159-2FB8-41FD-BE68-D3E042E274BC, 7
-DEFINE_PROPERTYKEY(PKEY_Sync_ConflictSecondLocation, 0xCE50C159, 0x2FB8, 0x41FD, 0xBE, 0x68, 0xD3, 0xE0, 0x42, 0xE2, 0x74, 0xBC, 7);
-
-//  Name:     System.Sync.HandlerCollectionID -- PKEY_Sync_HandlerCollectionID
-//  Type:     Guid -- VT_CLSID
-//  FormatID: 7BD5533E-AF15-44DB-B8C8-BD6624E1D032, 2
-DEFINE_PROPERTYKEY(PKEY_Sync_HandlerCollectionID, 0x7BD5533E, 0xAF15, 0x44DB, 0xB8, 0xC8, 0xBD, 0x66, 0x24, 0xE1, 0xD0, 0x32, 2);
-
-//  Name:     System.Sync.HandlerID -- PKEY_Sync_HandlerID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7BD5533E-AF15-44DB-B8C8-BD6624E1D032, 3
-DEFINE_PROPERTYKEY(PKEY_Sync_HandlerID, 0x7BD5533E, 0xAF15, 0x44DB, 0xB8, 0xC8, 0xBD, 0x66, 0x24, 0xE1, 0xD0, 0x32, 3);
-
-//  Name:     System.Sync.HandlerName -- PKEY_Sync_HandlerName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CE50C159-2FB8-41FD-BE68-D3E042E274BC, 2
-DEFINE_PROPERTYKEY(PKEY_Sync_HandlerName, 0xCE50C159, 0x2FB8, 0x41FD, 0xBE, 0x68, 0xD3, 0xE0, 0x42, 0xE2, 0x74, 0xBC, 2);
-
-//  Name:     System.Sync.HandlerType -- PKEY_Sync_HandlerType
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: 7BD5533E-AF15-44DB-B8C8-BD6624E1D032, 8
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Sync_HandlerType, 0x7BD5533E, 0xAF15, 0x44DB, 0xB8, 0xC8, 0xBD, 0x66, 0x24, 0xE1, 0xD0, 0x32, 8);
-
-// Possible discrete values for PKEY_Sync_HandlerType are:
-#define SYNC_HANDLERTYPE_OTHER              0ul
-#define SYNC_HANDLERTYPE_PROGRAMS           1ul
-#define SYNC_HANDLERTYPE_DEVICES            2ul
-#define SYNC_HANDLERTYPE_FOLDERS            3ul
-#define SYNC_HANDLERTYPE_WEBSERVICES        4ul
-#define SYNC_HANDLERTYPE_COMPUTERS          5ul
-
-//  Name:     System.Sync.HandlerTypeLabel -- PKEY_Sync_HandlerTypeLabel
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7BD5533E-AF15-44DB-B8C8-BD6624E1D032, 9
-//  
-//  
-DEFINE_PROPERTYKEY(PKEY_Sync_HandlerTypeLabel, 0x7BD5533E, 0xAF15, 0x44DB, 0xB8, 0xC8, 0xBD, 0x66, 0x24, 0xE1, 0xD0, 0x32, 9);
-
-//  Name:     System.Sync.ItemID -- PKEY_Sync_ItemID
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 7BD5533E-AF15-44DB-B8C8-BD6624E1D032, 6
-DEFINE_PROPERTYKEY(PKEY_Sync_ItemID, 0x7BD5533E, 0xAF15, 0x44DB, 0xB8, 0xC8, 0xBD, 0x66, 0x24, 0xE1, 0xD0, 0x32, 6);
-
-//  Name:     System.Sync.ItemName -- PKEY_Sync_ItemName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: CE50C159-2FB8-41FD-BE68-D3E042E274BC, 3
-DEFINE_PROPERTYKEY(PKEY_Sync_ItemName, 0xCE50C159, 0x2FB8, 0x41FD, 0xBE, 0x68, 0xD3, 0xE0, 0x42, 0xE2, 0x74, 0xBC, 3);
- 
-//-----------------------------------------------------------------------------
-// Task properties
-
-//  Name:     System.Task.BillingInformation -- PKEY_Task_BillingInformation
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: D37D52C6-261C-4303-82B3-08B926AC6F12, 100
-DEFINE_PROPERTYKEY(PKEY_Task_BillingInformation, 0xD37D52C6, 0x261C, 0x4303, 0x82, 0xB3, 0x08, 0xB9, 0x26, 0xAC, 0x6F, 0x12, 100);
-
-//  Name:     System.Task.CompletionStatus -- PKEY_Task_CompletionStatus
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 084D8A0A-E6D5-40DE-BF1F-C8820E7C877C, 100
-DEFINE_PROPERTYKEY(PKEY_Task_CompletionStatus, 0x084D8A0A, 0xE6D5, 0x40DE, 0xBF, 0x1F, 0xC8, 0x82, 0x0E, 0x7C, 0x87, 0x7C, 100);
-
-//  Name:     System.Task.Owner -- PKEY_Task_Owner
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: 08C7CC5F-60F2-4494-AD75-55E3E0B5ADD0, 100
-DEFINE_PROPERTYKEY(PKEY_Task_Owner, 0x08C7CC5F, 0x60F2, 0x4494, 0xAD, 0x75, 0x55, 0xE3, 0xE0, 0xB5, 0xAD, 0xD0, 100);
-
- 
- 
-//-----------------------------------------------------------------------------
-// Video properties
-
-//  Name:     System.Video.Compression -- PKEY_Video_Compression
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 10 (PIDVSI_COMPRESSION)
-//
-//  Indicates the level of compression for the video stream.  "Compression".
-DEFINE_PROPERTYKEY(PKEY_Video_Compression, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 10);
-
-//  Name:     System.Video.Director -- PKEY_Video_Director
-//  Type:     Multivalue String -- VT_VECTOR | VT_LPWSTR  (For variants: VT_ARRAY | VT_BSTR)
-//  FormatID: (PSGUID_MEDIAFILESUMMARYINFORMATION) 64440492-4C8B-11D1-8B70-080036B11A03, 20 (PIDMSI_DIRECTOR)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Video_Director, 0x64440492, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 20);
-
-//  Name:     System.Video.EncodingBitrate -- PKEY_Video_EncodingBitrate
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 8 (PIDVSI_DATA_RATE)
-//
-//  Indicates the data rate in "bits per second" for the video stream. "DataRate".
-DEFINE_PROPERTYKEY(PKEY_Video_EncodingBitrate, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 8);
-
-//  Name:     System.Video.FourCC -- PKEY_Video_FourCC
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 44
-//  
-//  Indicates the 4CC for the video stream.
-DEFINE_PROPERTYKEY(PKEY_Video_FourCC, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 44);
-
-//  Name:     System.Video.FrameHeight -- PKEY_Video_FrameHeight
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 4
-//
-//  Indicates the frame height for the video stream.
-DEFINE_PROPERTYKEY(PKEY_Video_FrameHeight, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 4);
-
-//  Name:     System.Video.FrameRate -- PKEY_Video_FrameRate
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 6 (PIDVSI_FRAME_RATE)
-//
-//  Indicates the frame rate in "frames per millisecond" for the video stream.  "FrameRate".
-DEFINE_PROPERTYKEY(PKEY_Video_FrameRate, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 6);
-
-//  Name:     System.Video.FrameWidth -- PKEY_Video_FrameWidth
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 3
-//
-//  Indicates the frame width for the video stream.
-DEFINE_PROPERTYKEY(PKEY_Video_FrameWidth, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 3);
-
-//  Name:     System.Video.HorizontalAspectRatio -- PKEY_Video_HorizontalAspectRatio
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 42
-//  
-//  Indicates the horizontal portion of the aspect ratio. The X portion of XX:YY,
-//  like 16:9.
-DEFINE_PROPERTYKEY(PKEY_Video_HorizontalAspectRatio, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 42);
-
-//  Name:     System.Video.SampleSize -- PKEY_Video_SampleSize
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 9 (PIDVSI_SAMPLE_SIZE)
-//
-//  Indicates the sample size in bits for the video stream.  "SampleSize".
-DEFINE_PROPERTYKEY(PKEY_Video_SampleSize, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 9);
-
-//  Name:     System.Video.StreamName -- PKEY_Video_StreamName
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 2 (PIDVSI_STREAM_NAME)
-//
-//  Indicates the name for the video stream. "StreamName".
-DEFINE_PROPERTYKEY(PKEY_Video_StreamName, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 2);
-
-//  Name:     System.Video.StreamNumber -- PKEY_Video_StreamNumber
-//  Type:     UInt16 -- VT_UI2
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 11 (PIDVSI_STREAM_NUMBER)
-//
-//  "Stream Number".
-DEFINE_PROPERTYKEY(PKEY_Video_StreamNumber, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 11);
-
-//  Name:     System.Video.TotalBitrate -- PKEY_Video_TotalBitrate
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 43 (PIDVSI_TOTAL_BITRATE)
-//
-//  Indicates the total data rate in "bits per second" for all video and audio streams.
-DEFINE_PROPERTYKEY(PKEY_Video_TotalBitrate, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 43);
-
-//  Name:     System.Video.VerticalAspectRatio -- PKEY_Video_VerticalAspectRatio
-//  Type:     UInt32 -- VT_UI4
-//  FormatID: (FMTID_VideoSummaryInformation) 64440491-4C8B-11D1-8B70-080036B11A03, 45
-//  
-//  Indicates the vertical portion of the aspect ratio. The Y portion of 
-//  XX:YY, like 16:9.
-DEFINE_PROPERTYKEY(PKEY_Video_VerticalAspectRatio, 0x64440491, 0x4C8B, 0x11D1, 0x8B, 0x70, 0x08, 0x00, 0x36, 0xB1, 0x1A, 0x03, 45);
-
- 
- 
-//-----------------------------------------------------------------------------
-// Volume properties
-
-//  Name:     System.Volume.FileSystem -- PKEY_Volume_FileSystem
-//  Type:     String -- VT_LPWSTR  (For variants: VT_BSTR)
-//  FormatID: (FMTID_Volume) 9B174B35-40FF-11D2-A27E-00C04FC30871, 4 (PID_VOLUME_FILESYSTEM)  (Filesystem Volume Properties)
-//
-//  Indicates the filesystem of the volume.
-DEFINE_PROPERTYKEY(PKEY_Volume_FileSystem, 0x9B174B35, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 4);
-
-//  Name:     System.Volume.IsMappedDrive -- PKEY_Volume_IsMappedDrive
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: 149C0B69-2C2D-48FC-808F-D318D78C4636, 2
-DEFINE_PROPERTYKEY(PKEY_Volume_IsMappedDrive, 0x149C0B69, 0x2C2D, 0x48FC, 0x80, 0x8F, 0xD3, 0x18, 0xD7, 0x8C, 0x46, 0x36, 2);
-
-//  Name:     System.Volume.IsRoot -- PKEY_Volume_IsRoot
-//  Type:     Boolean -- VT_BOOL
-//  FormatID: (FMTID_Volume) 9B174B35-40FF-11D2-A27E-00C04FC30871, 10  (Filesystem Volume Properties)
-//
-//  
-DEFINE_PROPERTYKEY(PKEY_Volume_IsRoot, 0x9B174B35, 0x40FF, 0x11D2, 0xA2, 0x7E, 0x00, 0xC0, 0x4F, 0xC3, 0x08, 0x71, 10);
-
-#endif  /* _INC_PROPKEY */
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/propkeydef.h b/portaudio/src/hostapi/wasapi/mingw-include/propkeydef.h
deleted file mode 100644
index 65fcb8779..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/propkeydef.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#ifndef PID_FIRST_USABLE
-#define PID_FIRST_USABLE 2
-#endif
-
-#ifndef REFPROPERTYKEY
-#ifdef __cplusplus
-#define REFPROPERTYKEY const PROPERTYKEY &
-#else // !__cplusplus
-#define REFPROPERTYKEY const PROPERTYKEY * __MIDL_CONST
-#endif // __cplusplus
-#endif //REFPROPERTYKEY
-
-#ifdef DEFINE_PROPERTYKEY
-#undef DEFINE_PROPERTYKEY
-#endif
-
-#ifdef INITGUID
-#define DEFINE_PROPERTYKEY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8, pid) EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY name = { { l, w1, w2, { b1, b2,  b3,  b4,  b5,  b6,  b7,  b8 } }, pid }
-#else
-#define DEFINE_PROPERTYKEY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8, pid) EXTERN_C const PROPERTYKEY name
-#endif // INITGUID
-
-#ifndef IsEqualPropertyKey
-#define IsEqualPropertyKey(a, b)   (((a).pid == (b).pid) && IsEqualIID((a).fmtid, (b).fmtid) )
-#endif  // IsEqualPropertyKey
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/propsys.h b/portaudio/src/hostapi/wasapi/mingw-include/propsys.h
deleted file mode 100644
index 5c1312c07..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/propsys.h
+++ /dev/null
@@ -1,3605 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for propsys.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 475
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __propsys_h__
-#define __propsys_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-#ifndef __IInitializeWithFile_FWD_DEFINED__
-#define __IInitializeWithFile_FWD_DEFINED__
-typedef interface IInitializeWithFile IInitializeWithFile;
-#endif 	/* __IInitializeWithFile_FWD_DEFINED__ */
-
-
-#ifndef __IInitializeWithStream_FWD_DEFINED__
-#define __IInitializeWithStream_FWD_DEFINED__
-typedef interface IInitializeWithStream IInitializeWithStream;
-#endif 	/* __IInitializeWithStream_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyStore_FWD_DEFINED__
-#define __IPropertyStore_FWD_DEFINED__
-typedef interface IPropertyStore IPropertyStore;
-#endif 	/* __IPropertyStore_FWD_DEFINED__ */
-
-
-#ifndef __INamedPropertyStore_FWD_DEFINED__
-#define __INamedPropertyStore_FWD_DEFINED__
-typedef interface INamedPropertyStore INamedPropertyStore;
-#endif 	/* __INamedPropertyStore_FWD_DEFINED__ */
-
-
-#ifndef __IObjectWithPropertyKey_FWD_DEFINED__
-#define __IObjectWithPropertyKey_FWD_DEFINED__
-typedef interface IObjectWithPropertyKey IObjectWithPropertyKey;
-#endif 	/* __IObjectWithPropertyKey_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyChange_FWD_DEFINED__
-#define __IPropertyChange_FWD_DEFINED__
-typedef interface IPropertyChange IPropertyChange;
-#endif 	/* __IPropertyChange_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyChangeArray_FWD_DEFINED__
-#define __IPropertyChangeArray_FWD_DEFINED__
-typedef interface IPropertyChangeArray IPropertyChangeArray;
-#endif 	/* __IPropertyChangeArray_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyStoreCapabilities_FWD_DEFINED__
-#define __IPropertyStoreCapabilities_FWD_DEFINED__
-typedef interface IPropertyStoreCapabilities IPropertyStoreCapabilities;
-#endif 	/* __IPropertyStoreCapabilities_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyStoreCache_FWD_DEFINED__
-#define __IPropertyStoreCache_FWD_DEFINED__
-typedef interface IPropertyStoreCache IPropertyStoreCache;
-#endif 	/* __IPropertyStoreCache_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyEnumType_FWD_DEFINED__
-#define __IPropertyEnumType_FWD_DEFINED__
-typedef interface IPropertyEnumType IPropertyEnumType;
-#endif 	/* __IPropertyEnumType_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyEnumTypeList_FWD_DEFINED__
-#define __IPropertyEnumTypeList_FWD_DEFINED__
-typedef interface IPropertyEnumTypeList IPropertyEnumTypeList;
-#endif 	/* __IPropertyEnumTypeList_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyDescription_FWD_DEFINED__
-#define __IPropertyDescription_FWD_DEFINED__
-typedef interface IPropertyDescription IPropertyDescription;
-#endif 	/* __IPropertyDescription_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyDescriptionAliasInfo_FWD_DEFINED__
-#define __IPropertyDescriptionAliasInfo_FWD_DEFINED__
-typedef interface IPropertyDescriptionAliasInfo IPropertyDescriptionAliasInfo;
-#endif 	/* __IPropertyDescriptionAliasInfo_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyDescriptionSearchInfo_FWD_DEFINED__
-#define __IPropertyDescriptionSearchInfo_FWD_DEFINED__
-typedef interface IPropertyDescriptionSearchInfo IPropertyDescriptionSearchInfo;
-#endif 	/* __IPropertyDescriptionSearchInfo_FWD_DEFINED__ */
-
-
-#ifndef __IPropertySystem_FWD_DEFINED__
-#define __IPropertySystem_FWD_DEFINED__
-typedef interface IPropertySystem IPropertySystem;
-#endif 	/* __IPropertySystem_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyDescriptionList_FWD_DEFINED__
-#define __IPropertyDescriptionList_FWD_DEFINED__
-typedef interface IPropertyDescriptionList IPropertyDescriptionList;
-#endif 	/* __IPropertyDescriptionList_FWD_DEFINED__ */
-
-
-#ifndef __IPropertyStoreFactory_FWD_DEFINED__
-#define __IPropertyStoreFactory_FWD_DEFINED__
-typedef interface IPropertyStoreFactory IPropertyStoreFactory;
-#endif 	/* __IPropertyStoreFactory_FWD_DEFINED__ */
-
-
-#ifndef __IDelayedPropertyStoreFactory_FWD_DEFINED__
-#define __IDelayedPropertyStoreFactory_FWD_DEFINED__
-typedef interface IDelayedPropertyStoreFactory IDelayedPropertyStoreFactory;
-#endif 	/* __IDelayedPropertyStoreFactory_FWD_DEFINED__ */
-
-
-#ifndef __IPersistSerializedPropStorage_FWD_DEFINED__
-#define __IPersistSerializedPropStorage_FWD_DEFINED__
-typedef interface IPersistSerializedPropStorage IPersistSerializedPropStorage;
-#endif 	/* __IPersistSerializedPropStorage_FWD_DEFINED__ */
-
-
-#ifndef __IPropertySystemChangeNotify_FWD_DEFINED__
-#define __IPropertySystemChangeNotify_FWD_DEFINED__
-typedef interface IPropertySystemChangeNotify IPropertySystemChangeNotify;
-#endif 	/* __IPropertySystemChangeNotify_FWD_DEFINED__ */
-
-
-#ifndef __ICreateObject_FWD_DEFINED__
-#define __ICreateObject_FWD_DEFINED__
-typedef interface ICreateObject ICreateObject;
-#endif 	/* __ICreateObject_FWD_DEFINED__ */
-
-
-#ifndef __InMemoryPropertyStore_FWD_DEFINED__
-#define __InMemoryPropertyStore_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class InMemoryPropertyStore InMemoryPropertyStore;
-#else
-typedef struct InMemoryPropertyStore InMemoryPropertyStore;
-#endif /* __cplusplus */
-
-#endif 	/* __InMemoryPropertyStore_FWD_DEFINED__ */
-
-
-#ifndef __PropertySystem_FWD_DEFINED__
-#define __PropertySystem_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class PropertySystem PropertySystem;
-#else
-typedef struct PropertySystem PropertySystem;
-#endif /* __cplusplus */
-
-#endif 	/* __PropertySystem_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "objidl.h"
-#include "oleidl.h"
-#include "ocidl.h"
-#include "shtypes.h"
-#include "structuredquery.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_propsys_0000_0000 */
-/* [local] */ 
-
-#ifndef PSSTDAPI
-#if defined(_PROPSYS_)
-#define PSSTDAPI          STDAPI
-#define PSSTDAPI_(type)   STDAPI_(type)
-#else
-#define PSSTDAPI          EXTERN_C DECLSPEC_IMPORT HRESULT STDAPICALLTYPE
-#define PSSTDAPI_(type)   EXTERN_C DECLSPEC_IMPORT type STDAPICALLTYPE
-#endif
-#endif // PSSTDAPI
-#if 0
-typedef PROPERTYKEY *REFPROPERTYKEY;
-
-#endif // 0
-#include <propkeydef.h>
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IInitializeWithFile_INTERFACE_DEFINED__
-#define __IInitializeWithFile_INTERFACE_DEFINED__
-
-/* interface IInitializeWithFile */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IInitializeWithFile;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("b7d14566-0509-4cce-a71f-0a554233bd9b")
-    IInitializeWithFile : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Initialize( 
-            /* [string][in] */ __RPC__in LPCWSTR pszFilePath,
-            /* [in] */ DWORD grfMode) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IInitializeWithFileVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IInitializeWithFile * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IInitializeWithFile * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IInitializeWithFile * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Initialize )( 
-            IInitializeWithFile * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszFilePath,
-            /* [in] */ DWORD grfMode);
-        
-        END_INTERFACE
-    } IInitializeWithFileVtbl;
-
-    interface IInitializeWithFile
-    {
-        CONST_VTBL struct IInitializeWithFileVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IInitializeWithFile_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IInitializeWithFile_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IInitializeWithFile_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IInitializeWithFile_Initialize(This,pszFilePath,grfMode)	\
-    ( (This)->lpVtbl -> Initialize(This,pszFilePath,grfMode) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IInitializeWithFile_INTERFACE_DEFINED__ */
-
-
-#ifndef __IInitializeWithStream_INTERFACE_DEFINED__
-#define __IInitializeWithStream_INTERFACE_DEFINED__
-
-/* interface IInitializeWithStream */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IInitializeWithStream;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("b824b49d-22ac-4161-ac8a-9916e8fa3f7f")
-    IInitializeWithStream : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE Initialize( 
-            /* [in] */ IStream *pstream,
-            /* [in] */ DWORD grfMode) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IInitializeWithStreamVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IInitializeWithStream * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IInitializeWithStream * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IInitializeWithStream * This);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Initialize )( 
-            IInitializeWithStream * This,
-            /* [in] */ IStream *pstream,
-            /* [in] */ DWORD grfMode);
-        
-        END_INTERFACE
-    } IInitializeWithStreamVtbl;
-
-    interface IInitializeWithStream
-    {
-        CONST_VTBL struct IInitializeWithStreamVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IInitializeWithStream_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IInitializeWithStream_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IInitializeWithStream_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IInitializeWithStream_Initialize(This,pstream,grfMode)	\
-    ( (This)->lpVtbl -> Initialize(This,pstream,grfMode) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IInitializeWithStream_RemoteInitialize_Proxy( 
-    IInitializeWithStream * This,
-    /* [in] */ __RPC__in_opt IStream *pstream,
-    /* [in] */ DWORD grfMode);
-
-
-void __RPC_STUB IInitializeWithStream_RemoteInitialize_Stub(
-    IRpcStubBuffer *This,
-    IRpcChannelBuffer *_pRpcChannelBuffer,
-    PRPC_MESSAGE _pRpcMessage,
-    DWORD *_pdwStubPhase);
-
-
-
-#endif 	/* __IInitializeWithStream_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyStore_INTERFACE_DEFINED__
-#define __IPropertyStore_INTERFACE_DEFINED__
-
-/* interface IPropertyStore */
-/* [unique][object][helpstring][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyStore;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99")
-    IPropertyStore : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetCount( 
-            /* [out] */ __RPC__out DWORD *cProps) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAt( 
-            /* [in] */ DWORD iProp,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetValue( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PROPVARIANT *pv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetValue( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Commit( void) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyStoreVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyStore * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyStore * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyStore * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IPropertyStore * This,
-            /* [out] */ __RPC__out DWORD *cProps);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAt )( 
-            IPropertyStore * This,
-            /* [in] */ DWORD iProp,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValue )( 
-            IPropertyStore * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PROPVARIANT *pv);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetValue )( 
-            IPropertyStore * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *Commit )( 
-            IPropertyStore * This);
-        
-        END_INTERFACE
-    } IPropertyStoreVtbl;
-
-    interface IPropertyStore
-    {
-        CONST_VTBL struct IPropertyStoreVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyStore_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyStore_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyStore_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyStore_GetCount(This,cProps)	\
-    ( (This)->lpVtbl -> GetCount(This,cProps) ) 
-
-#define IPropertyStore_GetAt(This,iProp,pkey)	\
-    ( (This)->lpVtbl -> GetAt(This,iProp,pkey) ) 
-
-#define IPropertyStore_GetValue(This,key,pv)	\
-    ( (This)->lpVtbl -> GetValue(This,key,pv) ) 
-
-#define IPropertyStore_SetValue(This,key,propvar)	\
-    ( (This)->lpVtbl -> SetValue(This,key,propvar) ) 
-
-#define IPropertyStore_Commit(This)	\
-    ( (This)->lpVtbl -> Commit(This) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyStore_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propsys_0000_0003 */
-/* [local] */ 
-
-typedef /* [unique] */  __RPC_unique_pointer IPropertyStore *LPPROPERTYSTORE;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0003_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0003_v0_0_s_ifspec;
-
-#ifndef __INamedPropertyStore_INTERFACE_DEFINED__
-#define __INamedPropertyStore_INTERFACE_DEFINED__
-
-/* interface INamedPropertyStore */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_INamedPropertyStore;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("71604b0f-97b0-4764-8577-2f13e98a1422")
-    INamedPropertyStore : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetNamedValue( 
-            /* [string][in] */ __RPC__in LPCWSTR pszName,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvar) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetNamedValue( 
-            /* [string][in] */ __RPC__in LPCWSTR pszName,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetNameCount( 
-            /* [out] */ __RPC__out DWORD *pdwCount) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetNameAt( 
-            /* [in] */ DWORD iProp,
-            /* [out] */ __RPC__deref_out_opt BSTR *pbstrName) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct INamedPropertyStoreVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            INamedPropertyStore * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            INamedPropertyStore * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            INamedPropertyStore * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetNamedValue )( 
-            INamedPropertyStore * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszName,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetNamedValue )( 
-            INamedPropertyStore * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszName,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetNameCount )( 
-            INamedPropertyStore * This,
-            /* [out] */ __RPC__out DWORD *pdwCount);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetNameAt )( 
-            INamedPropertyStore * This,
-            /* [in] */ DWORD iProp,
-            /* [out] */ __RPC__deref_out_opt BSTR *pbstrName);
-        
-        END_INTERFACE
-    } INamedPropertyStoreVtbl;
-
-    interface INamedPropertyStore
-    {
-        CONST_VTBL struct INamedPropertyStoreVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define INamedPropertyStore_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define INamedPropertyStore_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define INamedPropertyStore_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define INamedPropertyStore_GetNamedValue(This,pszName,ppropvar)	\
-    ( (This)->lpVtbl -> GetNamedValue(This,pszName,ppropvar) ) 
-
-#define INamedPropertyStore_SetNamedValue(This,pszName,propvar)	\
-    ( (This)->lpVtbl -> SetNamedValue(This,pszName,propvar) ) 
-
-#define INamedPropertyStore_GetNameCount(This,pdwCount)	\
-    ( (This)->lpVtbl -> GetNameCount(This,pdwCount) ) 
-
-#define INamedPropertyStore_GetNameAt(This,iProp,pbstrName)	\
-    ( (This)->lpVtbl -> GetNameAt(This,iProp,pbstrName) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __INamedPropertyStore_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propsys_0000_0004 */
-/* [local] */ 
-
-/* [v1_enum] */ 
-enum tagGETPROPERTYSTOREFLAGS
-    {	GPS_DEFAULT	= 0,
-	GPS_HANDLERPROPERTIESONLY	= 0x1,
-	GPS_READWRITE	= 0x2,
-	GPS_TEMPORARY	= 0x4,
-	GPS_FASTPROPERTIESONLY	= 0x8,
-	GPS_OPENSLOWITEM	= 0x10,
-	GPS_DELAYCREATION	= 0x20,
-	GPS_BESTEFFORT	= 0x40,
-	GPS_MASK_VALID	= 0x7f
-    } ;
-typedef int GETPROPERTYSTOREFLAGS;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0004_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0004_v0_0_s_ifspec;
-
-#ifndef __IObjectWithPropertyKey_INTERFACE_DEFINED__
-#define __IObjectWithPropertyKey_INTERFACE_DEFINED__
-
-/* interface IObjectWithPropertyKey */
-/* [uuid][object] */ 
-
-
-EXTERN_C const IID IID_IObjectWithPropertyKey;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("fc0ca0a7-c316-4fd2-9031-3e628e6d4f23")
-    IObjectWithPropertyKey : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE SetPropertyKey( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyKey( 
-            /* [out] */ __RPC__out PROPERTYKEY *pkey) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IObjectWithPropertyKeyVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IObjectWithPropertyKey * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IObjectWithPropertyKey * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IObjectWithPropertyKey * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetPropertyKey )( 
-            IObjectWithPropertyKey * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyKey )( 
-            IObjectWithPropertyKey * This,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        END_INTERFACE
-    } IObjectWithPropertyKeyVtbl;
-
-    interface IObjectWithPropertyKey
-    {
-        CONST_VTBL struct IObjectWithPropertyKeyVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IObjectWithPropertyKey_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IObjectWithPropertyKey_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IObjectWithPropertyKey_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IObjectWithPropertyKey_SetPropertyKey(This,key)	\
-    ( (This)->lpVtbl -> SetPropertyKey(This,key) ) 
-
-#define IObjectWithPropertyKey_GetPropertyKey(This,pkey)	\
-    ( (This)->lpVtbl -> GetPropertyKey(This,pkey) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IObjectWithPropertyKey_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propsys_0000_0005 */
-/* [local] */ 
-
-typedef /* [v1_enum] */ 
-enum tagPKA_FLAGS
-    {	PKA_SET	= 0,
-	PKA_APPEND	= ( PKA_SET + 1 ) ,
-	PKA_DELETE	= ( PKA_APPEND + 1 ) 
-    } 	PKA_FLAGS;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0005_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0005_v0_0_s_ifspec;
-
-#ifndef __IPropertyChange_INTERFACE_DEFINED__
-#define __IPropertyChange_INTERFACE_DEFINED__
-
-/* interface IPropertyChange */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyChange;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("f917bc8a-1bba-4478-a245-1bde03eb9431")
-    IPropertyChange : public IObjectWithPropertyKey
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE ApplyToPropVariant( 
-            /* [in] */ __RPC__in REFPROPVARIANT propvarIn,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarOut) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyChangeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyChange * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyChange * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyChange * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetPropertyKey )( 
-            IPropertyChange * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyKey )( 
-            IPropertyChange * This,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        HRESULT ( STDMETHODCALLTYPE *ApplyToPropVariant )( 
-            IPropertyChange * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvarIn,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarOut);
-        
-        END_INTERFACE
-    } IPropertyChangeVtbl;
-
-    interface IPropertyChange
-    {
-        CONST_VTBL struct IPropertyChangeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyChange_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyChange_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyChange_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyChange_SetPropertyKey(This,key)	\
-    ( (This)->lpVtbl -> SetPropertyKey(This,key) ) 
-
-#define IPropertyChange_GetPropertyKey(This,pkey)	\
-    ( (This)->lpVtbl -> GetPropertyKey(This,pkey) ) 
-
-
-#define IPropertyChange_ApplyToPropVariant(This,propvarIn,ppropvarOut)	\
-    ( (This)->lpVtbl -> ApplyToPropVariant(This,propvarIn,ppropvarOut) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyChange_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyChangeArray_INTERFACE_DEFINED__
-#define __IPropertyChangeArray_INTERFACE_DEFINED__
-
-/* interface IPropertyChangeArray */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyChangeArray;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("380f5cad-1b5e-42f2-805d-637fd392d31e")
-    IPropertyChangeArray : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetCount( 
-            /* [out] */ __RPC__out UINT *pcOperations) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAt( 
-            /* [in] */ UINT iIndex,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE InsertAt( 
-            /* [in] */ UINT iIndex,
-            /* [in] */ __RPC__in_opt IPropertyChange *ppropChange) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Append( 
-            /* [in] */ __RPC__in_opt IPropertyChange *ppropChange) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE AppendOrReplace( 
-            /* [in] */ __RPC__in_opt IPropertyChange *ppropChange) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RemoveAt( 
-            /* [in] */ UINT iIndex) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE IsKeyInArray( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyChangeArrayVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyChangeArray * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyChangeArray * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyChangeArray * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IPropertyChangeArray * This,
-            /* [out] */ __RPC__out UINT *pcOperations);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAt )( 
-            IPropertyChangeArray * This,
-            /* [in] */ UINT iIndex,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *InsertAt )( 
-            IPropertyChangeArray * This,
-            /* [in] */ UINT iIndex,
-            /* [in] */ __RPC__in_opt IPropertyChange *ppropChange);
-        
-        HRESULT ( STDMETHODCALLTYPE *Append )( 
-            IPropertyChangeArray * This,
-            /* [in] */ __RPC__in_opt IPropertyChange *ppropChange);
-        
-        HRESULT ( STDMETHODCALLTYPE *AppendOrReplace )( 
-            IPropertyChangeArray * This,
-            /* [in] */ __RPC__in_opt IPropertyChange *ppropChange);
-        
-        HRESULT ( STDMETHODCALLTYPE *RemoveAt )( 
-            IPropertyChangeArray * This,
-            /* [in] */ UINT iIndex);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsKeyInArray )( 
-            IPropertyChangeArray * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key);
-        
-        END_INTERFACE
-    } IPropertyChangeArrayVtbl;
-
-    interface IPropertyChangeArray
-    {
-        CONST_VTBL struct IPropertyChangeArrayVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyChangeArray_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyChangeArray_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyChangeArray_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyChangeArray_GetCount(This,pcOperations)	\
-    ( (This)->lpVtbl -> GetCount(This,pcOperations) ) 
-
-#define IPropertyChangeArray_GetAt(This,iIndex,riid,ppv)	\
-    ( (This)->lpVtbl -> GetAt(This,iIndex,riid,ppv) ) 
-
-#define IPropertyChangeArray_InsertAt(This,iIndex,ppropChange)	\
-    ( (This)->lpVtbl -> InsertAt(This,iIndex,ppropChange) ) 
-
-#define IPropertyChangeArray_Append(This,ppropChange)	\
-    ( (This)->lpVtbl -> Append(This,ppropChange) ) 
-
-#define IPropertyChangeArray_AppendOrReplace(This,ppropChange)	\
-    ( (This)->lpVtbl -> AppendOrReplace(This,ppropChange) ) 
-
-#define IPropertyChangeArray_RemoveAt(This,iIndex)	\
-    ( (This)->lpVtbl -> RemoveAt(This,iIndex) ) 
-
-#define IPropertyChangeArray_IsKeyInArray(This,key)	\
-    ( (This)->lpVtbl -> IsKeyInArray(This,key) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyChangeArray_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyStoreCapabilities_INTERFACE_DEFINED__
-#define __IPropertyStoreCapabilities_INTERFACE_DEFINED__
-
-/* interface IPropertyStoreCapabilities */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyStoreCapabilities;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("c8e2d566-186e-4d49-bf41-6909ead56acc")
-    IPropertyStoreCapabilities : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE IsPropertyWritable( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyStoreCapabilitiesVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyStoreCapabilities * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyStoreCapabilities * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyStoreCapabilities * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsPropertyWritable )( 
-            IPropertyStoreCapabilities * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key);
-        
-        END_INTERFACE
-    } IPropertyStoreCapabilitiesVtbl;
-
-    interface IPropertyStoreCapabilities
-    {
-        CONST_VTBL struct IPropertyStoreCapabilitiesVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyStoreCapabilities_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyStoreCapabilities_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyStoreCapabilities_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyStoreCapabilities_IsPropertyWritable(This,key)	\
-    ( (This)->lpVtbl -> IsPropertyWritable(This,key) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyStoreCapabilities_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyStoreCache_INTERFACE_DEFINED__
-#define __IPropertyStoreCache_INTERFACE_DEFINED__
-
-/* interface IPropertyStoreCache */
-/* [unique][object][uuid] */ 
-
-typedef /* [v1_enum] */ 
-enum _PSC_STATE
-    {	PSC_NORMAL	= 0,
-	PSC_NOTINSOURCE	= 1,
-	PSC_DIRTY	= 2,
-	PSC_READONLY	= 3
-    } 	PSC_STATE;
-
-
-EXTERN_C const IID IID_IPropertyStoreCache;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("3017056d-9a91-4e90-937d-746c72abbf4f")
-    IPropertyStoreCache : public IPropertyStore
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetState( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PSC_STATE *pstate) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetValueAndState( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvar,
-            /* [out] */ __RPC__out PSC_STATE *pstate) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetState( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ PSC_STATE state) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetValueAndState( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [unique][in] */ __RPC__in_opt const PROPVARIANT *ppropvar,
-            /* [in] */ PSC_STATE state) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyStoreCacheVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyStoreCache * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyStoreCache * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IPropertyStoreCache * This,
-            /* [out] */ __RPC__out DWORD *cProps);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAt )( 
-            IPropertyStoreCache * This,
-            /* [in] */ DWORD iProp,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValue )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PROPVARIANT *pv);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetValue )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *Commit )( 
-            IPropertyStoreCache * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetState )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PSC_STATE *pstate);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValueAndState )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvar,
-            /* [out] */ __RPC__out PSC_STATE *pstate);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetState )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ PSC_STATE state);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetValueAndState )( 
-            IPropertyStoreCache * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [unique][in] */ __RPC__in_opt const PROPVARIANT *ppropvar,
-            /* [in] */ PSC_STATE state);
-        
-        END_INTERFACE
-    } IPropertyStoreCacheVtbl;
-
-    interface IPropertyStoreCache
-    {
-        CONST_VTBL struct IPropertyStoreCacheVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyStoreCache_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyStoreCache_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyStoreCache_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyStoreCache_GetCount(This,cProps)	\
-    ( (This)->lpVtbl -> GetCount(This,cProps) ) 
-
-#define IPropertyStoreCache_GetAt(This,iProp,pkey)	\
-    ( (This)->lpVtbl -> GetAt(This,iProp,pkey) ) 
-
-#define IPropertyStoreCache_GetValue(This,key,pv)	\
-    ( (This)->lpVtbl -> GetValue(This,key,pv) ) 
-
-#define IPropertyStoreCache_SetValue(This,key,propvar)	\
-    ( (This)->lpVtbl -> SetValue(This,key,propvar) ) 
-
-#define IPropertyStoreCache_Commit(This)	\
-    ( (This)->lpVtbl -> Commit(This) ) 
-
-
-#define IPropertyStoreCache_GetState(This,key,pstate)	\
-    ( (This)->lpVtbl -> GetState(This,key,pstate) ) 
-
-#define IPropertyStoreCache_GetValueAndState(This,key,ppropvar,pstate)	\
-    ( (This)->lpVtbl -> GetValueAndState(This,key,ppropvar,pstate) ) 
-
-#define IPropertyStoreCache_SetState(This,key,state)	\
-    ( (This)->lpVtbl -> SetState(This,key,state) ) 
-
-#define IPropertyStoreCache_SetValueAndState(This,key,ppropvar,state)	\
-    ( (This)->lpVtbl -> SetValueAndState(This,key,ppropvar,state) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyStoreCache_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyEnumType_INTERFACE_DEFINED__
-#define __IPropertyEnumType_INTERFACE_DEFINED__
-
-/* interface IPropertyEnumType */
-/* [unique][object][uuid] */ 
-
-/* [v1_enum] */ 
-enum tagPROPENUMTYPE
-    {	PET_DISCRETEVALUE	= 0,
-	PET_RANGEDVALUE	= 1,
-	PET_DEFAULTVALUE	= 2,
-	PET_ENDRANGE	= 3
-    } ;
-typedef enum tagPROPENUMTYPE PROPENUMTYPE;
-
-
-EXTERN_C const IID IID_IPropertyEnumType;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("11e1fbf9-2d56-4a6b-8db3-7cd193a471f2")
-    IPropertyEnumType : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetEnumType( 
-            /* [out] */ __RPC__out PROPENUMTYPE *penumtype) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetValue( 
-            /* [out] */ __RPC__out PROPVARIANT *ppropvar) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetRangeMinValue( 
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarMin) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetRangeSetValue( 
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarSet) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetDisplayText( 
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszDisplay) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyEnumTypeVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyEnumType * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyEnumType * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyEnumType * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEnumType )( 
-            IPropertyEnumType * This,
-            /* [out] */ __RPC__out PROPENUMTYPE *penumtype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValue )( 
-            IPropertyEnumType * This,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRangeMinValue )( 
-            IPropertyEnumType * This,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarMin);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRangeSetValue )( 
-            IPropertyEnumType * This,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarSet);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayText )( 
-            IPropertyEnumType * This,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszDisplay);
-        
-        END_INTERFACE
-    } IPropertyEnumTypeVtbl;
-
-    interface IPropertyEnumType
-    {
-        CONST_VTBL struct IPropertyEnumTypeVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyEnumType_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyEnumType_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyEnumType_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyEnumType_GetEnumType(This,penumtype)	\
-    ( (This)->lpVtbl -> GetEnumType(This,penumtype) ) 
-
-#define IPropertyEnumType_GetValue(This,ppropvar)	\
-    ( (This)->lpVtbl -> GetValue(This,ppropvar) ) 
-
-#define IPropertyEnumType_GetRangeMinValue(This,ppropvarMin)	\
-    ( (This)->lpVtbl -> GetRangeMinValue(This,ppropvarMin) ) 
-
-#define IPropertyEnumType_GetRangeSetValue(This,ppropvarSet)	\
-    ( (This)->lpVtbl -> GetRangeSetValue(This,ppropvarSet) ) 
-
-#define IPropertyEnumType_GetDisplayText(This,ppszDisplay)	\
-    ( (This)->lpVtbl -> GetDisplayText(This,ppszDisplay) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyEnumType_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyEnumTypeList_INTERFACE_DEFINED__
-#define __IPropertyEnumTypeList_INTERFACE_DEFINED__
-
-/* interface IPropertyEnumTypeList */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyEnumTypeList;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("a99400f4-3d84-4557-94ba-1242fb2cc9a6")
-    IPropertyEnumTypeList : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetCount( 
-            /* [out] */ __RPC__out UINT *pctypes) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAt( 
-            /* [in] */ UINT itype,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetConditionAt( 
-            /* [in] */ UINT nIndex,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE FindMatchingIndex( 
-            /* [in] */ __RPC__in REFPROPVARIANT propvarCmp,
-            /* [out] */ __RPC__out UINT *pnIndex) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyEnumTypeListVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyEnumTypeList * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyEnumTypeList * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyEnumTypeList * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IPropertyEnumTypeList * This,
-            /* [out] */ __RPC__out UINT *pctypes);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAt )( 
-            IPropertyEnumTypeList * This,
-            /* [in] */ UINT itype,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetConditionAt )( 
-            IPropertyEnumTypeList * This,
-            /* [in] */ UINT nIndex,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *FindMatchingIndex )( 
-            IPropertyEnumTypeList * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvarCmp,
-            /* [out] */ __RPC__out UINT *pnIndex);
-        
-        END_INTERFACE
-    } IPropertyEnumTypeListVtbl;
-
-    interface IPropertyEnumTypeList
-    {
-        CONST_VTBL struct IPropertyEnumTypeListVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyEnumTypeList_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyEnumTypeList_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyEnumTypeList_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyEnumTypeList_GetCount(This,pctypes)	\
-    ( (This)->lpVtbl -> GetCount(This,pctypes) ) 
-
-#define IPropertyEnumTypeList_GetAt(This,itype,riid,ppv)	\
-    ( (This)->lpVtbl -> GetAt(This,itype,riid,ppv) ) 
-
-#define IPropertyEnumTypeList_GetConditionAt(This,nIndex,riid,ppv)	\
-    ( (This)->lpVtbl -> GetConditionAt(This,nIndex,riid,ppv) ) 
-
-#define IPropertyEnumTypeList_FindMatchingIndex(This,propvarCmp,pnIndex)	\
-    ( (This)->lpVtbl -> FindMatchingIndex(This,propvarCmp,pnIndex) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyEnumTypeList_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyDescription_INTERFACE_DEFINED__
-#define __IPropertyDescription_INTERFACE_DEFINED__
-
-/* interface IPropertyDescription */
-/* [unique][object][uuid] */ 
-
-/* [v1_enum] */ 
-enum tagPROPDESC_TYPE_FLAGS
-    {	PDTF_DEFAULT	= 0,
-	PDTF_MULTIPLEVALUES	= 0x1,
-	PDTF_ISINNATE	= 0x2,
-	PDTF_ISGROUP	= 0x4,
-	PDTF_CANGROUPBY	= 0x8,
-	PDTF_CANSTACKBY	= 0x10,
-	PDTF_ISTREEPROPERTY	= 0x20,
-	PDTF_INCLUDEINFULLTEXTQUERY	= 0x40,
-	PDTF_ISVIEWABLE	= 0x80,
-	PDTF_ISQUERYABLE	= 0x100,
-	PDTF_ISSYSTEMPROPERTY	= 0x80000000,
-	PDTF_MASK_ALL	= 0x800001ff
-    } ;
-typedef int PROPDESC_TYPE_FLAGS;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_VIEW_FLAGS
-    {	PDVF_DEFAULT	= 0,
-	PDVF_CENTERALIGN	= 0x1,
-	PDVF_RIGHTALIGN	= 0x2,
-	PDVF_BEGINNEWGROUP	= 0x4,
-	PDVF_FILLAREA	= 0x8,
-	PDVF_SORTDESCENDING	= 0x10,
-	PDVF_SHOWONLYIFPRESENT	= 0x20,
-	PDVF_SHOWBYDEFAULT	= 0x40,
-	PDVF_SHOWINPRIMARYLIST	= 0x80,
-	PDVF_SHOWINSECONDARYLIST	= 0x100,
-	PDVF_HIDELABEL	= 0x200,
-	PDVF_HIDDEN	= 0x800,
-	PDVF_CANWRAP	= 0x1000,
-	PDVF_MASK_ALL	= 0x1bff
-    } ;
-typedef int PROPDESC_VIEW_FLAGS;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_DISPLAYTYPE
-    {	PDDT_STRING	= 0,
-	PDDT_NUMBER	= 1,
-	PDDT_BOOLEAN	= 2,
-	PDDT_DATETIME	= 3,
-	PDDT_ENUMERATED	= 4
-    } ;
-typedef enum tagPROPDESC_DISPLAYTYPE PROPDESC_DISPLAYTYPE;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_GROUPING_RANGE
-    {	PDGR_DISCRETE	= 0,
-	PDGR_ALPHANUMERIC	= 1,
-	PDGR_SIZE	= 2,
-	PDGR_DYNAMIC	= 3,
-	PDGR_DATE	= 4,
-	PDGR_PERCENT	= 5,
-	PDGR_ENUMERATED	= 6
-    } ;
-typedef enum tagPROPDESC_GROUPING_RANGE PROPDESC_GROUPING_RANGE;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_FORMAT_FLAGS
-    {	PDFF_DEFAULT	= 0,
-	PDFF_PREFIXNAME	= 0x1,
-	PDFF_FILENAME	= 0x2,
-	PDFF_ALWAYSKB	= 0x4,
-	PDFF_RESERVED_RIGHTTOLEFT	= 0x8,
-	PDFF_SHORTTIME	= 0x10,
-	PDFF_LONGTIME	= 0x20,
-	PDFF_HIDETIME	= 0x40,
-	PDFF_SHORTDATE	= 0x80,
-	PDFF_LONGDATE	= 0x100,
-	PDFF_HIDEDATE	= 0x200,
-	PDFF_RELATIVEDATE	= 0x400,
-	PDFF_USEEDITINVITATION	= 0x800,
-	PDFF_READONLY	= 0x1000,
-	PDFF_NOAUTOREADINGORDER	= 0x2000
-    } ;
-typedef int PROPDESC_FORMAT_FLAGS;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_SORTDESCRIPTION
-    {	PDSD_GENERAL	= 0,
-	PDSD_A_Z	= 1,
-	PDSD_LOWEST_HIGHEST	= 2,
-	PDSD_SMALLEST_BIGGEST	= 3,
-	PDSD_OLDEST_NEWEST	= 4
-    } ;
-typedef enum tagPROPDESC_SORTDESCRIPTION PROPDESC_SORTDESCRIPTION;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_RELATIVEDESCRIPTION_TYPE
-    {	PDRDT_GENERAL	= 0,
-	PDRDT_DATE	= 1,
-	PDRDT_SIZE	= 2,
-	PDRDT_COUNT	= 3,
-	PDRDT_REVISION	= 4,
-	PDRDT_LENGTH	= 5,
-	PDRDT_DURATION	= 6,
-	PDRDT_SPEED	= 7,
-	PDRDT_RATE	= 8,
-	PDRDT_RATING	= 9,
-	PDRDT_PRIORITY	= 10
-    } ;
-typedef enum tagPROPDESC_RELATIVEDESCRIPTION_TYPE PROPDESC_RELATIVEDESCRIPTION_TYPE;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_AGGREGATION_TYPE
-    {	PDAT_DEFAULT	= 0,
-	PDAT_FIRST	= 1,
-	PDAT_SUM	= 2,
-	PDAT_AVERAGE	= 3,
-	PDAT_DATERANGE	= 4,
-	PDAT_UNION	= 5,
-	PDAT_MAX	= 6,
-	PDAT_MIN	= 7
-    } ;
-typedef enum tagPROPDESC_AGGREGATION_TYPE PROPDESC_AGGREGATION_TYPE;
-
-/* [v1_enum] */ 
-enum tagPROPDESC_CONDITION_TYPE
-    {	PDCOT_NONE	= 0,
-	PDCOT_STRING	= 1,
-	PDCOT_SIZE	= 2,
-	PDCOT_DATETIME	= 3,
-	PDCOT_BOOLEAN	= 4,
-	PDCOT_NUMBER	= 5
-    } ;
-typedef enum tagPROPDESC_CONDITION_TYPE PROPDESC_CONDITION_TYPE;
-
-
-EXTERN_C const IID IID_IPropertyDescription;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("6f79d558-3e96-4549-a1d1-7d75d2288814")
-    IPropertyDescription : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyKey( 
-            /* [out] */ __RPC__out PROPERTYKEY *pkey) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetCanonicalName( 
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyType( 
-            /* [out] */ __RPC__out VARTYPE *pvartype) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetDisplayName( 
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetEditInvitation( 
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszInvite) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetTypeFlags( 
-            /* [in] */ PROPDESC_TYPE_FLAGS mask,
-            /* [out] */ __RPC__out PROPDESC_TYPE_FLAGS *ppdtFlags) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetViewFlags( 
-            /* [out] */ __RPC__out PROPDESC_VIEW_FLAGS *ppdvFlags) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetDefaultColumnWidth( 
-            /* [out] */ __RPC__out UINT *pcxChars) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetDisplayType( 
-            /* [out] */ __RPC__out PROPDESC_DISPLAYTYPE *pdisplaytype) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetColumnState( 
-            /* [out] */ __RPC__out SHCOLSTATEF *pcsFlags) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetGroupingRange( 
-            /* [out] */ __RPC__out PROPDESC_GROUPING_RANGE *pgr) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetRelativeDescriptionType( 
-            /* [out] */ __RPC__out PROPDESC_RELATIVEDESCRIPTION_TYPE *prdt) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetRelativeDescription( 
-            /* [in] */ __RPC__in REFPROPVARIANT propvar1,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar2,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc1,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc2) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetSortDescription( 
-            /* [out] */ __RPC__out PROPDESC_SORTDESCRIPTION *psd) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetSortDescriptionLabel( 
-            /* [in] */ BOOL fDescending,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDescription) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAggregationType( 
-            /* [out] */ __RPC__out PROPDESC_AGGREGATION_TYPE *paggtype) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetConditionType( 
-            /* [out] */ __RPC__out PROPDESC_CONDITION_TYPE *pcontype,
-            /* [out] */ __RPC__out CONDITION_OPERATION *popDefault) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetEnumTypeList( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE CoerceToCanonicalValue( 
-            /* [out][in] */ PROPVARIANT *ppropvar) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE FormatForDisplay( 
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdfFlags,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDisplay) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE IsValueCanonical( 
-            /* [in] */ __RPC__in REFPROPVARIANT propvar) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyDescriptionVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyDescription * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyDescription * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyDescription * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyKey )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCanonicalName )( 
-            IPropertyDescription * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyType )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out VARTYPE *pvartype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayName )( 
-            IPropertyDescription * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEditInvitation )( 
-            IPropertyDescription * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszInvite);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetTypeFlags )( 
-            IPropertyDescription * This,
-            /* [in] */ PROPDESC_TYPE_FLAGS mask,
-            /* [out] */ __RPC__out PROPDESC_TYPE_FLAGS *ppdtFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetViewFlags )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_VIEW_FLAGS *ppdvFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDefaultColumnWidth )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out UINT *pcxChars);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayType )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_DISPLAYTYPE *pdisplaytype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetColumnState )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out SHCOLSTATEF *pcsFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetGroupingRange )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_GROUPING_RANGE *pgr);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelativeDescriptionType )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_RELATIVEDESCRIPTION_TYPE *prdt);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelativeDescription )( 
-            IPropertyDescription * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar1,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar2,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc1,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc2);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortDescription )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_SORTDESCRIPTION *psd);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortDescriptionLabel )( 
-            IPropertyDescription * This,
-            /* [in] */ BOOL fDescending,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDescription);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAggregationType )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_AGGREGATION_TYPE *paggtype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetConditionType )( 
-            IPropertyDescription * This,
-            /* [out] */ __RPC__out PROPDESC_CONDITION_TYPE *pcontype,
-            /* [out] */ __RPC__out CONDITION_OPERATION *popDefault);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEnumTypeList )( 
-            IPropertyDescription * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *CoerceToCanonicalValue )( 
-            IPropertyDescription * This,
-            /* [out][in] */ PROPVARIANT *ppropvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *FormatForDisplay )( 
-            IPropertyDescription * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdfFlags,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDisplay);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsValueCanonical )( 
-            IPropertyDescription * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar);
-        
-        END_INTERFACE
-    } IPropertyDescriptionVtbl;
-
-    interface IPropertyDescription
-    {
-        CONST_VTBL struct IPropertyDescriptionVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyDescription_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyDescription_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyDescription_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyDescription_GetPropertyKey(This,pkey)	\
-    ( (This)->lpVtbl -> GetPropertyKey(This,pkey) ) 
-
-#define IPropertyDescription_GetCanonicalName(This,ppszName)	\
-    ( (This)->lpVtbl -> GetCanonicalName(This,ppszName) ) 
-
-#define IPropertyDescription_GetPropertyType(This,pvartype)	\
-    ( (This)->lpVtbl -> GetPropertyType(This,pvartype) ) 
-
-#define IPropertyDescription_GetDisplayName(This,ppszName)	\
-    ( (This)->lpVtbl -> GetDisplayName(This,ppszName) ) 
-
-#define IPropertyDescription_GetEditInvitation(This,ppszInvite)	\
-    ( (This)->lpVtbl -> GetEditInvitation(This,ppszInvite) ) 
-
-#define IPropertyDescription_GetTypeFlags(This,mask,ppdtFlags)	\
-    ( (This)->lpVtbl -> GetTypeFlags(This,mask,ppdtFlags) ) 
-
-#define IPropertyDescription_GetViewFlags(This,ppdvFlags)	\
-    ( (This)->lpVtbl -> GetViewFlags(This,ppdvFlags) ) 
-
-#define IPropertyDescription_GetDefaultColumnWidth(This,pcxChars)	\
-    ( (This)->lpVtbl -> GetDefaultColumnWidth(This,pcxChars) ) 
-
-#define IPropertyDescription_GetDisplayType(This,pdisplaytype)	\
-    ( (This)->lpVtbl -> GetDisplayType(This,pdisplaytype) ) 
-
-#define IPropertyDescription_GetColumnState(This,pcsFlags)	\
-    ( (This)->lpVtbl -> GetColumnState(This,pcsFlags) ) 
-
-#define IPropertyDescription_GetGroupingRange(This,pgr)	\
-    ( (This)->lpVtbl -> GetGroupingRange(This,pgr) ) 
-
-#define IPropertyDescription_GetRelativeDescriptionType(This,prdt)	\
-    ( (This)->lpVtbl -> GetRelativeDescriptionType(This,prdt) ) 
-
-#define IPropertyDescription_GetRelativeDescription(This,propvar1,propvar2,ppszDesc1,ppszDesc2)	\
-    ( (This)->lpVtbl -> GetRelativeDescription(This,propvar1,propvar2,ppszDesc1,ppszDesc2) ) 
-
-#define IPropertyDescription_GetSortDescription(This,psd)	\
-    ( (This)->lpVtbl -> GetSortDescription(This,psd) ) 
-
-#define IPropertyDescription_GetSortDescriptionLabel(This,fDescending,ppszDescription)	\
-    ( (This)->lpVtbl -> GetSortDescriptionLabel(This,fDescending,ppszDescription) ) 
-
-#define IPropertyDescription_GetAggregationType(This,paggtype)	\
-    ( (This)->lpVtbl -> GetAggregationType(This,paggtype) ) 
-
-#define IPropertyDescription_GetConditionType(This,pcontype,popDefault)	\
-    ( (This)->lpVtbl -> GetConditionType(This,pcontype,popDefault) ) 
-
-#define IPropertyDescription_GetEnumTypeList(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetEnumTypeList(This,riid,ppv) ) 
-
-#define IPropertyDescription_CoerceToCanonicalValue(This,ppropvar)	\
-    ( (This)->lpVtbl -> CoerceToCanonicalValue(This,ppropvar) ) 
-
-#define IPropertyDescription_FormatForDisplay(This,propvar,pdfFlags,ppszDisplay)	\
-    ( (This)->lpVtbl -> FormatForDisplay(This,propvar,pdfFlags,ppszDisplay) ) 
-
-#define IPropertyDescription_IsValueCanonical(This,propvar)	\
-    ( (This)->lpVtbl -> IsValueCanonical(This,propvar) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IPropertyDescription_RemoteCoerceToCanonicalValue_Proxy( 
-    IPropertyDescription * This,
-    /* [in] */ __RPC__in REFPROPVARIANT propvar,
-    /* [out] */ __RPC__out PROPVARIANT *ppropvar);
-
-
-void __RPC_STUB IPropertyDescription_RemoteCoerceToCanonicalValue_Stub(
-    IRpcStubBuffer *This,
-    IRpcChannelBuffer *_pRpcChannelBuffer,
-    PRPC_MESSAGE _pRpcMessage,
-    DWORD *_pdwStubPhase);
-
-
-
-#endif 	/* __IPropertyDescription_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyDescriptionAliasInfo_INTERFACE_DEFINED__
-#define __IPropertyDescriptionAliasInfo_INTERFACE_DEFINED__
-
-/* interface IPropertyDescriptionAliasInfo */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyDescriptionAliasInfo;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("f67104fc-2af9-46fd-b32d-243c1404f3d1")
-    IPropertyDescriptionAliasInfo : public IPropertyDescription
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetSortByAlias( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAdditionalSortByAliases( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyDescriptionAliasInfoVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyDescriptionAliasInfo * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyDescriptionAliasInfo * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyKey )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCanonicalName )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyType )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out VARTYPE *pvartype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayName )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEditInvitation )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszInvite);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetTypeFlags )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ PROPDESC_TYPE_FLAGS mask,
-            /* [out] */ __RPC__out PROPDESC_TYPE_FLAGS *ppdtFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetViewFlags )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_VIEW_FLAGS *ppdvFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDefaultColumnWidth )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out UINT *pcxChars);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayType )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_DISPLAYTYPE *pdisplaytype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetColumnState )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out SHCOLSTATEF *pcsFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetGroupingRange )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_GROUPING_RANGE *pgr);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelativeDescriptionType )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_RELATIVEDESCRIPTION_TYPE *prdt);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelativeDescription )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar1,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar2,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc1,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc2);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortDescription )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_SORTDESCRIPTION *psd);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortDescriptionLabel )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ BOOL fDescending,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDescription);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAggregationType )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_AGGREGATION_TYPE *paggtype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetConditionType )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out] */ __RPC__out PROPDESC_CONDITION_TYPE *pcontype,
-            /* [out] */ __RPC__out CONDITION_OPERATION *popDefault);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEnumTypeList )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *CoerceToCanonicalValue )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [out][in] */ PROPVARIANT *ppropvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *FormatForDisplay )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdfFlags,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDisplay);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsValueCanonical )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortByAlias )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAdditionalSortByAliases )( 
-            IPropertyDescriptionAliasInfo * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        END_INTERFACE
-    } IPropertyDescriptionAliasInfoVtbl;
-
-    interface IPropertyDescriptionAliasInfo
-    {
-        CONST_VTBL struct IPropertyDescriptionAliasInfoVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyDescriptionAliasInfo_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyDescriptionAliasInfo_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyDescriptionAliasInfo_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyDescriptionAliasInfo_GetPropertyKey(This,pkey)	\
-    ( (This)->lpVtbl -> GetPropertyKey(This,pkey) ) 
-
-#define IPropertyDescriptionAliasInfo_GetCanonicalName(This,ppszName)	\
-    ( (This)->lpVtbl -> GetCanonicalName(This,ppszName) ) 
-
-#define IPropertyDescriptionAliasInfo_GetPropertyType(This,pvartype)	\
-    ( (This)->lpVtbl -> GetPropertyType(This,pvartype) ) 
-
-#define IPropertyDescriptionAliasInfo_GetDisplayName(This,ppszName)	\
-    ( (This)->lpVtbl -> GetDisplayName(This,ppszName) ) 
-
-#define IPropertyDescriptionAliasInfo_GetEditInvitation(This,ppszInvite)	\
-    ( (This)->lpVtbl -> GetEditInvitation(This,ppszInvite) ) 
-
-#define IPropertyDescriptionAliasInfo_GetTypeFlags(This,mask,ppdtFlags)	\
-    ( (This)->lpVtbl -> GetTypeFlags(This,mask,ppdtFlags) ) 
-
-#define IPropertyDescriptionAliasInfo_GetViewFlags(This,ppdvFlags)	\
-    ( (This)->lpVtbl -> GetViewFlags(This,ppdvFlags) ) 
-
-#define IPropertyDescriptionAliasInfo_GetDefaultColumnWidth(This,pcxChars)	\
-    ( (This)->lpVtbl -> GetDefaultColumnWidth(This,pcxChars) ) 
-
-#define IPropertyDescriptionAliasInfo_GetDisplayType(This,pdisplaytype)	\
-    ( (This)->lpVtbl -> GetDisplayType(This,pdisplaytype) ) 
-
-#define IPropertyDescriptionAliasInfo_GetColumnState(This,pcsFlags)	\
-    ( (This)->lpVtbl -> GetColumnState(This,pcsFlags) ) 
-
-#define IPropertyDescriptionAliasInfo_GetGroupingRange(This,pgr)	\
-    ( (This)->lpVtbl -> GetGroupingRange(This,pgr) ) 
-
-#define IPropertyDescriptionAliasInfo_GetRelativeDescriptionType(This,prdt)	\
-    ( (This)->lpVtbl -> GetRelativeDescriptionType(This,prdt) ) 
-
-#define IPropertyDescriptionAliasInfo_GetRelativeDescription(This,propvar1,propvar2,ppszDesc1,ppszDesc2)	\
-    ( (This)->lpVtbl -> GetRelativeDescription(This,propvar1,propvar2,ppszDesc1,ppszDesc2) ) 
-
-#define IPropertyDescriptionAliasInfo_GetSortDescription(This,psd)	\
-    ( (This)->lpVtbl -> GetSortDescription(This,psd) ) 
-
-#define IPropertyDescriptionAliasInfo_GetSortDescriptionLabel(This,fDescending,ppszDescription)	\
-    ( (This)->lpVtbl -> GetSortDescriptionLabel(This,fDescending,ppszDescription) ) 
-
-#define IPropertyDescriptionAliasInfo_GetAggregationType(This,paggtype)	\
-    ( (This)->lpVtbl -> GetAggregationType(This,paggtype) ) 
-
-#define IPropertyDescriptionAliasInfo_GetConditionType(This,pcontype,popDefault)	\
-    ( (This)->lpVtbl -> GetConditionType(This,pcontype,popDefault) ) 
-
-#define IPropertyDescriptionAliasInfo_GetEnumTypeList(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetEnumTypeList(This,riid,ppv) ) 
-
-#define IPropertyDescriptionAliasInfo_CoerceToCanonicalValue(This,ppropvar)	\
-    ( (This)->lpVtbl -> CoerceToCanonicalValue(This,ppropvar) ) 
-
-#define IPropertyDescriptionAliasInfo_FormatForDisplay(This,propvar,pdfFlags,ppszDisplay)	\
-    ( (This)->lpVtbl -> FormatForDisplay(This,propvar,pdfFlags,ppszDisplay) ) 
-
-#define IPropertyDescriptionAliasInfo_IsValueCanonical(This,propvar)	\
-    ( (This)->lpVtbl -> IsValueCanonical(This,propvar) ) 
-
-
-#define IPropertyDescriptionAliasInfo_GetSortByAlias(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetSortByAlias(This,riid,ppv) ) 
-
-#define IPropertyDescriptionAliasInfo_GetAdditionalSortByAliases(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetAdditionalSortByAliases(This,riid,ppv) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyDescriptionAliasInfo_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyDescriptionSearchInfo_INTERFACE_DEFINED__
-#define __IPropertyDescriptionSearchInfo_INTERFACE_DEFINED__
-
-/* interface IPropertyDescriptionSearchInfo */
-/* [unique][object][uuid] */ 
-
-/* [v1_enum] */ 
-enum tagPROPDESC_SEARCHINFO_FLAGS
-    {	PDSIF_DEFAULT	= 0,
-	PDSIF_ININVERTEDINDEX	= 0x1,
-	PDSIF_ISCOLUMN	= 0x2,
-	PDSIF_ISCOLUMNSPARSE	= 0x4
-    } ;
-typedef int PROPDESC_SEARCHINFO_FLAGS;
-
-typedef /* [v1_enum] */ 
-enum tagPROPDESC_COLUMNINDEX_TYPE
-    {	PDCIT_NONE	= 0,
-	PDCIT_ONDISK	= 1,
-	PDCIT_INMEMORY	= 2
-    } 	PROPDESC_COLUMNINDEX_TYPE;
-
-
-EXTERN_C const IID IID_IPropertyDescriptionSearchInfo;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("078f91bd-29a2-440f-924e-46a291524520")
-    IPropertyDescriptionSearchInfo : public IPropertyDescription
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetSearchInfoFlags( 
-            /* [out] */ __RPC__out PROPDESC_SEARCHINFO_FLAGS *ppdsiFlags) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetColumnIndexType( 
-            /* [out] */ __RPC__out PROPDESC_COLUMNINDEX_TYPE *ppdciType) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetProjectionString( 
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszProjection) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetMaxSize( 
-            /* [out] */ __RPC__out UINT *pcbMaxSize) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyDescriptionSearchInfoVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyDescriptionSearchInfo * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyDescriptionSearchInfo * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyKey )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPERTYKEY *pkey);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCanonicalName )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyType )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out VARTYPE *pvartype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayName )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEditInvitation )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszInvite);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetTypeFlags )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ PROPDESC_TYPE_FLAGS mask,
-            /* [out] */ __RPC__out PROPDESC_TYPE_FLAGS *ppdtFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetViewFlags )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_VIEW_FLAGS *ppdvFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDefaultColumnWidth )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out UINT *pcxChars);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDisplayType )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_DISPLAYTYPE *pdisplaytype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetColumnState )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out SHCOLSTATEF *pcsFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetGroupingRange )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_GROUPING_RANGE *pgr);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelativeDescriptionType )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_RELATIVEDESCRIPTION_TYPE *prdt);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelativeDescription )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar1,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar2,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc1,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDesc2);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortDescription )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_SORTDESCRIPTION *psd);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSortDescriptionLabel )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ BOOL fDescending,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDescription);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAggregationType )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_AGGREGATION_TYPE *paggtype);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetConditionType )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_CONDITION_TYPE *pcontype,
-            /* [out] */ __RPC__out CONDITION_OPERATION *popDefault);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEnumTypeList )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *CoerceToCanonicalValue )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out][in] */ PROPVARIANT *ppropvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *FormatForDisplay )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdfFlags,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDisplay);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsValueCanonical )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSearchInfoFlags )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_SEARCHINFO_FLAGS *ppdsiFlags);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetColumnIndexType )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out PROPDESC_COLUMNINDEX_TYPE *ppdciType);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetProjectionString )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszProjection);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetMaxSize )( 
-            IPropertyDescriptionSearchInfo * This,
-            /* [out] */ __RPC__out UINT *pcbMaxSize);
-        
-        END_INTERFACE
-    } IPropertyDescriptionSearchInfoVtbl;
-
-    interface IPropertyDescriptionSearchInfo
-    {
-        CONST_VTBL struct IPropertyDescriptionSearchInfoVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyDescriptionSearchInfo_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyDescriptionSearchInfo_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyDescriptionSearchInfo_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyDescriptionSearchInfo_GetPropertyKey(This,pkey)	\
-    ( (This)->lpVtbl -> GetPropertyKey(This,pkey) ) 
-
-#define IPropertyDescriptionSearchInfo_GetCanonicalName(This,ppszName)	\
-    ( (This)->lpVtbl -> GetCanonicalName(This,ppszName) ) 
-
-#define IPropertyDescriptionSearchInfo_GetPropertyType(This,pvartype)	\
-    ( (This)->lpVtbl -> GetPropertyType(This,pvartype) ) 
-
-#define IPropertyDescriptionSearchInfo_GetDisplayName(This,ppszName)	\
-    ( (This)->lpVtbl -> GetDisplayName(This,ppszName) ) 
-
-#define IPropertyDescriptionSearchInfo_GetEditInvitation(This,ppszInvite)	\
-    ( (This)->lpVtbl -> GetEditInvitation(This,ppszInvite) ) 
-
-#define IPropertyDescriptionSearchInfo_GetTypeFlags(This,mask,ppdtFlags)	\
-    ( (This)->lpVtbl -> GetTypeFlags(This,mask,ppdtFlags) ) 
-
-#define IPropertyDescriptionSearchInfo_GetViewFlags(This,ppdvFlags)	\
-    ( (This)->lpVtbl -> GetViewFlags(This,ppdvFlags) ) 
-
-#define IPropertyDescriptionSearchInfo_GetDefaultColumnWidth(This,pcxChars)	\
-    ( (This)->lpVtbl -> GetDefaultColumnWidth(This,pcxChars) ) 
-
-#define IPropertyDescriptionSearchInfo_GetDisplayType(This,pdisplaytype)	\
-    ( (This)->lpVtbl -> GetDisplayType(This,pdisplaytype) ) 
-
-#define IPropertyDescriptionSearchInfo_GetColumnState(This,pcsFlags)	\
-    ( (This)->lpVtbl -> GetColumnState(This,pcsFlags) ) 
-
-#define IPropertyDescriptionSearchInfo_GetGroupingRange(This,pgr)	\
-    ( (This)->lpVtbl -> GetGroupingRange(This,pgr) ) 
-
-#define IPropertyDescriptionSearchInfo_GetRelativeDescriptionType(This,prdt)	\
-    ( (This)->lpVtbl -> GetRelativeDescriptionType(This,prdt) ) 
-
-#define IPropertyDescriptionSearchInfo_GetRelativeDescription(This,propvar1,propvar2,ppszDesc1,ppszDesc2)	\
-    ( (This)->lpVtbl -> GetRelativeDescription(This,propvar1,propvar2,ppszDesc1,ppszDesc2) ) 
-
-#define IPropertyDescriptionSearchInfo_GetSortDescription(This,psd)	\
-    ( (This)->lpVtbl -> GetSortDescription(This,psd) ) 
-
-#define IPropertyDescriptionSearchInfo_GetSortDescriptionLabel(This,fDescending,ppszDescription)	\
-    ( (This)->lpVtbl -> GetSortDescriptionLabel(This,fDescending,ppszDescription) ) 
-
-#define IPropertyDescriptionSearchInfo_GetAggregationType(This,paggtype)	\
-    ( (This)->lpVtbl -> GetAggregationType(This,paggtype) ) 
-
-#define IPropertyDescriptionSearchInfo_GetConditionType(This,pcontype,popDefault)	\
-    ( (This)->lpVtbl -> GetConditionType(This,pcontype,popDefault) ) 
-
-#define IPropertyDescriptionSearchInfo_GetEnumTypeList(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetEnumTypeList(This,riid,ppv) ) 
-
-#define IPropertyDescriptionSearchInfo_CoerceToCanonicalValue(This,ppropvar)	\
-    ( (This)->lpVtbl -> CoerceToCanonicalValue(This,ppropvar) ) 
-
-#define IPropertyDescriptionSearchInfo_FormatForDisplay(This,propvar,pdfFlags,ppszDisplay)	\
-    ( (This)->lpVtbl -> FormatForDisplay(This,propvar,pdfFlags,ppszDisplay) ) 
-
-#define IPropertyDescriptionSearchInfo_IsValueCanonical(This,propvar)	\
-    ( (This)->lpVtbl -> IsValueCanonical(This,propvar) ) 
-
-
-#define IPropertyDescriptionSearchInfo_GetSearchInfoFlags(This,ppdsiFlags)	\
-    ( (This)->lpVtbl -> GetSearchInfoFlags(This,ppdsiFlags) ) 
-
-#define IPropertyDescriptionSearchInfo_GetColumnIndexType(This,ppdciType)	\
-    ( (This)->lpVtbl -> GetColumnIndexType(This,ppdciType) ) 
-
-#define IPropertyDescriptionSearchInfo_GetProjectionString(This,ppszProjection)	\
-    ( (This)->lpVtbl -> GetProjectionString(This,ppszProjection) ) 
-
-#define IPropertyDescriptionSearchInfo_GetMaxSize(This,pcbMaxSize)	\
-    ( (This)->lpVtbl -> GetMaxSize(This,pcbMaxSize) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyDescriptionSearchInfo_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propsys_0000_0014 */
-/* [local] */ 
-
-/* [v1_enum] */ 
-enum tagPROPDESC_ENUMFILTER
-    {	PDEF_ALL	= 0,
-	PDEF_SYSTEM	= 1,
-	PDEF_NONSYSTEM	= 2,
-	PDEF_VIEWABLE	= 3,
-	PDEF_QUERYABLE	= 4,
-	PDEF_INFULLTEXTQUERY	= 5,
-	PDEF_COLUMN	= 6
-    } ;
-typedef enum tagPROPDESC_ENUMFILTER PROPDESC_ENUMFILTER;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0014_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0014_v0_0_s_ifspec;
-
-#ifndef __IPropertySystem_INTERFACE_DEFINED__
-#define __IPropertySystem_INTERFACE_DEFINED__
-
-/* interface IPropertySystem */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertySystem;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("ca724e8a-c3e6-442b-88a4-6fb0db8035a3")
-    IPropertySystem : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyDescription( 
-            /* [in] */ __RPC__in REFPROPERTYKEY propkey,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyDescriptionByName( 
-            /* [string][in] */ __RPC__in LPCWSTR pszCanonicalName,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyDescriptionListFromString( 
-            /* [string][in] */ __RPC__in LPCWSTR pszPropList,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE EnumeratePropertyDescriptions( 
-            /* [in] */ PROPDESC_ENUMFILTER filterOn,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE FormatForDisplay( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdff,
-            /* [size_is][string][out] */ __RPC__out_ecount_full_string(cchText) LPWSTR pszText,
-            /* [in] */ DWORD cchText) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE FormatForDisplayAlloc( 
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdff,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDisplay) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RegisterPropertySchema( 
-            /* [string][in] */ __RPC__in LPCWSTR pszPath) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE UnregisterPropertySchema( 
-            /* [string][in] */ __RPC__in LPCWSTR pszPath) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RefreshPropertySchema( void) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertySystemVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertySystem * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertySystem * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertySystem * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyDescription )( 
-            IPropertySystem * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY propkey,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyDescriptionByName )( 
-            IPropertySystem * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszCanonicalName,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyDescriptionListFromString )( 
-            IPropertySystem * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszPropList,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *EnumeratePropertyDescriptions )( 
-            IPropertySystem * This,
-            /* [in] */ PROPDESC_ENUMFILTER filterOn,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *FormatForDisplay )( 
-            IPropertySystem * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdff,
-            /* [size_is][string][out] */ __RPC__out_ecount_full_string(cchText) LPWSTR pszText,
-            /* [in] */ DWORD cchText);
-        
-        HRESULT ( STDMETHODCALLTYPE *FormatForDisplayAlloc )( 
-            IPropertySystem * This,
-            /* [in] */ __RPC__in REFPROPERTYKEY key,
-            /* [in] */ __RPC__in REFPROPVARIANT propvar,
-            /* [in] */ PROPDESC_FORMAT_FLAGS pdff,
-            /* [string][out] */ __RPC__deref_out_opt_string LPWSTR *ppszDisplay);
-        
-        HRESULT ( STDMETHODCALLTYPE *RegisterPropertySchema )( 
-            IPropertySystem * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszPath);
-        
-        HRESULT ( STDMETHODCALLTYPE *UnregisterPropertySchema )( 
-            IPropertySystem * This,
-            /* [string][in] */ __RPC__in LPCWSTR pszPath);
-        
-        HRESULT ( STDMETHODCALLTYPE *RefreshPropertySchema )( 
-            IPropertySystem * This);
-        
-        END_INTERFACE
-    } IPropertySystemVtbl;
-
-    interface IPropertySystem
-    {
-        CONST_VTBL struct IPropertySystemVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertySystem_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertySystem_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertySystem_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertySystem_GetPropertyDescription(This,propkey,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyDescription(This,propkey,riid,ppv) ) 
-
-#define IPropertySystem_GetPropertyDescriptionByName(This,pszCanonicalName,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyDescriptionByName(This,pszCanonicalName,riid,ppv) ) 
-
-#define IPropertySystem_GetPropertyDescriptionListFromString(This,pszPropList,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyDescriptionListFromString(This,pszPropList,riid,ppv) ) 
-
-#define IPropertySystem_EnumeratePropertyDescriptions(This,filterOn,riid,ppv)	\
-    ( (This)->lpVtbl -> EnumeratePropertyDescriptions(This,filterOn,riid,ppv) ) 
-
-#define IPropertySystem_FormatForDisplay(This,key,propvar,pdff,pszText,cchText)	\
-    ( (This)->lpVtbl -> FormatForDisplay(This,key,propvar,pdff,pszText,cchText) ) 
-
-#define IPropertySystem_FormatForDisplayAlloc(This,key,propvar,pdff,ppszDisplay)	\
-    ( (This)->lpVtbl -> FormatForDisplayAlloc(This,key,propvar,pdff,ppszDisplay) ) 
-
-#define IPropertySystem_RegisterPropertySchema(This,pszPath)	\
-    ( (This)->lpVtbl -> RegisterPropertySchema(This,pszPath) ) 
-
-#define IPropertySystem_UnregisterPropertySchema(This,pszPath)	\
-    ( (This)->lpVtbl -> UnregisterPropertySchema(This,pszPath) ) 
-
-#define IPropertySystem_RefreshPropertySchema(This)	\
-    ( (This)->lpVtbl -> RefreshPropertySchema(This) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertySystem_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyDescriptionList_INTERFACE_DEFINED__
-#define __IPropertyDescriptionList_INTERFACE_DEFINED__
-
-/* interface IPropertyDescriptionList */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyDescriptionList;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("1f9fc1d0-c39b-4b26-817f-011967d3440e")
-    IPropertyDescriptionList : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetCount( 
-            /* [out] */ __RPC__out UINT *pcElem) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetAt( 
-            /* [in] */ UINT iElem,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyDescriptionListVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyDescriptionList * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyDescriptionList * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyDescriptionList * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetCount )( 
-            IPropertyDescriptionList * This,
-            /* [out] */ __RPC__out UINT *pcElem);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetAt )( 
-            IPropertyDescriptionList * This,
-            /* [in] */ UINT iElem,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        END_INTERFACE
-    } IPropertyDescriptionListVtbl;
-
-    interface IPropertyDescriptionList
-    {
-        CONST_VTBL struct IPropertyDescriptionListVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyDescriptionList_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyDescriptionList_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyDescriptionList_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyDescriptionList_GetCount(This,pcElem)	\
-    ( (This)->lpVtbl -> GetCount(This,pcElem) ) 
-
-#define IPropertyDescriptionList_GetAt(This,iElem,riid,ppv)	\
-    ( (This)->lpVtbl -> GetAt(This,iElem,riid,ppv) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyDescriptionList_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertyStoreFactory_INTERFACE_DEFINED__
-#define __IPropertyStoreFactory_INTERFACE_DEFINED__
-
-/* interface IPropertyStoreFactory */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertyStoreFactory;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("bc110b6d-57e8-4148-a9c6-91015ab2f3a5")
-    IPropertyStoreFactory : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyStore( 
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [unique][in] */ __RPC__in_opt IUnknown *pUnkFactory,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyStoreForKeys( 
-            /* [unique][in] */ __RPC__in_opt const PROPERTYKEY *rgKeys,
-            /* [in] */ UINT cKeys,
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertyStoreFactoryVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertyStoreFactory * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertyStoreFactory * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertyStoreFactory * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyStore )( 
-            IPropertyStoreFactory * This,
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [unique][in] */ __RPC__in_opt IUnknown *pUnkFactory,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyStoreForKeys )( 
-            IPropertyStoreFactory * This,
-            /* [unique][in] */ __RPC__in_opt const PROPERTYKEY *rgKeys,
-            /* [in] */ UINT cKeys,
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        END_INTERFACE
-    } IPropertyStoreFactoryVtbl;
-
-    interface IPropertyStoreFactory
-    {
-        CONST_VTBL struct IPropertyStoreFactoryVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertyStoreFactory_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertyStoreFactory_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertyStoreFactory_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertyStoreFactory_GetPropertyStore(This,flags,pUnkFactory,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyStore(This,flags,pUnkFactory,riid,ppv) ) 
-
-#define IPropertyStoreFactory_GetPropertyStoreForKeys(This,rgKeys,cKeys,flags,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyStoreForKeys(This,rgKeys,cKeys,flags,riid,ppv) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertyStoreFactory_INTERFACE_DEFINED__ */
-
-
-#ifndef __IDelayedPropertyStoreFactory_INTERFACE_DEFINED__
-#define __IDelayedPropertyStoreFactory_INTERFACE_DEFINED__
-
-/* interface IDelayedPropertyStoreFactory */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IDelayedPropertyStoreFactory;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("40d4577f-e237-4bdb-bd69-58f089431b6a")
-    IDelayedPropertyStoreFactory : public IPropertyStoreFactory
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetDelayedPropertyStore( 
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [in] */ DWORD dwStoreId,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IDelayedPropertyStoreFactoryVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IDelayedPropertyStoreFactory * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IDelayedPropertyStoreFactory * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IDelayedPropertyStoreFactory * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyStore )( 
-            IDelayedPropertyStoreFactory * This,
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [unique][in] */ __RPC__in_opt IUnknown *pUnkFactory,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyStoreForKeys )( 
-            IDelayedPropertyStoreFactory * This,
-            /* [unique][in] */ __RPC__in_opt const PROPERTYKEY *rgKeys,
-            /* [in] */ UINT cKeys,
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetDelayedPropertyStore )( 
-            IDelayedPropertyStoreFactory * This,
-            /* [in] */ GETPROPERTYSTOREFLAGS flags,
-            /* [in] */ DWORD dwStoreId,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        END_INTERFACE
-    } IDelayedPropertyStoreFactoryVtbl;
-
-    interface IDelayedPropertyStoreFactory
-    {
-        CONST_VTBL struct IDelayedPropertyStoreFactoryVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IDelayedPropertyStoreFactory_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IDelayedPropertyStoreFactory_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IDelayedPropertyStoreFactory_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IDelayedPropertyStoreFactory_GetPropertyStore(This,flags,pUnkFactory,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyStore(This,flags,pUnkFactory,riid,ppv) ) 
-
-#define IDelayedPropertyStoreFactory_GetPropertyStoreForKeys(This,rgKeys,cKeys,flags,riid,ppv)	\
-    ( (This)->lpVtbl -> GetPropertyStoreForKeys(This,rgKeys,cKeys,flags,riid,ppv) ) 
-
-
-#define IDelayedPropertyStoreFactory_GetDelayedPropertyStore(This,flags,dwStoreId,riid,ppv)	\
-    ( (This)->lpVtbl -> GetDelayedPropertyStore(This,flags,dwStoreId,riid,ppv) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IDelayedPropertyStoreFactory_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propsys_0000_0018 */
-/* [local] */ 
-
-/* [v1_enum] */ 
-enum tagPERSIST_SPROPSTORE_FLAGS
-    {	FPSPS_READONLY	= 0x1
-    } ;
-typedef int PERSIST_SPROPSTORE_FLAGS;
-
-typedef struct tagSERIALIZEDPROPSTORAGE SERIALIZEDPROPSTORAGE;
-
-typedef SERIALIZEDPROPSTORAGE __unaligned *PUSERIALIZEDPROPSTORAGE;
-
-typedef const SERIALIZEDPROPSTORAGE __unaligned *PCUSERIALIZEDPROPSTORAGE;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0018_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0018_v0_0_s_ifspec;
-
-#ifndef __IPersistSerializedPropStorage_INTERFACE_DEFINED__
-#define __IPersistSerializedPropStorage_INTERFACE_DEFINED__
-
-/* interface IPersistSerializedPropStorage */
-/* [object][local][unique][uuid] */ 
-
-
-EXTERN_C const IID IID_IPersistSerializedPropStorage;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("e318ad57-0aa0-450f-aca5-6fab7103d917")
-    IPersistSerializedPropStorage : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE SetFlags( 
-            /* [in] */ PERSIST_SPROPSTORE_FLAGS flags) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetPropertyStorage( 
-            /* [in] */ 
-            __in_bcount(cb)  PCUSERIALIZEDPROPSTORAGE psps,
-            /* [in] */ 
-            __in  DWORD cb) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetPropertyStorage( 
-            /* [out] */ 
-            __deref_out_bcount(*pcb)  SERIALIZEDPROPSTORAGE **ppsps,
-            /* [out] */ 
-            __out  DWORD *pcb) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPersistSerializedPropStorageVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPersistSerializedPropStorage * This,
-            /* [in] */ REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPersistSerializedPropStorage * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPersistSerializedPropStorage * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetFlags )( 
-            IPersistSerializedPropStorage * This,
-            /* [in] */ PERSIST_SPROPSTORE_FLAGS flags);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetPropertyStorage )( 
-            IPersistSerializedPropStorage * This,
-            /* [in] */ 
-            __in_bcount(cb)  PCUSERIALIZEDPROPSTORAGE psps,
-            /* [in] */ 
-            __in  DWORD cb);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetPropertyStorage )( 
-            IPersistSerializedPropStorage * This,
-            /* [out] */ 
-            __deref_out_bcount(*pcb)  SERIALIZEDPROPSTORAGE **ppsps,
-            /* [out] */ 
-            __out  DWORD *pcb);
-        
-        END_INTERFACE
-    } IPersistSerializedPropStorageVtbl;
-
-    interface IPersistSerializedPropStorage
-    {
-        CONST_VTBL struct IPersistSerializedPropStorageVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPersistSerializedPropStorage_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPersistSerializedPropStorage_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPersistSerializedPropStorage_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPersistSerializedPropStorage_SetFlags(This,flags)	\
-    ( (This)->lpVtbl -> SetFlags(This,flags) ) 
-
-#define IPersistSerializedPropStorage_SetPropertyStorage(This,psps,cb)	\
-    ( (This)->lpVtbl -> SetPropertyStorage(This,psps,cb) ) 
-
-#define IPersistSerializedPropStorage_GetPropertyStorage(This,ppsps,pcb)	\
-    ( (This)->lpVtbl -> GetPropertyStorage(This,ppsps,pcb) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPersistSerializedPropStorage_INTERFACE_DEFINED__ */
-
-
-#ifndef __IPropertySystemChangeNotify_INTERFACE_DEFINED__
-#define __IPropertySystemChangeNotify_INTERFACE_DEFINED__
-
-/* interface IPropertySystemChangeNotify */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IPropertySystemChangeNotify;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("fa955fd9-38be-4879-a6ce-824cf52d609f")
-    IPropertySystemChangeNotify : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE SchemaRefreshed( void) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IPropertySystemChangeNotifyVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IPropertySystemChangeNotify * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IPropertySystemChangeNotify * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IPropertySystemChangeNotify * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *SchemaRefreshed )( 
-            IPropertySystemChangeNotify * This);
-        
-        END_INTERFACE
-    } IPropertySystemChangeNotifyVtbl;
-
-    interface IPropertySystemChangeNotify
-    {
-        CONST_VTBL struct IPropertySystemChangeNotifyVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IPropertySystemChangeNotify_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IPropertySystemChangeNotify_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IPropertySystemChangeNotify_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IPropertySystemChangeNotify_SchemaRefreshed(This)	\
-    ( (This)->lpVtbl -> SchemaRefreshed(This) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IPropertySystemChangeNotify_INTERFACE_DEFINED__ */
-
-
-#ifndef __ICreateObject_INTERFACE_DEFINED__
-#define __ICreateObject_INTERFACE_DEFINED__
-
-/* interface ICreateObject */
-/* [object][unique][uuid] */ 
-
-
-EXTERN_C const IID IID_ICreateObject;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("75121952-e0d0-43e5-9380-1d80483acf72")
-    ICreateObject : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE CreateObject( 
-            /* [in] */ __RPC__in REFCLSID clsid,
-            /* [unique][in] */ __RPC__in_opt IUnknown *pUnkOuter,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct ICreateObjectVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ICreateObject * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ICreateObject * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ICreateObject * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *CreateObject )( 
-            ICreateObject * This,
-            /* [in] */ __RPC__in REFCLSID clsid,
-            /* [unique][in] */ __RPC__in_opt IUnknown *pUnkOuter,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ __RPC__deref_out_opt void **ppv);
-        
-        END_INTERFACE
-    } ICreateObjectVtbl;
-
-    interface ICreateObject
-    {
-        CONST_VTBL struct ICreateObjectVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ICreateObject_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ICreateObject_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ICreateObject_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define ICreateObject_CreateObject(This,clsid,pUnkOuter,riid,ppv)	\
-    ( (This)->lpVtbl -> CreateObject(This,clsid,pUnkOuter,riid,ppv) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ICreateObject_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_propsys_0000_0021 */
-/* [local] */ 
-
-// Format a property value for display purposes
-PSSTDAPI PSFormatForDisplay(
-    __in REFPROPERTYKEY propkey,
-    __in REFPROPVARIANT propvar,
-    __in PROPDESC_FORMAT_FLAGS pdfFlags,
-    __out_ecount(cchText) LPWSTR pwszText,
-    __in DWORD cchText);
-
-PSSTDAPI PSFormatForDisplayAlloc(
-    __in REFPROPERTYKEY key,
-    __in REFPROPVARIANT propvar,
-    __in PROPDESC_FORMAT_FLAGS pdff,
-    __deref_out PWSTR *ppszDisplay);
-
-PSSTDAPI PSFormatPropertyValue(
-    __in IPropertyStore *pps,
-    __in IPropertyDescription *ppd,
-    __in PROPDESC_FORMAT_FLAGS pdff,
-    __deref_out LPWSTR *ppszDisplay);
-
-
-#define PKEY_PIDSTR_MAX     10   // will take care of any long integer value
-#define GUIDSTRING_MAX      (1 + 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 + 1 + 1)  // "{12345678-1234-1234-1234-123456789012}"
-#define PKEYSTR_MAX         (GUIDSTRING_MAX + 1 + PKEY_PIDSTR_MAX)
-
-// Convert a PROPERTYKEY to and from a PWSTR
-PSSTDAPI PSStringFromPropertyKey(
-    __in REFPROPERTYKEY pkey,
-    __out_ecount(cch) LPWSTR psz,
-    __in UINT cch);
-
-PSSTDAPI PSPropertyKeyFromString(
-    __in LPCWSTR pszString,
-    __out PROPERTYKEY *pkey);
-
-
-// Creates an in-memory property store
-// Returns an IPropertyStore, IPersistSerializedPropStorage, and related interfaces interface
-PSSTDAPI PSCreateMemoryPropertyStore(
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Create a read-only, delay-bind multiplexing property store
-// Returns an IPropertyStore interface or related interfaces
-PSSTDAPI PSCreateDelayedMultiplexPropertyStore(
-    __in GETPROPERTYSTOREFLAGS flags,
-    __in IDelayedPropertyStoreFactory *pdpsf,
-    __in_ecount(cStores) const DWORD *rgStoreIds,
-    __in DWORD cStores,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Create a read-only property store from one or more sources (which each must support either IPropertyStore or IPropertySetStorage)
-// Returns an IPropertyStore interface or related interfaces
-PSSTDAPI PSCreateMultiplexPropertyStore(
-    __in_ecount(cStores) IUnknown **prgpunkStores,
-    __in DWORD cStores,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Create a container for IPropertyChanges
-// Returns an IPropertyChangeArray interface
-PSSTDAPI PSCreatePropertyChangeArray(
-    __in_ecount_opt(cChanges) const PROPERTYKEY *rgpropkey,
-    __in_ecount_opt(cChanges) const PKA_FLAGS *rgflags,
-    __in_ecount_opt(cChanges) const PROPVARIANT *rgpropvar,
-    __in UINT cChanges,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Create a simple property change
-// Returns an IPropertyChange interface
-PSSTDAPI PSCreateSimplePropertyChange(
-    __in PKA_FLAGS flags,
-    __in REFPROPERTYKEY key,
-    __in REFPROPVARIANT propvar,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Get a property description
-// Returns an IPropertyDescription interface
-PSSTDAPI PSGetPropertyDescription(
-    __in REFPROPERTYKEY propkey,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-PSSTDAPI PSGetPropertyDescriptionByName(
-    __in LPCWSTR pszCanonicalName,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Lookup a per-machine registered file property handler
-PSSTDAPI PSLookupPropertyHandlerCLSID(
-    __in PCWSTR pszFilePath,
-    __out CLSID *pclsid);
-// Get a property handler, on Vista or downlevel to XP
-// punkItem is a shell item created with an SHCreateItemXXX API
-// Returns an IPropertyStore
-PSSTDAPI PSGetItemPropertyHandler(
-    __in IUnknown *punkItem,
-    __in BOOL fReadWrite,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Get a property handler, on Vista or downlevel to XP
-// punkItem is a shell item created with an SHCreateItemXXX API
-// punkCreateObject supports ICreateObject
-// Returns an IPropertyStore
-PSSTDAPI PSGetItemPropertyHandlerWithCreateObject(
-    __in IUnknown *punkItem,
-    __in BOOL fReadWrite,
-    __in IUnknown *punkCreateObject,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Get or set a property value from a store
-PSSTDAPI PSGetPropertyValue(
-    __in IPropertyStore *pps,
-    __in IPropertyDescription *ppd,
-    __out PROPVARIANT *ppropvar);
-
-PSSTDAPI PSSetPropertyValue(
-    __in IPropertyStore *pps,
-    __in IPropertyDescription *ppd,
-    __in REFPROPVARIANT propvar);
-
-
-// Interact with the set of property descriptions
-PSSTDAPI PSRegisterPropertySchema(
-    __in PCWSTR pszPath);
-
-PSSTDAPI PSUnregisterPropertySchema(
-    __in PCWSTR pszPath);
-
-PSSTDAPI PSRefreshPropertySchema();
-
-// Returns either: IPropertyDescriptionList or IEnumUnknown interfaces
-PSSTDAPI PSEnumeratePropertyDescriptions(
-    __in PROPDESC_ENUMFILTER filterOn,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Convert between a PROPERTYKEY and its canonical name
-PSSTDAPI PSGetPropertyKeyFromName(
-    __in PCWSTR pszName,
-    __out PROPERTYKEY *ppropkey);
-
-PSSTDAPI PSGetNameFromPropertyKey(
-    __in REFPROPERTYKEY propkey,
-    __deref_out PWSTR *ppszCanonicalName);
-
-
-// Coerce and canonicalize a property value
-PSSTDAPI PSCoerceToCanonicalValue(
-    __in REFPROPERTYKEY key,
-    __inout PROPVARIANT *ppropvar);
-
-
-// Convert a 'prop:' string into a list of property descriptions
-// Returns an IPropertyDescriptionList interface
-PSSTDAPI PSGetPropertyDescriptionListFromString(
-    __in LPCWSTR pszPropList,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Wrap an IPropertySetStorage interface in an IPropertyStore interface
-// Returns an IPropertyStore or related interface
-PSSTDAPI PSCreatePropertyStoreFromPropertySetStorage(
-    __in IPropertySetStorage *ppss,
-    DWORD grfMode,
-    REFIID riid,
-    __deref_out void **ppv);
-
-
-// punkSource must support IPropertyStore or IPropertySetStorage
-// On success, the returned ppv is guaranteed to support IPropertyStore.
-// If punkSource already supports IPropertyStore, no wrapper is created.
-PSSTDAPI PSCreatePropertyStoreFromObject(
-    __in IUnknown *punk,
-    __in DWORD grfMode,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// punkSource must support IPropertyStore
-// riid may be IPropertyStore, IPropertySetStorage, IPropertyStoreCapabilities, or IObjectProvider
-PSSTDAPI PSCreateAdapterFromPropertyStore(
-    __in IPropertyStore *pps,
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Talk to the property system using an interface
-// Returns an IPropertySystem interface
-PSSTDAPI PSGetPropertySystem(
-    __in REFIID riid,
-    __deref_out void **ppv);
-
-
-// Obtain a value from serialized property storage
-PSSTDAPI PSGetPropertyFromPropertyStorage(
-    __in_bcount(cb) PCUSERIALIZEDPROPSTORAGE psps, 
-    __in DWORD cb, 
-    __in REFPROPERTYKEY rpkey, 
-    __out PROPVARIANT *ppropvar);
-
-
-// Obtain a named value from serialized property storage
-PSSTDAPI PSGetNamedPropertyFromPropertyStorage(
-    __in_bcount(cb) PCUSERIALIZEDPROPSTORAGE psps, 
-    __in DWORD cb, 
-    __in LPCWSTR pszName, 
-    __out PROPVARIANT *ppropvar);
-
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0021_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_propsys_0000_0021_v0_0_s_ifspec;
-
-
-#ifndef __PropSysObjects_LIBRARY_DEFINED__
-#define __PropSysObjects_LIBRARY_DEFINED__
-
-/* library PropSysObjects */
-/* [version][lcid][uuid] */ 
-
-
-EXTERN_C const IID LIBID_PropSysObjects;
-
-EXTERN_C const CLSID CLSID_InMemoryPropertyStore;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("9a02e012-6303-4e1e-b9a1-630f802592c5")
-InMemoryPropertyStore;
-#endif
-
-EXTERN_C const CLSID CLSID_PropertySystem;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("b8967f85-58ae-4f46-9fb2-5d7904798f4b")
-PropertySystem;
-#endif
-#endif /* __PropSysObjects_LIBRARY_DEFINED__ */
-
-/* Additional Prototypes for ALL interfaces */
-
-unsigned long             __RPC_USER  BSTR_UserSize(     unsigned long *, unsigned long            , BSTR * ); 
-unsigned char * __RPC_USER  BSTR_UserMarshal(  unsigned long *, unsigned char *, BSTR * ); 
-unsigned char * __RPC_USER  BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); 
-void                      __RPC_USER  BSTR_UserFree(     unsigned long *, BSTR * ); 
-
-unsigned long             __RPC_USER  LPSAFEARRAY_UserSize(     unsigned long *, unsigned long            , LPSAFEARRAY * ); 
-unsigned char * __RPC_USER  LPSAFEARRAY_UserMarshal(  unsigned long *, unsigned char *, LPSAFEARRAY * ); 
-unsigned char * __RPC_USER  LPSAFEARRAY_UserUnmarshal(unsigned long *, unsigned char *, LPSAFEARRAY * ); 
-void                      __RPC_USER  LPSAFEARRAY_UserFree(     unsigned long *, LPSAFEARRAY * ); 
-
-unsigned long             __RPC_USER  BSTR_UserSize64(     unsigned long *, unsigned long            , BSTR * ); 
-unsigned char * __RPC_USER  BSTR_UserMarshal64(  unsigned long *, unsigned char *, BSTR * ); 
-unsigned char * __RPC_USER  BSTR_UserUnmarshal64(unsigned long *, unsigned char *, BSTR * ); 
-void                      __RPC_USER  BSTR_UserFree64(     unsigned long *, BSTR * ); 
-
-unsigned long             __RPC_USER  LPSAFEARRAY_UserSize64(     unsigned long *, unsigned long            , LPSAFEARRAY * ); 
-unsigned char * __RPC_USER  LPSAFEARRAY_UserMarshal64(  unsigned long *, unsigned char *, LPSAFEARRAY * ); 
-unsigned char * __RPC_USER  LPSAFEARRAY_UserUnmarshal64(unsigned long *, unsigned char *, LPSAFEARRAY * ); 
-void                      __RPC_USER  LPSAFEARRAY_UserFree64(     unsigned long *, LPSAFEARRAY * ); 
-
-/* [local] */ HRESULT STDMETHODCALLTYPE IInitializeWithStream_Initialize_Proxy( 
-    IInitializeWithStream * This,
-    /* [in] */ IStream *pstream,
-    /* [in] */ DWORD grfMode);
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IInitializeWithStream_Initialize_Stub( 
-    IInitializeWithStream * This,
-    /* [in] */ __RPC__in_opt IStream *pstream,
-    /* [in] */ DWORD grfMode);
-
-/* [local] */ HRESULT STDMETHODCALLTYPE IPropertyDescription_CoerceToCanonicalValue_Proxy( 
-    IPropertyDescription * This,
-    /* [out][in] */ PROPVARIANT *ppropvar);
-
-
-/* [call_as] */ HRESULT STDMETHODCALLTYPE IPropertyDescription_CoerceToCanonicalValue_Stub( 
-    IPropertyDescription * This,
-    /* [in] */ __RPC__in REFPROPVARIANT propvar,
-    /* [out] */ __RPC__out PROPVARIANT *ppropvar);
-
-
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/rpcsal.h b/portaudio/src/hostapi/wasapi/mingw-include/rpcsal.h
deleted file mode 100644
index 70adbc6fd..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/rpcsal.h
+++ /dev/null
@@ -1,113 +0,0 @@
-#pragma once
-
-#if __GNUC__ >=3
-#pragma GCC system_header
-#endif
-
-#define RPC_range(min,max)
-
-#define __RPC__in           
-#define __RPC__in_string
-#define __RPC__in_opt_string
-#define __RPC__deref_opt_in_opt
-#define __RPC__opt_in_opt_string
-#define __RPC__in_ecount(size) 
-#define __RPC__in_ecount_full(size)
-#define __RPC__in_ecount_full_string(size)
-#define __RPC__in_ecount_part(size, length)
-#define __RPC__in_ecount_full_opt(size)
-#define __RPC__in_ecount_full_opt_string(size)
-#define __RPC__inout_ecount_full_opt_string(size)
-#define __RPC__in_ecount_part_opt(size, length)
-
-#define __RPC__deref_in 
-#define __RPC__deref_in_string
-#define __RPC__deref_opt_in
-#define __RPC__deref_in_opt
-#define __RPC__deref_in_ecount(size) 
-#define __RPC__deref_in_ecount_part(size, length) 
-#define __RPC__deref_in_ecount_full(size) 
-#define __RPC__deref_in_ecount_full_opt(size)
-#define __RPC__deref_in_ecount_full_string(size)
-#define __RPC__deref_in_ecount_full_opt_string(size)
-#define __RPC__deref_in_ecount_opt(size) 
-#define __RPC__deref_in_ecount_opt_string(size)
-#define __RPC__deref_in_ecount_part_opt(size, length) 
-
-// [out]
-#define __RPC__out     
-#define __RPC__out_ecount(size) 
-#define __RPC__out_ecount_part(size, length) 
-#define __RPC__out_ecount_full(size)
-#define __RPC__out_ecount_full_string(size)
-
-// [in,out] 
-#define __RPC__inout                                   
-#define __RPC__inout_string
-#define __RPC__opt_inout
-#define __RPC__inout_ecount(size)                     
-#define __RPC__inout_ecount_part(size, length)    
-#define __RPC__inout_ecount_full(size)          
-#define __RPC__inout_ecount_full_string(size)          
-
-// [in,unique] 
-#define __RPC__in_opt       
-#define __RPC__in_ecount_opt(size)   
-
-
-// [in,out,unique] 
-#define __RPC__inout_opt    
-#define __RPC__inout_ecount_opt(size)  
-#define __RPC__inout_ecount_part_opt(size, length) 
-#define __RPC__inout_ecount_full_opt(size)     
-#define __RPC__inout_ecount_full_string(size)
-
-// [out] **
-#define __RPC__deref_out   
-#define __RPC__deref_out_string
-#define __RPC__deref_out_opt 
-#define __RPC__deref_out_opt_string
-#define __RPC__deref_out_ecount(size) 
-#define __RPC__deref_out_ecount_part(size, length) 
-#define __RPC__deref_out_ecount_full(size)  
-#define __RPC__deref_out_ecount_full_string(size)
-
-
-// [in,out] **, second pointer decoration. 
-#define __RPC__deref_inout    
-#define __RPC__deref_inout_string
-#define __RPC__deref_inout_opt 
-#define __RPC__deref_inout_opt_string
-#define __RPC__deref_inout_ecount_full(size)
-#define __RPC__deref_inout_ecount_full_string(size)
-#define __RPC__deref_inout_ecount_opt(size) 
-#define __RPC__deref_inout_ecount_part_opt(size, length) 
-#define __RPC__deref_inout_ecount_full_opt(size) 
-#define __RPC__deref_inout_ecount_full_opt_string(size) 
-
-// #define __RPC_out_opt    out_opt is not allowed in rpc
-
-// [in,out,unique] 
-#define __RPC__deref_opt_inout  
-#define __RPC__deref_opt_inout_string
-#define __RPC__deref_opt_inout_ecount(size)     
-#define __RPC__deref_opt_inout_ecount_part(size, length) 
-#define __RPC__deref_opt_inout_ecount_full(size) 
-#define __RPC__deref_opt_inout_ecount_full_string(size)
-
-#define __RPC__deref_out_ecount_opt(size) 
-#define __RPC__deref_out_ecount_part_opt(size, length) 
-#define __RPC__deref_out_ecount_full_opt(size) 
-#define __RPC__deref_out_ecount_full_opt_string(size)
-
-#define __RPC__deref_opt_inout_opt      
-#define __RPC__deref_opt_inout_opt_string
-#define __RPC__deref_opt_inout_ecount_opt(size)   
-#define __RPC__deref_opt_inout_ecount_part_opt(size, length) 
-#define __RPC__deref_opt_inout_ecount_full_opt(size) 
-#define __RPC__deref_opt_inout_ecount_full_opt_string(size) 
-
-#define __RPC_full_pointer  
-#define __RPC_unique_pointer
-#define __RPC_ref_pointer
-#define __RPC_string                               
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/sal.h b/portaudio/src/hostapi/wasapi/mingw-include/sal.h
deleted file mode 100644
index d7b99fc99..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/sal.h
+++ /dev/null
@@ -1,252 +0,0 @@
-#pragma once
-
-#if __GNUC__ >=3
-#pragma GCC system_header
-#endif
-
-/*#define __null*/ // << Conflicts with GCC internal type __null
-#define __notnull
-#define __maybenull
-#define __readonly
-#define __notreadonly
-#define __maybereadonly
-#define __valid
-#define __notvalid
-#define __maybevalid
-#define __readableTo(extent)
-#define __elem_readableTo(size)
-#define __byte_readableTo(size)
-#define __writableTo(size)
-#define __elem_writableTo(size)
-#define __byte_writableTo(size)
-#define __deref
-#define __pre
-#define __post
-#define __precond(expr)
-#define __postcond(expr)
-#define __exceptthat
-#define __execeptthat
-#define __inner_success(expr)
-#define __inner_checkReturn
-#define __inner_typefix(ctype)
-#define __inner_override
-#define __inner_callback
-#define __inner_blocksOn(resource)
-#define __inner_fallthrough_dec
-#define __inner_fallthrough
-#define __refparam
-#define __inner_control_entrypoint(category)
-#define __inner_data_entrypoint(category)
-
-#define __ecount(size)
-#define __bcount(size)
-#define __in
-#define __in_ecount(size)
-#define __in_bcount(size)
-#define __in_z
-#define __in_ecount_z(size)
-#define __in_bcount_z(size)
-#define __in_nz
-#define __in_ecount_nz(size)
-#define __in_bcount_nz(size)
-#define __out
-#define __out_ecount(size)
-#define __out_bcount(size)
-#define __out_ecount_part(size,length)
-#define __out_bcount_part(size,length)
-#define __out_ecount_full(size)
-#define __out_bcount_full(size)
-#define __out_z
-#define __out_z_opt
-#define __out_ecount_z(size)
-#define __out_bcount_z(size)
-#define __out_ecount_part_z(size,length)
-#define __out_bcount_part_z(size,length)
-#define __out_ecount_full_z(size)
-#define __out_bcount_full_z(size)
-#define __out_nz
-#define __out_nz_opt
-#define __out_ecount_nz(size)
-#define __out_bcount_nz(size)
-#define __inout
-#define __inout_ecount(size)
-#define __inout_bcount(size)
-#define __inout_ecount_part(size,length)
-#define __inout_bcount_part(size,length)
-#define __inout_ecount_full(size)
-#define __inout_bcount_full(size)
-#define __inout_z
-#define __inout_ecount_z(size)
-#define __inout_bcount_z(size)
-#define __inout_nz
-#define __inout_ecount_nz(size)
-#define __inout_bcount_nz(size)
-#define __ecount_opt(size)
-#define __bcount_opt(size)
-#define __in_opt
-#define __in_ecount_opt(size)
-#define __in_bcount_opt(size)
-#define __in_z_opt
-#define __in_ecount_z_opt(size)
-#define __in_bcount_z_opt(size)
-#define __in_nz_opt
-#define __in_ecount_nz_opt(size)
-#define __in_bcount_nz_opt(size)
-#define __out_opt
-#define __out_ecount_opt(size)
-#define __out_bcount_opt(size)
-#define __out_ecount_part_opt(size,length)
-#define __out_bcount_part_opt(size,length)
-#define __out_ecount_full_opt(size)
-#define __out_bcount_full_opt(size)
-#define __out_ecount_z_opt(size)
-#define __out_bcount_z_opt(size)
-#define __out_ecount_part_z_opt(size,length)
-#define __out_bcount_part_z_opt(size,length)
-#define __out_ecount_full_z_opt(size)
-#define __out_bcount_full_z_opt(size)
-#define __out_ecount_nz_opt(size)
-#define __out_bcount_nz_opt(size)
-#define __inout_opt
-#define __inout_ecount_opt(size)
-#define __inout_bcount_opt(size)
-#define __inout_ecount_part_opt(size,length)
-#define __inout_bcount_part_opt(size,length)
-#define __inout_ecount_full_opt(size)
-#define __inout_bcount_full_opt(size)
-#define __inout_z_opt
-#define __inout_ecount_z_opt(size)
-#define __inout_ecount_z_opt(size)
-#define __inout_bcount_z_opt(size)
-#define __inout_nz_opt
-#define __inout_ecount_nz_opt(size)
-#define __inout_bcount_nz_opt(size)
-#define __deref_ecount(size)
-#define __deref_bcount(size)
-#define __deref_out
-#define __deref_out_ecount(size)
-#define __deref_out_bcount(size)
-#define __deref_out_ecount_part(size,length)
-#define __deref_out_bcount_part(size,length)
-#define __deref_out_ecount_full(size)
-#define __deref_out_bcount_full(size)
-#define __deref_out_z
-#define __deref_out_ecount_z(size)
-#define __deref_out_bcount_z(size)
-#define __deref_out_nz
-#define __deref_out_ecount_nz(size)
-#define __deref_out_bcount_nz(size)
-#define __deref_inout
-#define __deref_inout_z
-#define __deref_inout_ecount(size)
-#define __deref_inout_bcount(size)
-#define __deref_inout_ecount_part(size,length)
-#define __deref_inout_bcount_part(size,length)
-#define __deref_inout_ecount_full(size)
-#define __deref_inout_bcount_full(size)
-#define __deref_inout_z
-#define __deref_inout_ecount_z(size)
-#define __deref_inout_bcount_z(size)
-#define __deref_inout_nz
-#define __deref_inout_ecount_nz(size)
-#define __deref_inout_bcount_nz(size)
-#define __deref_ecount_opt(size)
-#define __deref_bcount_opt(size)
-#define __deref_out_opt
-#define __deref_out_ecount_opt(size)
-#define __deref_out_bcount_opt(size)
-#define __deref_out_ecount_part_opt(size,length)
-#define __deref_out_bcount_part_opt(size,length)
-#define __deref_out_ecount_full_opt(size)
-#define __deref_out_bcount_full_opt(size)
-#define __deref_out_z_opt
-#define __deref_out_ecount_z_opt(size)
-#define __deref_out_bcount_z_opt(size)
-#define __deref_out_nz_opt
-#define __deref_out_ecount_nz_opt(size)
-#define __deref_out_bcount_nz_opt(size)
-#define __deref_inout_opt
-#define __deref_inout_ecount_opt(size)
-#define __deref_inout_bcount_opt(size)
-#define __deref_inout_ecount_part_opt(size,length)
-#define __deref_inout_bcount_part_opt(size,length)
-#define __deref_inout_ecount_full_opt(size)
-#define __deref_inout_bcount_full_opt(size)
-#define __deref_inout_z_opt
-#define __deref_inout_ecount_z_opt(size)
-#define __deref_inout_bcount_z_opt(size)
-#define __deref_inout_nz_opt
-#define __deref_inout_ecount_nz_opt(size)
-#define __deref_inout_bcount_nz_opt(size)
-#define __deref_opt_ecount(size)
-#define __deref_opt_bcount(size)
-#define __deref_opt_out
-#define __deref_opt_out_z
-#define __deref_opt_out_ecount(size)
-#define __deref_opt_out_bcount(size)
-#define __deref_opt_out_ecount_part(size,length)
-#define __deref_opt_out_bcount_part(size,length)
-#define __deref_opt_out_ecount_full(size)
-#define __deref_opt_out_bcount_full(size)
-#define __deref_opt_inout
-#define __deref_opt_inout_ecount(size)
-#define __deref_opt_inout_bcount(size)
-#define __deref_opt_inout_ecount_part(size,length)
-#define __deref_opt_inout_bcount_part(size,length)
-#define __deref_opt_inout_ecount_full(size)
-#define __deref_opt_inout_bcount_full(size)
-#define __deref_opt_inout_z
-#define __deref_opt_inout_ecount_z(size)
-#define __deref_opt_inout_bcount_z(size)
-#define __deref_opt_inout_nz
-#define __deref_opt_inout_ecount_nz(size)
-#define __deref_opt_inout_bcount_nz(size)
-#define __deref_opt_ecount_opt(size)
-#define __deref_opt_bcount_opt(size)
-#define __deref_opt_out_opt
-#define __deref_opt_out_ecount_opt(size)
-#define __deref_opt_out_bcount_opt(size)
-#define __deref_opt_out_ecount_part_opt(size,length)
-#define __deref_opt_out_bcount_part_opt(size,length)
-#define __deref_opt_out_ecount_full_opt(size)
-#define __deref_opt_out_bcount_full_opt(size)
-#define __deref_opt_out_z_opt
-#define __deref_opt_out_ecount_z_opt(size)
-#define __deref_opt_out_bcount_z_opt(size)
-#define __deref_opt_out_nz_opt
-#define __deref_opt_out_ecount_nz_opt(size)
-#define __deref_opt_out_bcount_nz_opt(size)
-#define __deref_opt_inout_opt
-#define __deref_opt_inout_ecount_opt(size)
-#define __deref_opt_inout_bcount_opt(size)
-#define __deref_opt_inout_ecount_part_opt(size,length)
-#define __deref_opt_inout_bcount_part_opt(size,length)
-#define __deref_opt_inout_ecount_full_opt(size)
-#define __deref_opt_inout_bcount_full_opt(size)
-#define __deref_opt_inout_z_opt
-#define __deref_opt_inout_ecount_z_opt(size)
-#define __deref_opt_inout_bcount_z_opt(size)
-#define __deref_opt_inout_nz_opt
-#define __deref_opt_inout_ecount_nz_opt(size)
-#define __deref_opt_inout_bcount_nz_opt(size)
-
-#define __success(expr)
-#define __nullterminated
-#define __nullnullterminated
-#define __reserved
-#define __checkReturn
-#define __typefix(ctype)
-#define __override
-#define __callback
-#define __format_string
-#define __blocksOn(resource)
-#define __control_entrypoint(category)
-#define __data_entrypoint(category)
-
-#ifndef __fallthrough
-    #define __fallthrough __inner_fallthrough
-#endif
-
-#ifndef __analysis_assume
-    #define __analysis_assume(expr)
-#endif
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/sdkddkver.h b/portaudio/src/hostapi/wasapi/mingw-include/sdkddkver.h
deleted file mode 100644
index 0e4d20764..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/sdkddkver.h
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
-
-Copyright (c) Microsoft Corporation. All rights reserved.
-
-Module Name:
-
-    sdkddkver.h
-
-Abstract:
-
-    Master include file for versioning windows SDK/DDK.
-
-*/
-
-#ifndef _INC_SDKDDKVER
-#define _INC_SDKDDKVER
-
-#pragma once
-
-//
-// _WIN32_WINNT version constants
-//
-#define _WIN32_WINNT_NT4                    0x0400
-#define _WIN32_WINNT_WIN2K                  0x0500
-#define _WIN32_WINNT_WINXP                  0x0501
-#define _WIN32_WINNT_WS03                   0x0502
-#define _WIN32_WINNT_LONGHORN               0x0600
-
-//
-// _WIN32_IE_ version constants
-//
-#define _WIN32_IE_IE20                      0x0200
-#define _WIN32_IE_IE30                      0x0300
-#define _WIN32_IE_IE302                     0x0302
-#define _WIN32_IE_IE40                      0x0400
-#define _WIN32_IE_IE401                     0x0401
-#define _WIN32_IE_IE50                      0x0500
-#define _WIN32_IE_IE501                     0x0501
-#define _WIN32_IE_IE55                      0x0550
-#define _WIN32_IE_IE60                      0x0600
-#define _WIN32_IE_IE60SP1                   0x0601
-#define _WIN32_IE_IE60SP2                   0x0603
-#define _WIN32_IE_IE70                      0x0700
-
-//
-// IE <-> OS version mapping
-//
-// NT4 supports IE versions 2.0 -> 6.0 SP1
-#define _WIN32_IE_NT4                       _WIN32_IE_IE20
-#define _WIN32_IE_NT4SP1                    _WIN32_IE_IE20
-#define _WIN32_IE_NT4SP2                    _WIN32_IE_IE20
-#define _WIN32_IE_NT4SP3                    _WIN32_IE_IE302
-#define _WIN32_IE_NT4SP4                    _WIN32_IE_IE401
-#define _WIN32_IE_NT4SP5                    _WIN32_IE_IE401
-#define _WIN32_IE_NT4SP6                    _WIN32_IE_IE50
-// Win98 supports IE versions 4.01 -> 6.0 SP1
-#define _WIN32_IE_WIN98                     _WIN32_IE_IE401
-// Win98SE supports IE versions 5.0 -> 6.0 SP1
-#define _WIN32_IE_WIN98SE                   _WIN32_IE_IE50
-// WinME supports IE versions 5.5 -> 6.0 SP1
-#define _WIN32_IE_WINME                     _WIN32_IE_IE55
-// Win2k supports IE versions 5.01 -> 6.0 SP1
-#define _WIN32_IE_WIN2K                     _WIN32_IE_IE501
-#define _WIN32_IE_WIN2KSP1                  _WIN32_IE_IE501
-#define _WIN32_IE_WIN2KSP2                  _WIN32_IE_IE501
-#define _WIN32_IE_WIN2KSP3                  _WIN32_IE_IE501
-#define _WIN32_IE_WIN2KSP4                  _WIN32_IE_IE501
-#define _WIN32_IE_XP                        _WIN32_IE_IE60
-#define _WIN32_IE_XPSP1                     _WIN32_IE_IE60SP1
-#define _WIN32_IE_XPSP2                     _WIN32_IE_IE60SP2
-#define _WIN32_IE_WS03                      0x0602
-#define _WIN32_IE_WS03SP1                   _WIN32_IE_IE60SP2
-#define _WIN32_IE_LONGHORN                  _WIN32_IE_IE70
-
-
-//
-// NTDDI version constants
-//
-#define NTDDI_WIN2K                         0x05000000
-#define NTDDI_WIN2KSP1                      0x05000100
-#define NTDDI_WIN2KSP2                      0x05000200
-#define NTDDI_WIN2KSP3                      0x05000300
-#define NTDDI_WIN2KSP4                      0x05000400
-
-#define NTDDI_WINXP                         0x05010000
-#define NTDDI_WINXPSP1                      0x05010100
-#define NTDDI_WINXPSP2                      0x05010200
-
-#define NTDDI_WS03                          0x05020000
-#define NTDDI_WS03SP1                       0x05020100
-
-#define NTDDI_LONGHORN                      0x06000000
-
-//
-// masks for version macros
-//
-#define OSVERSION_MASK      0xFFFF0000
-#define SPVERSION_MASK      0x0000FF00
-#define SUBVERSION_MASK     0x000000FF
-
-
-//
-// macros to extract various version fields from the NTDDI version
-//
-#define OSVER(Version)  ((Version) & OSVERSION_MASK)
-#define SPVER(Version)  (((Version) & SPVERSION_MASK) >> 8)
-#define SUBVER(Version) (((Version) & SUBVERSION_MASK) )
-
-
-#if defined(DECLSPEC_DEPRECATED_DDK)
-
-// deprecate in 2k or later
-#if (NTDDI_VERSION >= NTDDI_WIN2K)
-#define DECLSPEC_DEPRECATED_DDK_WIN2K DECLSPEC_DEPRECATED_DDK
-#else
-#define DECLSPEC_DEPRECATED_DDK_WIN2K
-#endif
-
-// deprecate in XP or later
-#if (NTDDI_VERSION >= NTDDI_WINXP)
-#define DECLSPEC_DEPRECATED_DDK_WINXP DECLSPEC_DEPRECATED_DDK
-#else
-#define DECLSPEC_DEPRECATED_DDK_WINXP
-#endif
-
-// deprecate in WS03 or later
-#if (NTDDI_VERSION >= NTDDI_WS03)
-#define DECLSPEC_DEPRECATED_DDK_WIN2003 DECLSPEC_DEPRECATED_DDK
-#else
-#define DECLSPEC_DEPRECATED_DDK_WIN2003
-#endif
-
-// deprecate in WS03 or later
-#if (NTDDI_VERSION >= NTDDI_LONGHORN)
-#define DECLSPEC_DEPRECATED_DDK_LONGHORN DECLSPEC_DEPRECATED_DDK
-#else
-#define DECLSPEC_DEPRECATED_DDK_LONGHORN
-#endif
-
-#endif // defined(DECLSPEC_DEPRECATED_DDK)
-
-
-//
-// if versions aren't already defined, default to most current
-//
-
-#define NTDDI_VERSION_FROM_WIN32_WINNT2(ver)    ver##0000
-#define NTDDI_VERSION_FROM_WIN32_WINNT(ver)     NTDDI_VERSION_FROM_WIN32_WINNT2(ver)
-
-#if !defined(_WIN32_WINNT) && !defined(_CHICAGO_)
-#define  _WIN32_WINNT   0x0600
-#endif
-
-#ifndef NTDDI_VERSION
-#ifdef _WIN32_WINNT
-// set NTDDI_VERSION based on _WIN32_WINNT
-#define NTDDI_VERSION   NTDDI_VERSION_FROM_WIN32_WINNT(_WIN32_WINNT)
-#else
-#define NTDDI_VERSION   0x06000000
-#endif
-#endif
-
-#ifndef WINVER
-#ifdef _WIN32_WINNT
-// set WINVER based on _WIN32_WINNT
-#define WINVER          _WIN32_WINNT
-#else
-#define WINVER          0x0600
-#endif
-#endif
-
-#ifndef _WIN32_IE
-#ifdef _WIN32_WINNT
-// set _WIN32_IE based on _WIN32_WINNT
-#if (_WIN32_WINNT <= _WIN32_WINNT_NT4)
-#define _WIN32_IE       _WIN32_IE_IE50
-#elif (_WIN32_WINNT <= _WIN32_WINNT_WIN2K)
-#define _WIN32_IE       _WIN32_IE_IE501
-#elif (_WIN32_WINNT <= _WIN32_WINNT_WINXP)
-#define _WIN32_IE       _WIN32_IE_IE60
-#elif (_WIN32_WINNT <= _WIN32_WINNT_WS03)
-#define _WIN32_IE       0x0602
-#else
-#define _WIN32_IE       0x0700
-#endif
-#else
-#define _WIN32_IE       0x0700
-#endif
-#endif
-
-//
-// Sanity check for compatible versions
-//
-#if defined(_WIN32_WINNT) && !defined(MIDL_PASS) && !defined(RC_INVOKED)
-
-#if (defined(WINVER) && (WINVER < 0x0400) && (_WIN32_WINNT > 0x0400))
-#error WINVER setting conflicts with _WIN32_WINNT setting
-#endif
-
-#if (((OSVERSION_MASK & NTDDI_VERSION) == NTDDI_WIN2K) && (_WIN32_WINNT != _WIN32_WINNT_WIN2K))
-#error NTDDI_VERSION setting conflicts with _WIN32_WINNT setting
-#endif
-
-#if (((OSVERSION_MASK & NTDDI_VERSION) == NTDDI_WINXP) && (_WIN32_WINNT != _WIN32_WINNT_WINXP))
-#error NTDDI_VERSION setting conflicts with _WIN32_WINNT setting
-#endif
-
-#if (((OSVERSION_MASK & NTDDI_VERSION) == NTDDI_WS03) && (_WIN32_WINNT != _WIN32_WINNT_WS03))
-#error NTDDI_VERSION setting conflicts with _WIN32_WINNT setting
-#endif
-
-#if (((OSVERSION_MASK & NTDDI_VERSION) == NTDDI_LONGHORN) && (_WIN32_WINNT != _WIN32_WINNT_LONGHORN))
-#error NTDDI_VERSION setting conflicts with _WIN32_WINNT setting
-#endif
-
-#if ((_WIN32_WINNT < _WIN32_WINNT_WIN2K) && (_WIN32_IE > _WIN32_IE_IE60SP1))
-#error _WIN32_WINNT settings conflicts with _WIN32_IE setting
-#endif
-
-#endif  // defined(_WIN32_WINNT) && !defined(MIDL_PASS) && !defined(_WINRESRC_)
-
-
-#endif  // !_INC_SDKDDKVER
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/shtypes.h b/portaudio/src/hostapi/wasapi/mingw-include/shtypes.h
deleted file mode 100644
index 5106b3f7b..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/shtypes.h
+++ /dev/null
@@ -1,468 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for shtypes.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 500
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-
-#ifndef __shtypes_h__
-#define __shtypes_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-/* header files for imported files */
-#include "wtypes.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_shtypes_0000_0000 */
-/* [local] */ 
-
-//+-------------------------------------------------------------------------
-//
-//  Microsoft Windows
-//  Copyright (c) Microsoft Corporation. All rights reserved.
-//
-//--------------------------------------------------------------------------
-//===========================================================================
-//
-// Object identifiers in the explorer's name space (ItemID and IDList)
-//
-//  All the items that the user can browse with the explorer (such as files,
-// directories, servers, work-groups, etc.) has an identifier which is unique
-// among items within the parent folder. Those identifiers are called item
-// IDs (SHITEMID). Since all its parent folders have their own item IDs,
-// any items can be uniquely identified by a list of item IDs, which is called
-// an ID list (ITEMIDLIST).
-//
-//  ID lists are almost always allocated by the task allocator (see some
-// description below as well as OLE 2.0 SDK) and may be passed across
-// some of shell interfaces (such as IShellFolder). Each item ID in an ID list
-// is only meaningful to its parent folder (which has generated it), and all
-// the clients must treat it as an opaque binary data except the first two
-// bytes, which indicates the size of the item ID.
-//
-//  When a shell extension -- which implements the IShellFolder interace --
-// generates an item ID, it may put any information in it, not only the data
-// with that it needs to identifies the item, but also some additional
-// information, which would help implementing some other functions efficiently.
-// For example, the shell's IShellFolder implementation of file system items
-// stores the primary (long) name of a file or a directory as the item
-// identifier, but it also stores its alternative (short) name, size and date
-// etc.
-//
-//  When an ID list is passed to one of shell APIs (such as SHGetPathFromIDList),
-// it is always an absolute path -- relative from the root of the name space,
-// which is the desktop folder. When an ID list is passed to one of IShellFolder
-// member function, it is always a relative path from the folder (unless it
-// is explicitly specified).
-//
-//===========================================================================
-//
-// SHITEMID -- Item ID  (mkid)
-//     USHORT      cb;             // Size of the ID (including cb itself)
-//     BYTE        abID[];         // The item ID (variable length)
-//
-#include <pshpack1.h>
-typedef struct _SHITEMID
-    {
-    USHORT cb;
-    BYTE abID[ 1 ];
-    } 	SHITEMID;
-
-#include <poppack.h>
-#if defined(_M_IX86)
-#define __unaligned
-#endif // __unaligned
-typedef SHITEMID __unaligned *LPSHITEMID;
-
-typedef const SHITEMID __unaligned *LPCSHITEMID;
-
-//
-// ITEMIDLIST -- List if item IDs (combined with 0-terminator)
-//
-#include <pshpack1.h>
-typedef struct _ITEMIDLIST
-    {
-    SHITEMID mkid;
-    } 	ITEMIDLIST;
-
-#if defined(STRICT_TYPED_ITEMIDS) && defined(__cplusplus)
-typedef struct _ITEMIDLIST_RELATIVE : ITEMIDLIST {} ITEMIDLIST_RELATIVE;
-typedef struct _ITEMID_CHILD : ITEMIDLIST_RELATIVE {} ITEMID_CHILD;
-typedef struct _ITEMIDLIST_ABSOLUTE : ITEMIDLIST_RELATIVE {} ITEMIDLIST_ABSOLUTE;
-#else // !(defined(STRICT_TYPED_ITEMIDS) && defined(__cplusplus))
-typedef ITEMIDLIST ITEMIDLIST_RELATIVE;
-
-typedef ITEMIDLIST ITEMID_CHILD;
-
-typedef ITEMIDLIST ITEMIDLIST_ABSOLUTE;
-
-#endif // defined(STRICT_TYPED_ITEMIDS) && defined(__cplusplus)
-#include <poppack.h>
-typedef /* [unique] */  __RPC_unique_pointer BYTE_BLOB *wirePIDL;
-
-typedef /* [wire_marshal] */ ITEMIDLIST __unaligned *LPITEMIDLIST;
-
-typedef /* [wire_marshal] */ const ITEMIDLIST __unaligned *LPCITEMIDLIST;
-
-#if defined(STRICT_TYPED_ITEMIDS) && defined(__cplusplus)
-typedef /* [wire_marshal] */ ITEMIDLIST_ABSOLUTE *PIDLIST_ABSOLUTE;
-
-typedef /* [wire_marshal] */ const ITEMIDLIST_ABSOLUTE *PCIDLIST_ABSOLUTE;
-
-typedef /* [wire_marshal] */ const ITEMIDLIST_ABSOLUTE __unaligned *PCUIDLIST_ABSOLUTE;
-
-typedef /* [wire_marshal] */ ITEMIDLIST_RELATIVE *PIDLIST_RELATIVE;
-
-typedef /* [wire_marshal] */ const ITEMIDLIST_RELATIVE *PCIDLIST_RELATIVE;
-
-typedef /* [wire_marshal] */ ITEMIDLIST_RELATIVE __unaligned *PUIDLIST_RELATIVE;
-
-typedef /* [wire_marshal] */ const ITEMIDLIST_RELATIVE __unaligned *PCUIDLIST_RELATIVE;
-
-typedef /* [wire_marshal] */ ITEMID_CHILD *PITEMID_CHILD;
-
-typedef /* [wire_marshal] */ const ITEMID_CHILD *PCITEMID_CHILD;
-
-typedef /* [wire_marshal] */ ITEMID_CHILD __unaligned *PUITEMID_CHILD;
-
-typedef /* [wire_marshal] */ const ITEMID_CHILD __unaligned *PCUITEMID_CHILD;
-
-typedef const PCUITEMID_CHILD *PCUITEMID_CHILD_ARRAY;
-
-typedef const PCUIDLIST_RELATIVE *PCUIDLIST_RELATIVE_ARRAY;
-
-typedef const PCIDLIST_ABSOLUTE *PCIDLIST_ABSOLUTE_ARRAY;
-
-typedef const PCUIDLIST_ABSOLUTE *PCUIDLIST_ABSOLUTE_ARRAY;
-
-#else // !(defined(STRICT_TYPED_ITEMIDS) && defined(__cplusplus))
-#define PIDLIST_ABSOLUTE         LPITEMIDLIST
-#define PCIDLIST_ABSOLUTE        LPCITEMIDLIST
-#define PCUIDLIST_ABSOLUTE       LPCITEMIDLIST
-#define PIDLIST_RELATIVE         LPITEMIDLIST
-#define PCIDLIST_RELATIVE        LPCITEMIDLIST
-#define PUIDLIST_RELATIVE        LPITEMIDLIST
-#define PCUIDLIST_RELATIVE       LPCITEMIDLIST
-#define PITEMID_CHILD            LPITEMIDLIST
-#define PCITEMID_CHILD           LPCITEMIDLIST
-#define PUITEMID_CHILD           LPITEMIDLIST
-#define PCUITEMID_CHILD          LPCITEMIDLIST
-#define PCUITEMID_CHILD_ARRAY    LPCITEMIDLIST *
-#define PCUIDLIST_RELATIVE_ARRAY LPCITEMIDLIST *
-#define PCIDLIST_ABSOLUTE_ARRAY  LPCITEMIDLIST *
-#define PCUIDLIST_ABSOLUTE_ARRAY LPCITEMIDLIST *
-#endif // defined(STRICT_TYPED_ITEMIDS) && defined(__cplusplus)
-#ifdef MIDL_PASS
-typedef struct _WIN32_FIND_DATAA
-    {
-    DWORD dwFileAttributes;
-    FILETIME ftCreationTime;
-    FILETIME ftLastAccessTime;
-    FILETIME ftLastWriteTime;
-    DWORD nFileSizeHigh;
-    DWORD nFileSizeLow;
-    DWORD dwReserved0;
-    DWORD dwReserved1;
-    CHAR cFileName[ 260 ];
-    CHAR cAlternateFileName[ 14 ];
-    } 	WIN32_FIND_DATAA;
-
-typedef struct _WIN32_FIND_DATAA *PWIN32_FIND_DATAA;
-
-typedef struct _WIN32_FIND_DATAA *LPWIN32_FIND_DATAA;
-
-typedef struct _WIN32_FIND_DATAW
-    {
-    DWORD dwFileAttributes;
-    FILETIME ftCreationTime;
-    FILETIME ftLastAccessTime;
-    FILETIME ftLastWriteTime;
-    DWORD nFileSizeHigh;
-    DWORD nFileSizeLow;
-    DWORD dwReserved0;
-    DWORD dwReserved1;
-    WCHAR cFileName[ 260 ];
-    WCHAR cAlternateFileName[ 14 ];
-    } 	WIN32_FIND_DATAW;
-
-typedef struct _WIN32_FIND_DATAW *PWIN32_FIND_DATAW;
-
-typedef struct _WIN32_FIND_DATAW *LPWIN32_FIND_DATAW;
-
-#endif // MIDL_PASS
-//-------------------------------------------------------------------------
-//
-// struct STRRET
-//
-// structure for returning strings from IShellFolder member functions
-//
-//-------------------------------------------------------------------------
-//
-//  uType indicate which union member to use 
-//    STRRET_WSTR    Use STRRET.pOleStr     must be freed by caller of GetDisplayNameOf
-//    STRRET_OFFSET  Use STRRET.uOffset     Offset into SHITEMID for ANSI string 
-//    STRRET_CSTR    Use STRRET.cStr        ANSI Buffer
-//
-typedef /* [v1_enum] */ 
-enum tagSTRRET_TYPE
-    {	STRRET_WSTR	= 0,
-	STRRET_OFFSET	= 0x1,
-	STRRET_CSTR	= 0x2
-    } 	STRRET_TYPE;
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1200)
-#pragma warning(push)
-#pragma warning(disable:4201) /* nonstandard extension used : nameless struct/union */
-#pragma once
-#endif
-#include <pshpack8.h>
-typedef struct _STRRET
-    {
-    UINT uType;
-    union 
-        {
-        LPWSTR pOleStr;
-        UINT uOffset;
-        char cStr[ 260 ];
-        } 	DUMMYUNIONNAME;
-    } 	STRRET;
-
-#include <poppack.h>
-#if defined(_MSC_VER) && (_MSC_VER >= 1200)
-#pragma warning(pop)
-#endif
-typedef STRRET *LPSTRRET;
-
-//-------------------------------------------------------------------------
-//
-// struct SHELLDETAILS
-//
-// structure for returning strings from IShellDetails
-//
-//-------------------------------------------------------------------------
-//
-//  fmt;            // LVCFMT_* value (header only)
-//  cxChar;         // Number of 'average' characters (header only)
-//  str;            // String information
-//
-#include <pshpack1.h>
-typedef struct _SHELLDETAILS
-    {
-    int fmt;
-    int cxChar;
-    STRRET str;
-    } 	SHELLDETAILS;
-
-typedef struct _SHELLDETAILS *LPSHELLDETAILS;
-
-#include <poppack.h>
-
-#if (_WIN32_IE >= _WIN32_IE_IE60SP2)
-typedef /* [v1_enum] */ 
-enum tagPERCEIVED
-    {	PERCEIVED_TYPE_FIRST	= -3,
-	PERCEIVED_TYPE_CUSTOM	= -3,
-	PERCEIVED_TYPE_UNSPECIFIED	= -2,
-	PERCEIVED_TYPE_FOLDER	= -1,
-	PERCEIVED_TYPE_UNKNOWN	= 0,
-	PERCEIVED_TYPE_TEXT	= 1,
-	PERCEIVED_TYPE_IMAGE	= 2,
-	PERCEIVED_TYPE_AUDIO	= 3,
-	PERCEIVED_TYPE_VIDEO	= 4,
-	PERCEIVED_TYPE_COMPRESSED	= 5,
-	PERCEIVED_TYPE_DOCUMENT	= 6,
-	PERCEIVED_TYPE_SYSTEM	= 7,
-	PERCEIVED_TYPE_APPLICATION	= 8,
-	PERCEIVED_TYPE_GAMEMEDIA	= 9,
-	PERCEIVED_TYPE_CONTACTS	= 10,
-	PERCEIVED_TYPE_LAST	= 10
-    } 	PERCEIVED;
-
-#define PERCEIVEDFLAG_UNDEFINED     0x0000
-#define PERCEIVEDFLAG_SOFTCODED     0x0001
-#define PERCEIVEDFLAG_HARDCODED     0x0002
-#define PERCEIVEDFLAG_NATIVESUPPORT 0x0004
-#define PERCEIVEDFLAG_GDIPLUS       0x0010
-#define PERCEIVEDFLAG_WMSDK         0x0020
-#define PERCEIVEDFLAG_ZIPFOLDER     0x0040
-typedef DWORD PERCEIVEDFLAG;
-
-#endif  // _WIN32_IE_IE60SP2
-
-#if (NTDDI_VERSION >= NTDDI_LONGHORN)
-typedef struct _COMDLG_FILTERSPEC
-    {
-    LPCWSTR pszName;
-    LPCWSTR pszSpec;
-    } 	COMDLG_FILTERSPEC;
-
-typedef struct tagMACHINE_ID
-    {
-    char szName[ 16 ];
-    } 	MACHINE_ID;
-
-typedef struct tagDOMAIN_RELATIVE_OBJECTID
-    {
-    GUID guidVolume;
-    GUID guidObject;
-    } 	DOMAIN_RELATIVE_OBJECTID;
-
-typedef GUID KNOWNFOLDERID;
-
-#if 0
-typedef KNOWNFOLDERID *REFKNOWNFOLDERID;
-
-#endif // 0
-#ifdef __cplusplus
-#define REFKNOWNFOLDERID const KNOWNFOLDERID &
-#else // !__cplusplus
-#define REFKNOWNFOLDERID const KNOWNFOLDERID * __MIDL_CONST
-#endif // __cplusplus
-#endif  // NTDDI_LONGHORN
-typedef GUID FOLDERTYPEID;
-
-#if 0
-typedef FOLDERTYPEID *REFFOLDERTYPEID;
-
-#endif // 0
-#ifdef __cplusplus
-#define REFFOLDERTYPEID const FOLDERTYPEID &
-#else // !__cplusplus
-#define REFFOLDERTYPEID const FOLDERTYPEID * __MIDL_CONST
-#endif // __cplusplus
-typedef GUID TASKOWNERID;
-
-#if 0
-typedef TASKOWNERID *REFTASKOWNERID;
-
-#endif // 0
-#ifdef __cplusplus
-#define REFTASKOWNERID const TASKOWNERID &
-#else // !__cplusplus
-#define REFTASKOWNERID const TASKOWNERID * __MIDL_CONST
-#endif // __cplusplus
-#ifndef LF_FACESIZE
-typedef struct tagLOGFONTA
-    {
-    LONG lfHeight;
-    LONG lfWidth;
-    LONG lfEscapement;
-    LONG lfOrientation;
-    LONG lfWeight;
-    BYTE lfItalic;
-    BYTE lfUnderline;
-    BYTE lfStrikeOut;
-    BYTE lfCharSet;
-    BYTE lfOutPrecision;
-    BYTE lfClipPrecision;
-    BYTE lfQuality;
-    BYTE lfPitchAndFamily;
-    CHAR lfFaceName[ 32 ];
-    } 	LOGFONTA;
-
-typedef struct tagLOGFONTW
-    {
-    LONG lfHeight;
-    LONG lfWidth;
-    LONG lfEscapement;
-    LONG lfOrientation;
-    LONG lfWeight;
-    BYTE lfItalic;
-    BYTE lfUnderline;
-    BYTE lfStrikeOut;
-    BYTE lfCharSet;
-    BYTE lfOutPrecision;
-    BYTE lfClipPrecision;
-    BYTE lfQuality;
-    BYTE lfPitchAndFamily;
-    WCHAR lfFaceName[ 32 ];
-    } 	LOGFONTW;
-
-typedef LOGFONTA LOGFONT;
-
-#endif // LF_FACESIZE
-typedef /* [v1_enum] */ 
-enum tagSHCOLSTATE
-    {	SHCOLSTATE_TYPE_STR	= 0x1,
-	SHCOLSTATE_TYPE_INT	= 0x2,
-	SHCOLSTATE_TYPE_DATE	= 0x3,
-	SHCOLSTATE_TYPEMASK	= 0xf,
-	SHCOLSTATE_ONBYDEFAULT	= 0x10,
-	SHCOLSTATE_SLOW	= 0x20,
-	SHCOLSTATE_EXTENDED	= 0x40,
-	SHCOLSTATE_SECONDARYUI	= 0x80,
-	SHCOLSTATE_HIDDEN	= 0x100,
-	SHCOLSTATE_PREFER_VARCMP	= 0x200,
-	SHCOLSTATE_PREFER_FMTCMP	= 0x400,
-	SHCOLSTATE_NOSORTBYFOLDERNESS	= 0x800,
-	SHCOLSTATE_VIEWONLY	= 0x10000,
-	SHCOLSTATE_BATCHREAD	= 0x20000,
-	SHCOLSTATE_NO_GROUPBY	= 0x40000,
-	SHCOLSTATE_FIXED_WIDTH	= 0x1000,
-	SHCOLSTATE_NODPISCALE	= 0x2000,
-	SHCOLSTATE_FIXED_RATIO	= 0x4000,
-	SHCOLSTATE_DISPLAYMASK	= 0xf000
-    } 	SHCOLSTATE;
-
-typedef DWORD SHCOLSTATEF;
-
-typedef PROPERTYKEY SHCOLUMNID;
-
-typedef const SHCOLUMNID *LPCSHCOLUMNID;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_shtypes_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_shtypes_0000_0000_v0_0_s_ifspec;
-
-/* Additional Prototypes for ALL interfaces */
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/mingw-include/structuredquery.h b/portaudio/src/hostapi/wasapi/mingw-include/structuredquery.h
deleted file mode 100644
index a42ec89e7..000000000
--- a/portaudio/src/hostapi/wasapi/mingw-include/structuredquery.h
+++ /dev/null
@@ -1,2478 +0,0 @@
-
-
-/* this ALWAYS GENERATED file contains the definitions for the interfaces */
-
-
- /* File created by MIDL compiler version 7.00.0499 */
-/* Compiler settings for structuredquery.idl:
-    Oicf, W1, Zp8, env=Win32 (32b run)
-    protocol : dce , ms_ext, c_ext, robust
-    error checks: allocation ref bounds_check enum stub_data 
-    VC __declspec() decoration level: 
-         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
-         DECLSPEC_UUID(), MIDL_INTERFACE()
-*/
-//@@MIDL_FILE_HEADING(  )
-
-#pragma warning( disable: 4049 )  /* more than 64k source lines */
-
-
-/* verify that the <rpcndr.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCNDR_H_VERSION__
-#define __REQUIRED_RPCNDR_H_VERSION__ 475
-#endif
-
-/* verify that the <rpcsal.h> version is high enough to compile this file*/
-#ifndef __REQUIRED_RPCSAL_H_VERSION__
-#define __REQUIRED_RPCSAL_H_VERSION__ 100
-#endif
-
-#include "rpc.h"
-#include "rpcndr.h"
-
-#ifndef __RPCNDR_H_VERSION__
-#error this stub requires an updated version of <rpcndr.h>
-#endif // __RPCNDR_H_VERSION__
-
-#ifndef COM_NO_WINDOWS_H
-#include "windows.h"
-#include "ole2.h"
-#endif /*COM_NO_WINDOWS_H*/
-
-#ifndef __structuredquery_h__
-#define __structuredquery_h__
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1020)
-#pragma once
-#endif
-
-/* Forward Declarations */ 
-
-#ifndef __IQueryParser_FWD_DEFINED__
-#define __IQueryParser_FWD_DEFINED__
-typedef interface IQueryParser IQueryParser;
-#endif 	/* __IQueryParser_FWD_DEFINED__ */
-
-
-#ifndef __IConditionFactory_FWD_DEFINED__
-#define __IConditionFactory_FWD_DEFINED__
-typedef interface IConditionFactory IConditionFactory;
-#endif 	/* __IConditionFactory_FWD_DEFINED__ */
-
-
-#ifndef __IQuerySolution_FWD_DEFINED__
-#define __IQuerySolution_FWD_DEFINED__
-typedef interface IQuerySolution IQuerySolution;
-#endif 	/* __IQuerySolution_FWD_DEFINED__ */
-
-
-#ifndef __ICondition_FWD_DEFINED__
-#define __ICondition_FWD_DEFINED__
-typedef interface ICondition ICondition;
-#endif 	/* __ICondition_FWD_DEFINED__ */
-
-
-#ifndef __IConditionGenerator_FWD_DEFINED__
-#define __IConditionGenerator_FWD_DEFINED__
-typedef interface IConditionGenerator IConditionGenerator;
-#endif 	/* __IConditionGenerator_FWD_DEFINED__ */
-
-
-#ifndef __IRichChunk_FWD_DEFINED__
-#define __IRichChunk_FWD_DEFINED__
-typedef interface IRichChunk IRichChunk;
-#endif 	/* __IRichChunk_FWD_DEFINED__ */
-
-
-#ifndef __IInterval_FWD_DEFINED__
-#define __IInterval_FWD_DEFINED__
-typedef interface IInterval IInterval;
-#endif 	/* __IInterval_FWD_DEFINED__ */
-
-
-#ifndef __IMetaData_FWD_DEFINED__
-#define __IMetaData_FWD_DEFINED__
-typedef interface IMetaData IMetaData;
-#endif 	/* __IMetaData_FWD_DEFINED__ */
-
-
-#ifndef __IEntity_FWD_DEFINED__
-#define __IEntity_FWD_DEFINED__
-typedef interface IEntity IEntity;
-#endif 	/* __IEntity_FWD_DEFINED__ */
-
-
-#ifndef __IRelationship_FWD_DEFINED__
-#define __IRelationship_FWD_DEFINED__
-typedef interface IRelationship IRelationship;
-#endif 	/* __IRelationship_FWD_DEFINED__ */
-
-
-#ifndef __INamedEntity_FWD_DEFINED__
-#define __INamedEntity_FWD_DEFINED__
-typedef interface INamedEntity INamedEntity;
-#endif 	/* __INamedEntity_FWD_DEFINED__ */
-
-
-#ifndef __ISchemaProvider_FWD_DEFINED__
-#define __ISchemaProvider_FWD_DEFINED__
-typedef interface ISchemaProvider ISchemaProvider;
-#endif 	/* __ISchemaProvider_FWD_DEFINED__ */
-
-
-#ifndef __ITokenCollection_FWD_DEFINED__
-#define __ITokenCollection_FWD_DEFINED__
-typedef interface ITokenCollection ITokenCollection;
-#endif 	/* __ITokenCollection_FWD_DEFINED__ */
-
-
-#ifndef __INamedEntityCollector_FWD_DEFINED__
-#define __INamedEntityCollector_FWD_DEFINED__
-typedef interface INamedEntityCollector INamedEntityCollector;
-#endif 	/* __INamedEntityCollector_FWD_DEFINED__ */
-
-
-#ifndef __ISchemaLocalizerSupport_FWD_DEFINED__
-#define __ISchemaLocalizerSupport_FWD_DEFINED__
-typedef interface ISchemaLocalizerSupport ISchemaLocalizerSupport;
-#endif 	/* __ISchemaLocalizerSupport_FWD_DEFINED__ */
-
-
-#ifndef __IQueryParserManager_FWD_DEFINED__
-#define __IQueryParserManager_FWD_DEFINED__
-typedef interface IQueryParserManager IQueryParserManager;
-#endif 	/* __IQueryParserManager_FWD_DEFINED__ */
-
-
-#ifndef __QueryParser_FWD_DEFINED__
-#define __QueryParser_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class QueryParser QueryParser;
-#else
-typedef struct QueryParser QueryParser;
-#endif /* __cplusplus */
-
-#endif 	/* __QueryParser_FWD_DEFINED__ */
-
-
-#ifndef __NegationCondition_FWD_DEFINED__
-#define __NegationCondition_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class NegationCondition NegationCondition;
-#else
-typedef struct NegationCondition NegationCondition;
-#endif /* __cplusplus */
-
-#endif 	/* __NegationCondition_FWD_DEFINED__ */
-
-
-#ifndef __CompoundCondition_FWD_DEFINED__
-#define __CompoundCondition_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class CompoundCondition CompoundCondition;
-#else
-typedef struct CompoundCondition CompoundCondition;
-#endif /* __cplusplus */
-
-#endif 	/* __CompoundCondition_FWD_DEFINED__ */
-
-
-#ifndef __LeafCondition_FWD_DEFINED__
-#define __LeafCondition_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class LeafCondition LeafCondition;
-#else
-typedef struct LeafCondition LeafCondition;
-#endif /* __cplusplus */
-
-#endif 	/* __LeafCondition_FWD_DEFINED__ */
-
-
-#ifndef __ConditionFactory_FWD_DEFINED__
-#define __ConditionFactory_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class ConditionFactory ConditionFactory;
-#else
-typedef struct ConditionFactory ConditionFactory;
-#endif /* __cplusplus */
-
-#endif 	/* __ConditionFactory_FWD_DEFINED__ */
-
-
-#ifndef __Interval_FWD_DEFINED__
-#define __Interval_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class Interval Interval;
-#else
-typedef struct Interval Interval;
-#endif /* __cplusplus */
-
-#endif 	/* __Interval_FWD_DEFINED__ */
-
-
-#ifndef __QueryParserManager_FWD_DEFINED__
-#define __QueryParserManager_FWD_DEFINED__
-
-#ifdef __cplusplus
-typedef class QueryParserManager QueryParserManager;
-#else
-typedef struct QueryParserManager QueryParserManager;
-#endif /* __cplusplus */
-
-#endif 	/* __QueryParserManager_FWD_DEFINED__ */
-
-
-/* header files for imported files */
-#include "oaidl.h"
-#include "ocidl.h"
-#include "propidl.h"
-
-#ifdef __cplusplus
-extern "C"{
-#endif 
-
-
-/* interface __MIDL_itf_structuredquery_0000_0000 */
-/* [local] */ 
-
-
-
-
-
-
-
-
-
-
-
-typedef /* [v1_enum] */ 
-enum tagCONDITION_TYPE
-    {	CT_AND_CONDITION	= 0,
-	CT_OR_CONDITION	= ( CT_AND_CONDITION + 1 ) ,
-	CT_NOT_CONDITION	= ( CT_OR_CONDITION + 1 ) ,
-	CT_LEAF_CONDITION	= ( CT_NOT_CONDITION + 1 ) 
-    } 	CONDITION_TYPE;
-
-typedef /* [v1_enum] */ 
-enum tagCONDITION_OPERATION
-    {	COP_IMPLICIT	= 0,
-	COP_EQUAL	= ( COP_IMPLICIT + 1 ) ,
-	COP_NOTEQUAL	= ( COP_EQUAL + 1 ) ,
-	COP_LESSTHAN	= ( COP_NOTEQUAL + 1 ) ,
-	COP_GREATERTHAN	= ( COP_LESSTHAN + 1 ) ,
-	COP_LESSTHANOREQUAL	= ( COP_GREATERTHAN + 1 ) ,
-	COP_GREATERTHANOREQUAL	= ( COP_LESSTHANOREQUAL + 1 ) ,
-	COP_VALUE_STARTSWITH	= ( COP_GREATERTHANOREQUAL + 1 ) ,
-	COP_VALUE_ENDSWITH	= ( COP_VALUE_STARTSWITH + 1 ) ,
-	COP_VALUE_CONTAINS	= ( COP_VALUE_ENDSWITH + 1 ) ,
-	COP_VALUE_NOTCONTAINS	= ( COP_VALUE_CONTAINS + 1 ) ,
-	COP_DOSWILDCARDS	= ( COP_VALUE_NOTCONTAINS + 1 ) ,
-	COP_WORD_EQUAL	= ( COP_DOSWILDCARDS + 1 ) ,
-	COP_WORD_STARTSWITH	= ( COP_WORD_EQUAL + 1 ) ,
-	COP_APPLICATION_SPECIFIC	= ( COP_WORD_STARTSWITH + 1 ) 
-    } 	CONDITION_OPERATION;
-
-typedef /* [v1_enum] */ 
-enum tagSTRUCTURED_QUERY_SINGLE_OPTION
-    {	SQSO_SCHEMA	= 0,
-	SQSO_LOCALE_WORD_BREAKING	= ( SQSO_SCHEMA + 1 ) ,
-	SQSO_WORD_BREAKER	= ( SQSO_LOCALE_WORD_BREAKING + 1 ) ,
-	SQSO_NATURAL_SYNTAX	= ( SQSO_WORD_BREAKER + 1 ) ,
-	SQSO_AUTOMATIC_WILDCARD	= ( SQSO_NATURAL_SYNTAX + 1 ) ,
-	SQSO_TRACE_LEVEL	= ( SQSO_AUTOMATIC_WILDCARD + 1 ) ,
-	SQSO_LANGUAGE_KEYWORDS	= ( SQSO_TRACE_LEVEL + 1 ) 
-    } 	STRUCTURED_QUERY_SINGLE_OPTION;
-
-typedef /* [v1_enum] */ 
-enum tagSTRUCTURED_QUERY_MULTIOPTION
-    {	SQMO_VIRTUAL_PROPERTY	= 0,
-	SQMO_DEFAULT_PROPERTY	= ( SQMO_VIRTUAL_PROPERTY + 1 ) ,
-	SQMO_GENERATOR_FOR_TYPE	= ( SQMO_DEFAULT_PROPERTY + 1 ) 
-    } 	STRUCTURED_QUERY_MULTIOPTION;
-
-typedef /* [v1_enum] */ 
-enum tagSTRUCTURED_QUERY_PARSE_ERROR
-    {	SQPE_NONE	= 0,
-	SQPE_EXTRA_OPENING_PARENTHESIS	= ( SQPE_NONE + 1 ) ,
-	SQPE_EXTRA_CLOSING_PARENTHESIS	= ( SQPE_EXTRA_OPENING_PARENTHESIS + 1 ) ,
-	SQPE_IGNORED_MODIFIER	= ( SQPE_EXTRA_CLOSING_PARENTHESIS + 1 ) ,
-	SQPE_IGNORED_CONNECTOR	= ( SQPE_IGNORED_MODIFIER + 1 ) ,
-	SQPE_IGNORED_KEYWORD	= ( SQPE_IGNORED_CONNECTOR + 1 ) ,
-	SQPE_UNHANDLED	= ( SQPE_IGNORED_KEYWORD + 1 ) 
-    } 	STRUCTURED_QUERY_PARSE_ERROR;
-
-/* [v1_enum] */ 
-enum tagSTRUCTURED_QUERY_RESOLVE_OPTION
-    {	SQRO_DONT_RESOLVE_DATETIME	= 0x1,
-	SQRO_ALWAYS_ONE_INTERVAL	= 0x2,
-	SQRO_DONT_SIMPLIFY_CONDITION_TREES	= 0x4,
-	SQRO_DONT_MAP_RELATIONS	= 0x8,
-	SQRO_DONT_RESOLVE_RANGES	= 0x10,
-	SQRO_DONT_REMOVE_UNRESTRICTED_KEYWORDS	= 0x20,
-	SQRO_DONT_SPLIT_WORDS	= 0x40,
-	SQRO_IGNORE_PHRASE_ORDER	= 0x80
-    } ;
-typedef int STRUCTURED_QUERY_RESOLVE_OPTION;
-
-typedef /* [v1_enum] */ 
-enum tagINTERVAL_LIMIT_KIND
-    {	ILK_EXPLICIT_INCLUDED	= 0,
-	ILK_EXPLICIT_EXCLUDED	= ( ILK_EXPLICIT_INCLUDED + 1 ) ,
-	ILK_NEGATIVE_INFINITY	= ( ILK_EXPLICIT_EXCLUDED + 1 ) ,
-	ILK_POSITIVE_INFINITY	= ( ILK_NEGATIVE_INFINITY + 1 ) 
-    } 	INTERVAL_LIMIT_KIND;
-
-typedef /* [v1_enum] */ 
-enum tagQUERY_PARSER_MANAGER_OPTION
-    {	QPMO_SCHEMA_BINARY_NAME	= 0,
-	QPMO_PRELOCALIZED_SCHEMA_BINARY_PATH	= ( QPMO_SCHEMA_BINARY_NAME + 1 ) ,
-	QPMO_UNLOCALIZED_SCHEMA_BINARY_PATH	= ( QPMO_PRELOCALIZED_SCHEMA_BINARY_PATH + 1 ) ,
-	QPMO_LOCALIZED_SCHEMA_BINARY_PATH	= ( QPMO_UNLOCALIZED_SCHEMA_BINARY_PATH + 1 ) ,
-	QPMO_APPEND_LCID_TO_LOCALIZED_PATH	= ( QPMO_LOCALIZED_SCHEMA_BINARY_PATH + 1 ) ,
-	QPMO_LOCALIZER_SUPPORT	= ( QPMO_APPEND_LCID_TO_LOCALIZED_PATH + 1 ) 
-    } 	QUERY_PARSER_MANAGER_OPTION;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_structuredquery_0000_0000_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_structuredquery_0000_0000_v0_0_s_ifspec;
-
-#ifndef __IQueryParser_INTERFACE_DEFINED__
-#define __IQueryParser_INTERFACE_DEFINED__
-
-/* interface IQueryParser */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IQueryParser;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("2EBDEE67-3505-43f8-9946-EA44ABC8E5B0")
-    IQueryParser : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Parse( 
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [in] */ __RPC__in_opt IEnumUnknown *pCustomProperties,
-            /* [retval][out] */ __RPC__deref_out_opt IQuerySolution **ppSolution) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetOption( 
-            /* [in] */ STRUCTURED_QUERY_SINGLE_OPTION option,
-            /* [in] */ __RPC__in const PROPVARIANT *pOptionValue) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetOption( 
-            /* [in] */ STRUCTURED_QUERY_SINGLE_OPTION option,
-            /* [retval][out] */ __RPC__out PROPVARIANT *pOptionValue) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetMultiOption( 
-            /* [in] */ STRUCTURED_QUERY_MULTIOPTION option,
-            /* [in] */ __RPC__in LPCWSTR pszOptionKey,
-            /* [in] */ __RPC__in const PROPVARIANT *pOptionValue) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetSchemaProvider( 
-            /* [retval][out] */ __RPC__deref_out_opt ISchemaProvider **ppSchemaProvider) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RestateToString( 
-            /* [in] */ __RPC__in_opt ICondition *pCondition,
-            /* [in] */ BOOL fUseEnglish,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszQueryString) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE ParsePropertyValue( 
-            /* [in] */ __RPC__in LPCWSTR pszPropertyName,
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [retval][out] */ __RPC__deref_out_opt IQuerySolution **ppSolution) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RestatePropertyValueToString( 
-            /* [in] */ __RPC__in_opt ICondition *pCondition,
-            /* [in] */ BOOL fUseEnglish,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszPropertyName,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszQueryString) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IQueryParserVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IQueryParser * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IQueryParser * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IQueryParser * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Parse )( 
-            IQueryParser * This,
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [in] */ __RPC__in_opt IEnumUnknown *pCustomProperties,
-            /* [retval][out] */ __RPC__deref_out_opt IQuerySolution **ppSolution);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetOption )( 
-            IQueryParser * This,
-            /* [in] */ STRUCTURED_QUERY_SINGLE_OPTION option,
-            /* [in] */ __RPC__in const PROPVARIANT *pOptionValue);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetOption )( 
-            IQueryParser * This,
-            /* [in] */ STRUCTURED_QUERY_SINGLE_OPTION option,
-            /* [retval][out] */ __RPC__out PROPVARIANT *pOptionValue);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetMultiOption )( 
-            IQueryParser * This,
-            /* [in] */ STRUCTURED_QUERY_MULTIOPTION option,
-            /* [in] */ __RPC__in LPCWSTR pszOptionKey,
-            /* [in] */ __RPC__in const PROPVARIANT *pOptionValue);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSchemaProvider )( 
-            IQueryParser * This,
-            /* [retval][out] */ __RPC__deref_out_opt ISchemaProvider **ppSchemaProvider);
-        
-        HRESULT ( STDMETHODCALLTYPE *RestateToString )( 
-            IQueryParser * This,
-            /* [in] */ __RPC__in_opt ICondition *pCondition,
-            /* [in] */ BOOL fUseEnglish,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszQueryString);
-        
-        HRESULT ( STDMETHODCALLTYPE *ParsePropertyValue )( 
-            IQueryParser * This,
-            /* [in] */ __RPC__in LPCWSTR pszPropertyName,
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [retval][out] */ __RPC__deref_out_opt IQuerySolution **ppSolution);
-        
-        HRESULT ( STDMETHODCALLTYPE *RestatePropertyValueToString )( 
-            IQueryParser * This,
-            /* [in] */ __RPC__in_opt ICondition *pCondition,
-            /* [in] */ BOOL fUseEnglish,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszPropertyName,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszQueryString);
-        
-        END_INTERFACE
-    } IQueryParserVtbl;
-
-    interface IQueryParser
-    {
-        CONST_VTBL struct IQueryParserVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IQueryParser_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IQueryParser_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IQueryParser_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IQueryParser_Parse(This,pszInputString,pCustomProperties,ppSolution)	\
-    ( (This)->lpVtbl -> Parse(This,pszInputString,pCustomProperties,ppSolution) ) 
-
-#define IQueryParser_SetOption(This,option,pOptionValue)	\
-    ( (This)->lpVtbl -> SetOption(This,option,pOptionValue) ) 
-
-#define IQueryParser_GetOption(This,option,pOptionValue)	\
-    ( (This)->lpVtbl -> GetOption(This,option,pOptionValue) ) 
-
-#define IQueryParser_SetMultiOption(This,option,pszOptionKey,pOptionValue)	\
-    ( (This)->lpVtbl -> SetMultiOption(This,option,pszOptionKey,pOptionValue) ) 
-
-#define IQueryParser_GetSchemaProvider(This,ppSchemaProvider)	\
-    ( (This)->lpVtbl -> GetSchemaProvider(This,ppSchemaProvider) ) 
-
-#define IQueryParser_RestateToString(This,pCondition,fUseEnglish,ppszQueryString)	\
-    ( (This)->lpVtbl -> RestateToString(This,pCondition,fUseEnglish,ppszQueryString) ) 
-
-#define IQueryParser_ParsePropertyValue(This,pszPropertyName,pszInputString,ppSolution)	\
-    ( (This)->lpVtbl -> ParsePropertyValue(This,pszPropertyName,pszInputString,ppSolution) ) 
-
-#define IQueryParser_RestatePropertyValueToString(This,pCondition,fUseEnglish,ppszPropertyName,ppszQueryString)	\
-    ( (This)->lpVtbl -> RestatePropertyValueToString(This,pCondition,fUseEnglish,ppszPropertyName,ppszQueryString) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IQueryParser_INTERFACE_DEFINED__ */
-
-
-#ifndef __IConditionFactory_INTERFACE_DEFINED__
-#define __IConditionFactory_INTERFACE_DEFINED__
-
-/* interface IConditionFactory */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IConditionFactory;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("A5EFE073-B16F-474f-9F3E-9F8B497A3E08")
-    IConditionFactory : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE MakeNot( 
-            /* [in] */ __RPC__in_opt ICondition *pSubCondition,
-            /* [in] */ BOOL simplify,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE MakeAndOr( 
-            /* [in] */ CONDITION_TYPE nodeType,
-            /* [in] */ __RPC__in_opt IEnumUnknown *pSubConditions,
-            /* [in] */ BOOL simplify,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE MakeLeaf( 
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszPropertyName,
-            /* [in] */ CONDITION_OPERATION op,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValueType,
-            /* [in] */ __RPC__in const PROPVARIANT *pValue,
-            /* [in] */ __RPC__in_opt IRichChunk *pPropertyNameTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pOperationTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pValueTerm,
-            /* [in] */ BOOL expand,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE Resolve( 
-            /* [in] */ 
-            __in  ICondition *pConditionTree,
-            /* [in] */ 
-            __in  STRUCTURED_QUERY_RESOLVE_OPTION sqro,
-            /* [ref][in] */ 
-            __in_opt  const SYSTEMTIME *pstReferenceTime,
-            /* [retval][out] */ 
-            __out  ICondition **ppResolvedConditionTree) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IConditionFactoryVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IConditionFactory * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IConditionFactory * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IConditionFactory * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *MakeNot )( 
-            IConditionFactory * This,
-            /* [in] */ __RPC__in_opt ICondition *pSubCondition,
-            /* [in] */ BOOL simplify,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery);
-        
-        HRESULT ( STDMETHODCALLTYPE *MakeAndOr )( 
-            IConditionFactory * This,
-            /* [in] */ CONDITION_TYPE nodeType,
-            /* [in] */ __RPC__in_opt IEnumUnknown *pSubConditions,
-            /* [in] */ BOOL simplify,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery);
-        
-        HRESULT ( STDMETHODCALLTYPE *MakeLeaf )( 
-            IConditionFactory * This,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszPropertyName,
-            /* [in] */ CONDITION_OPERATION op,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValueType,
-            /* [in] */ __RPC__in const PROPVARIANT *pValue,
-            /* [in] */ __RPC__in_opt IRichChunk *pPropertyNameTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pOperationTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pValueTerm,
-            /* [in] */ BOOL expand,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Resolve )( 
-            IConditionFactory * This,
-            /* [in] */ 
-            __in  ICondition *pConditionTree,
-            /* [in] */ 
-            __in  STRUCTURED_QUERY_RESOLVE_OPTION sqro,
-            /* [ref][in] */ 
-            __in_opt  const SYSTEMTIME *pstReferenceTime,
-            /* [retval][out] */ 
-            __out  ICondition **ppResolvedConditionTree);
-        
-        END_INTERFACE
-    } IConditionFactoryVtbl;
-
-    interface IConditionFactory
-    {
-        CONST_VTBL struct IConditionFactoryVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IConditionFactory_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IConditionFactory_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IConditionFactory_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IConditionFactory_MakeNot(This,pSubCondition,simplify,ppResultQuery)	\
-    ( (This)->lpVtbl -> MakeNot(This,pSubCondition,simplify,ppResultQuery) ) 
-
-#define IConditionFactory_MakeAndOr(This,nodeType,pSubConditions,simplify,ppResultQuery)	\
-    ( (This)->lpVtbl -> MakeAndOr(This,nodeType,pSubConditions,simplify,ppResultQuery) ) 
-
-#define IConditionFactory_MakeLeaf(This,pszPropertyName,op,pszValueType,pValue,pPropertyNameTerm,pOperationTerm,pValueTerm,expand,ppResultQuery)	\
-    ( (This)->lpVtbl -> MakeLeaf(This,pszPropertyName,op,pszValueType,pValue,pPropertyNameTerm,pOperationTerm,pValueTerm,expand,ppResultQuery) ) 
-
-#define IConditionFactory_Resolve(This,pConditionTree,sqro,pstReferenceTime,ppResolvedConditionTree)	\
-    ( (This)->lpVtbl -> Resolve(This,pConditionTree,sqro,pstReferenceTime,ppResolvedConditionTree) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IConditionFactory_INTERFACE_DEFINED__ */
-
-
-#ifndef __IQuerySolution_INTERFACE_DEFINED__
-#define __IQuerySolution_INTERFACE_DEFINED__
-
-/* interface IQuerySolution */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IQuerySolution;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("D6EBC66B-8921-4193-AFDD-A1789FB7FF57")
-    IQuerySolution : public IConditionFactory
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetQuery( 
-            /* [out] */ 
-            __out_opt  ICondition **ppQueryNode,
-            /* [out] */ 
-            __out_opt  IEntity **ppMainType) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetErrors( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **ppParseErrors) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetLexicalData( 
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszInputString,
-            /* [out] */ 
-            __out_opt  ITokenCollection **ppTokens,
-            /* [out] */ 
-            __out_opt  LCID *pLocale,
-            /* [out] */ 
-            __out_opt  IUnknown **ppWordBreaker) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IQuerySolutionVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IQuerySolution * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IQuerySolution * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IQuerySolution * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *MakeNot )( 
-            IQuerySolution * This,
-            /* [in] */ __RPC__in_opt ICondition *pSubCondition,
-            /* [in] */ BOOL simplify,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery);
-        
-        HRESULT ( STDMETHODCALLTYPE *MakeAndOr )( 
-            IQuerySolution * This,
-            /* [in] */ CONDITION_TYPE nodeType,
-            /* [in] */ __RPC__in_opt IEnumUnknown *pSubConditions,
-            /* [in] */ BOOL simplify,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery);
-        
-        HRESULT ( STDMETHODCALLTYPE *MakeLeaf )( 
-            IQuerySolution * This,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszPropertyName,
-            /* [in] */ CONDITION_OPERATION op,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValueType,
-            /* [in] */ __RPC__in const PROPVARIANT *pValue,
-            /* [in] */ __RPC__in_opt IRichChunk *pPropertyNameTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pOperationTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pValueTerm,
-            /* [in] */ BOOL expand,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppResultQuery);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Resolve )( 
-            IQuerySolution * This,
-            /* [in] */ 
-            __in  ICondition *pConditionTree,
-            /* [in] */ 
-            __in  STRUCTURED_QUERY_RESOLVE_OPTION sqro,
-            /* [ref][in] */ 
-            __in_opt  const SYSTEMTIME *pstReferenceTime,
-            /* [retval][out] */ 
-            __out  ICondition **ppResolvedConditionTree);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetQuery )( 
-            IQuerySolution * This,
-            /* [out] */ 
-            __out_opt  ICondition **ppQueryNode,
-            /* [out] */ 
-            __out_opt  IEntity **ppMainType);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetErrors )( 
-            IQuerySolution * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **ppParseErrors);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetLexicalData )( 
-            IQuerySolution * This,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszInputString,
-            /* [out] */ 
-            __out_opt  ITokenCollection **ppTokens,
-            /* [out] */ 
-            __out_opt  LCID *pLocale,
-            /* [out] */ 
-            __out_opt  IUnknown **ppWordBreaker);
-        
-        END_INTERFACE
-    } IQuerySolutionVtbl;
-
-    interface IQuerySolution
-    {
-        CONST_VTBL struct IQuerySolutionVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IQuerySolution_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IQuerySolution_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IQuerySolution_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IQuerySolution_MakeNot(This,pSubCondition,simplify,ppResultQuery)	\
-    ( (This)->lpVtbl -> MakeNot(This,pSubCondition,simplify,ppResultQuery) ) 
-
-#define IQuerySolution_MakeAndOr(This,nodeType,pSubConditions,simplify,ppResultQuery)	\
-    ( (This)->lpVtbl -> MakeAndOr(This,nodeType,pSubConditions,simplify,ppResultQuery) ) 
-
-#define IQuerySolution_MakeLeaf(This,pszPropertyName,op,pszValueType,pValue,pPropertyNameTerm,pOperationTerm,pValueTerm,expand,ppResultQuery)	\
-    ( (This)->lpVtbl -> MakeLeaf(This,pszPropertyName,op,pszValueType,pValue,pPropertyNameTerm,pOperationTerm,pValueTerm,expand,ppResultQuery) ) 
-
-#define IQuerySolution_Resolve(This,pConditionTree,sqro,pstReferenceTime,ppResolvedConditionTree)	\
-    ( (This)->lpVtbl -> Resolve(This,pConditionTree,sqro,pstReferenceTime,ppResolvedConditionTree) ) 
-
-
-#define IQuerySolution_GetQuery(This,ppQueryNode,ppMainType)	\
-    ( (This)->lpVtbl -> GetQuery(This,ppQueryNode,ppMainType) ) 
-
-#define IQuerySolution_GetErrors(This,riid,ppParseErrors)	\
-    ( (This)->lpVtbl -> GetErrors(This,riid,ppParseErrors) ) 
-
-#define IQuerySolution_GetLexicalData(This,ppszInputString,ppTokens,pLocale,ppWordBreaker)	\
-    ( (This)->lpVtbl -> GetLexicalData(This,ppszInputString,ppTokens,pLocale,ppWordBreaker) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IQuerySolution_INTERFACE_DEFINED__ */
-
-
-#ifndef __ICondition_INTERFACE_DEFINED__
-#define __ICondition_INTERFACE_DEFINED__
-
-/* interface ICondition */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_ICondition;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("0FC988D4-C935-4b97-A973-46282EA175C8")
-    ICondition : public IPersistStream
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetConditionType( 
-            /* [retval][out] */ __RPC__out CONDITION_TYPE *pNodeType) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetSubConditions( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **ppv) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetComparisonInfo( 
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszPropertyName,
-            /* [out] */ 
-            __out_opt  CONDITION_OPERATION *pOperation,
-            /* [out] */ 
-            __out_opt  PROPVARIANT *pValue) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetValueType( 
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszValueTypeName) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetValueNormalization( 
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszNormalization) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetInputTerms( 
-            /* [out] */ 
-            __out_opt  IRichChunk **ppPropertyTerm,
-            /* [out] */ 
-            __out_opt  IRichChunk **ppOperationTerm,
-            /* [out] */ 
-            __out_opt  IRichChunk **ppValueTerm) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Clone( 
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppc) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IConditionVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ICondition * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ICondition * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ICondition * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetClassID )( 
-            ICondition * This,
-            /* [out] */ __RPC__out CLSID *pClassID);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsDirty )( 
-            ICondition * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Load )( 
-            ICondition * This,
-            /* [unique][in] */ __RPC__in_opt IStream *pStm);
-        
-        HRESULT ( STDMETHODCALLTYPE *Save )( 
-            ICondition * This,
-            /* [unique][in] */ __RPC__in_opt IStream *pStm,
-            /* [in] */ BOOL fClearDirty);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSizeMax )( 
-            ICondition * This,
-            /* [out] */ __RPC__out ULARGE_INTEGER *pcbSize);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetConditionType )( 
-            ICondition * This,
-            /* [retval][out] */ __RPC__out CONDITION_TYPE *pNodeType);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetSubConditions )( 
-            ICondition * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **ppv);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetComparisonInfo )( 
-            ICondition * This,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszPropertyName,
-            /* [out] */ 
-            __out_opt  CONDITION_OPERATION *pOperation,
-            /* [out] */ 
-            __out_opt  PROPVARIANT *pValue);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValueType )( 
-            ICondition * This,
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszValueTypeName);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValueNormalization )( 
-            ICondition * This,
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszNormalization);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetInputTerms )( 
-            ICondition * This,
-            /* [out] */ 
-            __out_opt  IRichChunk **ppPropertyTerm,
-            /* [out] */ 
-            __out_opt  IRichChunk **ppOperationTerm,
-            /* [out] */ 
-            __out_opt  IRichChunk **ppValueTerm);
-        
-        HRESULT ( STDMETHODCALLTYPE *Clone )( 
-            ICondition * This,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppc);
-        
-        END_INTERFACE
-    } IConditionVtbl;
-
-    interface ICondition
-    {
-        CONST_VTBL struct IConditionVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ICondition_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ICondition_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ICondition_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define ICondition_GetClassID(This,pClassID)	\
-    ( (This)->lpVtbl -> GetClassID(This,pClassID) ) 
-
-
-#define ICondition_IsDirty(This)	\
-    ( (This)->lpVtbl -> IsDirty(This) ) 
-
-#define ICondition_Load(This,pStm)	\
-    ( (This)->lpVtbl -> Load(This,pStm) ) 
-
-#define ICondition_Save(This,pStm,fClearDirty)	\
-    ( (This)->lpVtbl -> Save(This,pStm,fClearDirty) ) 
-
-#define ICondition_GetSizeMax(This,pcbSize)	\
-    ( (This)->lpVtbl -> GetSizeMax(This,pcbSize) ) 
-
-
-#define ICondition_GetConditionType(This,pNodeType)	\
-    ( (This)->lpVtbl -> GetConditionType(This,pNodeType) ) 
-
-#define ICondition_GetSubConditions(This,riid,ppv)	\
-    ( (This)->lpVtbl -> GetSubConditions(This,riid,ppv) ) 
-
-#define ICondition_GetComparisonInfo(This,ppszPropertyName,pOperation,pValue)	\
-    ( (This)->lpVtbl -> GetComparisonInfo(This,ppszPropertyName,pOperation,pValue) ) 
-
-#define ICondition_GetValueType(This,ppszValueTypeName)	\
-    ( (This)->lpVtbl -> GetValueType(This,ppszValueTypeName) ) 
-
-#define ICondition_GetValueNormalization(This,ppszNormalization)	\
-    ( (This)->lpVtbl -> GetValueNormalization(This,ppszNormalization) ) 
-
-#define ICondition_GetInputTerms(This,ppPropertyTerm,ppOperationTerm,ppValueTerm)	\
-    ( (This)->lpVtbl -> GetInputTerms(This,ppPropertyTerm,ppOperationTerm,ppValueTerm) ) 
-
-#define ICondition_Clone(This,ppc)	\
-    ( (This)->lpVtbl -> Clone(This,ppc) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ICondition_INTERFACE_DEFINED__ */
-
-
-#ifndef __IConditionGenerator_INTERFACE_DEFINED__
-#define __IConditionGenerator_INTERFACE_DEFINED__
-
-/* interface IConditionGenerator */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IConditionGenerator;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("92D2CC58-4386-45a3-B98C-7E0CE64A4117")
-    IConditionGenerator : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Initialize( 
-            /* [in] */ __RPC__in_opt ISchemaProvider *pSchemaProvider) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RecognizeNamedEntities( 
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [in] */ LCID lcid,
-            /* [in] */ __RPC__in_opt ITokenCollection *pTokenCollection,
-            /* [out][in] */ __RPC__inout_opt INamedEntityCollector *pNamedEntities) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GenerateForLeaf( 
-            /* [in] */ __RPC__in_opt IConditionFactory *pConditionFactory,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszPropertyName,
-            /* [in] */ CONDITION_OPERATION op,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValueType,
-            /* [in] */ __RPC__in LPCWSTR pszValue,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValue2,
-            /* [in] */ __RPC__in_opt IRichChunk *pPropertyNameTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pOperationTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pValueTerm,
-            /* [in] */ BOOL automaticWildcard,
-            /* [out] */ __RPC__out BOOL *pNoStringQuery,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppQueryExpression) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE DefaultPhrase( 
-            /* [unique][in] */ LPCWSTR pszValueType,
-            /* [in] */ const PROPVARIANT *ppropvar,
-            /* [in] */ BOOL fUseEnglish,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IConditionGeneratorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IConditionGenerator * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IConditionGenerator * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IConditionGenerator * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Initialize )( 
-            IConditionGenerator * This,
-            /* [in] */ __RPC__in_opt ISchemaProvider *pSchemaProvider);
-        
-        HRESULT ( STDMETHODCALLTYPE *RecognizeNamedEntities )( 
-            IConditionGenerator * This,
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [in] */ LCID lcid,
-            /* [in] */ __RPC__in_opt ITokenCollection *pTokenCollection,
-            /* [out][in] */ __RPC__inout_opt INamedEntityCollector *pNamedEntities);
-        
-        HRESULT ( STDMETHODCALLTYPE *GenerateForLeaf )( 
-            IConditionGenerator * This,
-            /* [in] */ __RPC__in_opt IConditionFactory *pConditionFactory,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszPropertyName,
-            /* [in] */ CONDITION_OPERATION op,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValueType,
-            /* [in] */ __RPC__in LPCWSTR pszValue,
-            /* [unique][in] */ __RPC__in_opt LPCWSTR pszValue2,
-            /* [in] */ __RPC__in_opt IRichChunk *pPropertyNameTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pOperationTerm,
-            /* [in] */ __RPC__in_opt IRichChunk *pValueTerm,
-            /* [in] */ BOOL automaticWildcard,
-            /* [out] */ __RPC__out BOOL *pNoStringQuery,
-            /* [retval][out] */ __RPC__deref_out_opt ICondition **ppQueryExpression);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *DefaultPhrase )( 
-            IConditionGenerator * This,
-            /* [unique][in] */ LPCWSTR pszValueType,
-            /* [in] */ const PROPVARIANT *ppropvar,
-            /* [in] */ BOOL fUseEnglish,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase);
-        
-        END_INTERFACE
-    } IConditionGeneratorVtbl;
-
-    interface IConditionGenerator
-    {
-        CONST_VTBL struct IConditionGeneratorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IConditionGenerator_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IConditionGenerator_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IConditionGenerator_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IConditionGenerator_Initialize(This,pSchemaProvider)	\
-    ( (This)->lpVtbl -> Initialize(This,pSchemaProvider) ) 
-
-#define IConditionGenerator_RecognizeNamedEntities(This,pszInputString,lcid,pTokenCollection,pNamedEntities)	\
-    ( (This)->lpVtbl -> RecognizeNamedEntities(This,pszInputString,lcid,pTokenCollection,pNamedEntities) ) 
-
-#define IConditionGenerator_GenerateForLeaf(This,pConditionFactory,pszPropertyName,op,pszValueType,pszValue,pszValue2,pPropertyNameTerm,pOperationTerm,pValueTerm,automaticWildcard,pNoStringQuery,ppQueryExpression)	\
-    ( (This)->lpVtbl -> GenerateForLeaf(This,pConditionFactory,pszPropertyName,op,pszValueType,pszValue,pszValue2,pPropertyNameTerm,pOperationTerm,pValueTerm,automaticWildcard,pNoStringQuery,ppQueryExpression) ) 
-
-#define IConditionGenerator_DefaultPhrase(This,pszValueType,ppropvar,fUseEnglish,ppszPhrase)	\
-    ( (This)->lpVtbl -> DefaultPhrase(This,pszValueType,ppropvar,fUseEnglish,ppszPhrase) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IConditionGenerator_INTERFACE_DEFINED__ */
-
-
-#ifndef __IRichChunk_INTERFACE_DEFINED__
-#define __IRichChunk_INTERFACE_DEFINED__
-
-/* interface IRichChunk */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IRichChunk;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("4FDEF69C-DBC9-454e-9910-B34F3C64B510")
-    IRichChunk : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetData( 
-            /* [out] */ 
-            __out_opt  ULONG *pFirstPos,
-            /* [out] */ 
-            __out_opt  ULONG *pLength,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppsz,
-            /* [out] */ 
-            __out_opt  PROPVARIANT *pValue) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IRichChunkVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IRichChunk * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IRichChunk * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IRichChunk * This);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetData )( 
-            IRichChunk * This,
-            /* [out] */ 
-            __out_opt  ULONG *pFirstPos,
-            /* [out] */ 
-            __out_opt  ULONG *pLength,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppsz,
-            /* [out] */ 
-            __out_opt  PROPVARIANT *pValue);
-        
-        END_INTERFACE
-    } IRichChunkVtbl;
-
-    interface IRichChunk
-    {
-        CONST_VTBL struct IRichChunkVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IRichChunk_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IRichChunk_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IRichChunk_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IRichChunk_GetData(This,pFirstPos,pLength,ppsz,pValue)	\
-    ( (This)->lpVtbl -> GetData(This,pFirstPos,pLength,ppsz,pValue) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IRichChunk_INTERFACE_DEFINED__ */
-
-
-#ifndef __IInterval_INTERFACE_DEFINED__
-#define __IInterval_INTERFACE_DEFINED__
-
-/* interface IInterval */
-/* [unique][uuid][object] */ 
-
-
-EXTERN_C const IID IID_IInterval;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("6BF0A714-3C18-430b-8B5D-83B1C234D3DB")
-    IInterval : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetLimits( 
-            /* [out] */ __RPC__out INTERVAL_LIMIT_KIND *pilkLower,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarLower,
-            /* [out] */ __RPC__out INTERVAL_LIMIT_KIND *pilkUpper,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarUpper) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IIntervalVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IInterval * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IInterval * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IInterval * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetLimits )( 
-            IInterval * This,
-            /* [out] */ __RPC__out INTERVAL_LIMIT_KIND *pilkLower,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarLower,
-            /* [out] */ __RPC__out INTERVAL_LIMIT_KIND *pilkUpper,
-            /* [out] */ __RPC__out PROPVARIANT *ppropvarUpper);
-        
-        END_INTERFACE
-    } IIntervalVtbl;
-
-    interface IInterval
-    {
-        CONST_VTBL struct IIntervalVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IInterval_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IInterval_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IInterval_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IInterval_GetLimits(This,pilkLower,ppropvarLower,pilkUpper,ppropvarUpper)	\
-    ( (This)->lpVtbl -> GetLimits(This,pilkLower,ppropvarLower,pilkUpper,ppropvarUpper) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IInterval_INTERFACE_DEFINED__ */
-
-
-#ifndef __IMetaData_INTERFACE_DEFINED__
-#define __IMetaData_INTERFACE_DEFINED__
-
-/* interface IMetaData */
-/* [unique][uuid][object][helpstring] */ 
-
-
-EXTERN_C const IID IID_IMetaData;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("780102B0-C43B-4876-BC7B-5E9BA5C88794")
-    IMetaData : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetData( 
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszKey,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszValue) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IMetaDataVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IMetaData * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IMetaData * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IMetaData * This);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetData )( 
-            IMetaData * This,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszKey,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppszValue);
-        
-        END_INTERFACE
-    } IMetaDataVtbl;
-
-    interface IMetaData
-    {
-        CONST_VTBL struct IMetaDataVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IMetaData_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IMetaData_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IMetaData_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IMetaData_GetData(This,ppszKey,ppszValue)	\
-    ( (This)->lpVtbl -> GetData(This,ppszKey,ppszValue) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IMetaData_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_structuredquery_0000_0008 */
-/* [local] */ 
-
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_structuredquery_0000_0008_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_structuredquery_0000_0008_v0_0_s_ifspec;
-
-#ifndef __IEntity_INTERFACE_DEFINED__
-#define __IEntity_INTERFACE_DEFINED__
-
-/* interface IEntity */
-/* [unique][object][uuid][helpstring] */ 
-
-
-EXTERN_C const IID IID_IEntity;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("24264891-E80B-4fd3-B7CE-4FF2FAE8931F")
-    IEntity : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE Name( 
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszName) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Base( 
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pBaseEntity) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Relationships( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pRelationships) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetRelationship( 
-            /* [in] */ __RPC__in LPCWSTR pszRelationName,
-            /* [retval][out] */ __RPC__deref_out_opt IRelationship **pRelationship) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE MetaData( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pMetaData) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE NamedEntities( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pNamedEntities) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetNamedEntity( 
-            /* [in] */ __RPC__in LPCWSTR pszValue,
-            /* [retval][out] */ __RPC__deref_out_opt INamedEntity **ppNamedEntity) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE DefaultPhrase( 
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IEntityVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IEntity * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IEntity * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IEntity * This);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Name )( 
-            IEntity * This,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *Base )( 
-            IEntity * This,
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pBaseEntity);
-        
-        HRESULT ( STDMETHODCALLTYPE *Relationships )( 
-            IEntity * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pRelationships);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetRelationship )( 
-            IEntity * This,
-            /* [in] */ __RPC__in LPCWSTR pszRelationName,
-            /* [retval][out] */ __RPC__deref_out_opt IRelationship **pRelationship);
-        
-        HRESULT ( STDMETHODCALLTYPE *MetaData )( 
-            IEntity * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pMetaData);
-        
-        HRESULT ( STDMETHODCALLTYPE *NamedEntities )( 
-            IEntity * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pNamedEntities);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetNamedEntity )( 
-            IEntity * This,
-            /* [in] */ __RPC__in LPCWSTR pszValue,
-            /* [retval][out] */ __RPC__deref_out_opt INamedEntity **ppNamedEntity);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *DefaultPhrase )( 
-            IEntity * This,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase);
-        
-        END_INTERFACE
-    } IEntityVtbl;
-
-    interface IEntity
-    {
-        CONST_VTBL struct IEntityVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IEntity_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IEntity_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IEntity_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IEntity_Name(This,ppszName)	\
-    ( (This)->lpVtbl -> Name(This,ppszName) ) 
-
-#define IEntity_Base(This,pBaseEntity)	\
-    ( (This)->lpVtbl -> Base(This,pBaseEntity) ) 
-
-#define IEntity_Relationships(This,riid,pRelationships)	\
-    ( (This)->lpVtbl -> Relationships(This,riid,pRelationships) ) 
-
-#define IEntity_GetRelationship(This,pszRelationName,pRelationship)	\
-    ( (This)->lpVtbl -> GetRelationship(This,pszRelationName,pRelationship) ) 
-
-#define IEntity_MetaData(This,riid,pMetaData)	\
-    ( (This)->lpVtbl -> MetaData(This,riid,pMetaData) ) 
-
-#define IEntity_NamedEntities(This,riid,pNamedEntities)	\
-    ( (This)->lpVtbl -> NamedEntities(This,riid,pNamedEntities) ) 
-
-#define IEntity_GetNamedEntity(This,pszValue,ppNamedEntity)	\
-    ( (This)->lpVtbl -> GetNamedEntity(This,pszValue,ppNamedEntity) ) 
-
-#define IEntity_DefaultPhrase(This,ppszPhrase)	\
-    ( (This)->lpVtbl -> DefaultPhrase(This,ppszPhrase) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IEntity_INTERFACE_DEFINED__ */
-
-
-#ifndef __IRelationship_INTERFACE_DEFINED__
-#define __IRelationship_INTERFACE_DEFINED__
-
-/* interface IRelationship */
-/* [unique][object][uuid][helpstring] */ 
-
-
-EXTERN_C const IID IID_IRelationship;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("2769280B-5108-498c-9C7F-A51239B63147")
-    IRelationship : public IUnknown
-    {
-    public:
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE Name( 
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszName) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE IsReal( 
-            /* [retval][out] */ __RPC__out BOOL *pIsReal) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Destination( 
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pDestinationEntity) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE MetaData( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pMetaData) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE DefaultPhrase( 
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IRelationshipVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IRelationship * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IRelationship * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IRelationship * This);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Name )( 
-            IRelationship * This,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszName);
-        
-        HRESULT ( STDMETHODCALLTYPE *IsReal )( 
-            IRelationship * This,
-            /* [retval][out] */ __RPC__out BOOL *pIsReal);
-        
-        HRESULT ( STDMETHODCALLTYPE *Destination )( 
-            IRelationship * This,
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pDestinationEntity);
-        
-        HRESULT ( STDMETHODCALLTYPE *MetaData )( 
-            IRelationship * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pMetaData);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *DefaultPhrase )( 
-            IRelationship * This,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase);
-        
-        END_INTERFACE
-    } IRelationshipVtbl;
-
-    interface IRelationship
-    {
-        CONST_VTBL struct IRelationshipVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IRelationship_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IRelationship_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IRelationship_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IRelationship_Name(This,ppszName)	\
-    ( (This)->lpVtbl -> Name(This,ppszName) ) 
-
-#define IRelationship_IsReal(This,pIsReal)	\
-    ( (This)->lpVtbl -> IsReal(This,pIsReal) ) 
-
-#define IRelationship_Destination(This,pDestinationEntity)	\
-    ( (This)->lpVtbl -> Destination(This,pDestinationEntity) ) 
-
-#define IRelationship_MetaData(This,riid,pMetaData)	\
-    ( (This)->lpVtbl -> MetaData(This,riid,pMetaData) ) 
-
-#define IRelationship_DefaultPhrase(This,ppszPhrase)	\
-    ( (This)->lpVtbl -> DefaultPhrase(This,ppszPhrase) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IRelationship_INTERFACE_DEFINED__ */
-
-
-#ifndef __INamedEntity_INTERFACE_DEFINED__
-#define __INamedEntity_INTERFACE_DEFINED__
-
-/* interface INamedEntity */
-/* [unique][uuid][object][helpstring] */ 
-
-
-EXTERN_C const IID IID_INamedEntity;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("ABDBD0B1-7D54-49fb-AB5C-BFF4130004CD")
-    INamedEntity : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE GetValue( 
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszValue) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE DefaultPhrase( 
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct INamedEntityVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            INamedEntity * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            INamedEntity * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            INamedEntity * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetValue )( 
-            INamedEntity * This,
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszValue);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *DefaultPhrase )( 
-            INamedEntity * This,
-            /* [retval][out] */ 
-            __deref_opt_out  LPWSTR *ppszPhrase);
-        
-        END_INTERFACE
-    } INamedEntityVtbl;
-
-    interface INamedEntity
-    {
-        CONST_VTBL struct INamedEntityVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define INamedEntity_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define INamedEntity_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define INamedEntity_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define INamedEntity_GetValue(This,ppszValue)	\
-    ( (This)->lpVtbl -> GetValue(This,ppszValue) ) 
-
-#define INamedEntity_DefaultPhrase(This,ppszPhrase)	\
-    ( (This)->lpVtbl -> DefaultPhrase(This,ppszPhrase) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __INamedEntity_INTERFACE_DEFINED__ */
-
-
-#ifndef __ISchemaProvider_INTERFACE_DEFINED__
-#define __ISchemaProvider_INTERFACE_DEFINED__
-
-/* interface ISchemaProvider */
-/* [unique][object][uuid][helpstring] */ 
-
-
-EXTERN_C const IID IID_ISchemaProvider;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("8CF89BCB-394C-49b2-AE28-A59DD4ED7F68")
-    ISchemaProvider : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Entities( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pEntities) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE RootEntity( 
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pRootEntity) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE GetEntity( 
-            /* [in] */ __RPC__in LPCWSTR pszEntityName,
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pEntity) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE MetaData( 
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pMetaData) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE Localize( 
-            /* [in] */ LCID lcid,
-            /* [in] */ __RPC__in_opt ISchemaLocalizerSupport *pSchemaLocalizerSupport) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SaveBinary( 
-            /* [in] */ __RPC__in LPCWSTR pszSchemaBinaryPath) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE LookupAuthoredNamedEntity( 
-            /* [in] */ __RPC__in_opt IEntity *pEntity,
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [in] */ __RPC__in_opt ITokenCollection *pTokenCollection,
-            /* [in] */ ULONG cTokensBegin,
-            /* [out] */ __RPC__out ULONG *pcTokensLength,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszValue) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct ISchemaProviderVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ISchemaProvider * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ISchemaProvider * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ISchemaProvider * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Entities )( 
-            ISchemaProvider * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pEntities);
-        
-        HRESULT ( STDMETHODCALLTYPE *RootEntity )( 
-            ISchemaProvider * This,
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pRootEntity);
-        
-        HRESULT ( STDMETHODCALLTYPE *GetEntity )( 
-            ISchemaProvider * This,
-            /* [in] */ __RPC__in LPCWSTR pszEntityName,
-            /* [retval][out] */ __RPC__deref_out_opt IEntity **pEntity);
-        
-        HRESULT ( STDMETHODCALLTYPE *MetaData )( 
-            ISchemaProvider * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **pMetaData);
-        
-        HRESULT ( STDMETHODCALLTYPE *Localize )( 
-            ISchemaProvider * This,
-            /* [in] */ LCID lcid,
-            /* [in] */ __RPC__in_opt ISchemaLocalizerSupport *pSchemaLocalizerSupport);
-        
-        HRESULT ( STDMETHODCALLTYPE *SaveBinary )( 
-            ISchemaProvider * This,
-            /* [in] */ __RPC__in LPCWSTR pszSchemaBinaryPath);
-        
-        HRESULT ( STDMETHODCALLTYPE *LookupAuthoredNamedEntity )( 
-            ISchemaProvider * This,
-            /* [in] */ __RPC__in_opt IEntity *pEntity,
-            /* [in] */ __RPC__in LPCWSTR pszInputString,
-            /* [in] */ __RPC__in_opt ITokenCollection *pTokenCollection,
-            /* [in] */ ULONG cTokensBegin,
-            /* [out] */ __RPC__out ULONG *pcTokensLength,
-            /* [out] */ __RPC__deref_out_opt LPWSTR *ppszValue);
-        
-        END_INTERFACE
-    } ISchemaProviderVtbl;
-
-    interface ISchemaProvider
-    {
-        CONST_VTBL struct ISchemaProviderVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ISchemaProvider_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ISchemaProvider_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ISchemaProvider_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define ISchemaProvider_Entities(This,riid,pEntities)	\
-    ( (This)->lpVtbl -> Entities(This,riid,pEntities) ) 
-
-#define ISchemaProvider_RootEntity(This,pRootEntity)	\
-    ( (This)->lpVtbl -> RootEntity(This,pRootEntity) ) 
-
-#define ISchemaProvider_GetEntity(This,pszEntityName,pEntity)	\
-    ( (This)->lpVtbl -> GetEntity(This,pszEntityName,pEntity) ) 
-
-#define ISchemaProvider_MetaData(This,riid,pMetaData)	\
-    ( (This)->lpVtbl -> MetaData(This,riid,pMetaData) ) 
-
-#define ISchemaProvider_Localize(This,lcid,pSchemaLocalizerSupport)	\
-    ( (This)->lpVtbl -> Localize(This,lcid,pSchemaLocalizerSupport) ) 
-
-#define ISchemaProvider_SaveBinary(This,pszSchemaBinaryPath)	\
-    ( (This)->lpVtbl -> SaveBinary(This,pszSchemaBinaryPath) ) 
-
-#define ISchemaProvider_LookupAuthoredNamedEntity(This,pEntity,pszInputString,pTokenCollection,cTokensBegin,pcTokensLength,ppszValue)	\
-    ( (This)->lpVtbl -> LookupAuthoredNamedEntity(This,pEntity,pszInputString,pTokenCollection,cTokensBegin,pcTokensLength,ppszValue) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ISchemaProvider_INTERFACE_DEFINED__ */
-
-
-#ifndef __ITokenCollection_INTERFACE_DEFINED__
-#define __ITokenCollection_INTERFACE_DEFINED__
-
-/* interface ITokenCollection */
-/* [unique][object][uuid][helpstring] */ 
-
-
-EXTERN_C const IID IID_ITokenCollection;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("22D8B4F2-F577-4adb-A335-C2AE88416FAB")
-    ITokenCollection : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE NumberOfTokens( 
-            __RPC__in ULONG *pCount) = 0;
-        
-        virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetToken( 
-            /* [in] */ ULONG i,
-            /* [out] */ 
-            __out_opt  ULONG *pBegin,
-            /* [out] */ 
-            __out_opt  ULONG *pLength,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppsz) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct ITokenCollectionVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ITokenCollection * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ITokenCollection * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ITokenCollection * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *NumberOfTokens )( 
-            ITokenCollection * This,
-            __RPC__in ULONG *pCount);
-        
-        /* [local] */ HRESULT ( STDMETHODCALLTYPE *GetToken )( 
-            ITokenCollection * This,
-            /* [in] */ ULONG i,
-            /* [out] */ 
-            __out_opt  ULONG *pBegin,
-            /* [out] */ 
-            __out_opt  ULONG *pLength,
-            /* [out] */ 
-            __deref_opt_out  LPWSTR *ppsz);
-        
-        END_INTERFACE
-    } ITokenCollectionVtbl;
-
-    interface ITokenCollection
-    {
-        CONST_VTBL struct ITokenCollectionVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ITokenCollection_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ITokenCollection_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ITokenCollection_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define ITokenCollection_NumberOfTokens(This,pCount)	\
-    ( (This)->lpVtbl -> NumberOfTokens(This,pCount) ) 
-
-#define ITokenCollection_GetToken(This,i,pBegin,pLength,ppsz)	\
-    ( (This)->lpVtbl -> GetToken(This,i,pBegin,pLength,ppsz) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ITokenCollection_INTERFACE_DEFINED__ */
-
-
-/* interface __MIDL_itf_structuredquery_0000_0013 */
-/* [local] */ 
-
-typedef /* [public][public][v1_enum] */ 
-enum __MIDL___MIDL_itf_structuredquery_0000_0013_0001
-    {	NEC_LOW	= 0,
-	NEC_MEDIUM	= ( NEC_LOW + 1 ) ,
-	NEC_HIGH	= ( NEC_MEDIUM + 1 ) 
-    } 	NAMED_ENTITY_CERTAINTY;
-
-
-
-extern RPC_IF_HANDLE __MIDL_itf_structuredquery_0000_0013_v0_0_c_ifspec;
-extern RPC_IF_HANDLE __MIDL_itf_structuredquery_0000_0013_v0_0_s_ifspec;
-
-#ifndef __INamedEntityCollector_INTERFACE_DEFINED__
-#define __INamedEntityCollector_INTERFACE_DEFINED__
-
-/* interface INamedEntityCollector */
-/* [unique][object][uuid][helpstring] */ 
-
-
-EXTERN_C const IID IID_INamedEntityCollector;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("AF2440F6-8AFC-47d0-9A7F-396A0ACFB43D")
-    INamedEntityCollector : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Add( 
-            /* [in] */ ULONG beginSpan,
-            /* [in] */ ULONG endSpan,
-            /* [in] */ ULONG beginActual,
-            /* [in] */ ULONG endActual,
-            /* [in] */ __RPC__in_opt IEntity *pType,
-            /* [in] */ __RPC__in LPCWSTR pszValue,
-            /* [in] */ NAMED_ENTITY_CERTAINTY certainty) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct INamedEntityCollectorVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            INamedEntityCollector * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            INamedEntityCollector * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            INamedEntityCollector * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Add )( 
-            INamedEntityCollector * This,
-            /* [in] */ ULONG beginSpan,
-            /* [in] */ ULONG endSpan,
-            /* [in] */ ULONG beginActual,
-            /* [in] */ ULONG endActual,
-            /* [in] */ __RPC__in_opt IEntity *pType,
-            /* [in] */ __RPC__in LPCWSTR pszValue,
-            /* [in] */ NAMED_ENTITY_CERTAINTY certainty);
-        
-        END_INTERFACE
-    } INamedEntityCollectorVtbl;
-
-    interface INamedEntityCollector
-    {
-        CONST_VTBL struct INamedEntityCollectorVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define INamedEntityCollector_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define INamedEntityCollector_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define INamedEntityCollector_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define INamedEntityCollector_Add(This,beginSpan,endSpan,beginActual,endActual,pType,pszValue,certainty)	\
-    ( (This)->lpVtbl -> Add(This,beginSpan,endSpan,beginActual,endActual,pType,pszValue,certainty) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __INamedEntityCollector_INTERFACE_DEFINED__ */
-
-
-#ifndef __ISchemaLocalizerSupport_INTERFACE_DEFINED__
-#define __ISchemaLocalizerSupport_INTERFACE_DEFINED__
-
-/* interface ISchemaLocalizerSupport */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_ISchemaLocalizerSupport;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("CA3FDCA2-BFBE-4eed-90D7-0CAEF0A1BDA1")
-    ISchemaLocalizerSupport : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE Localize( 
-            /* [in] */ __RPC__in LPCWSTR pszGlobalString,
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszLocalString) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct ISchemaLocalizerSupportVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            ISchemaLocalizerSupport * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            ISchemaLocalizerSupport * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            ISchemaLocalizerSupport * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *Localize )( 
-            ISchemaLocalizerSupport * This,
-            /* [in] */ __RPC__in LPCWSTR pszGlobalString,
-            /* [retval][out] */ __RPC__deref_out_opt LPWSTR *ppszLocalString);
-        
-        END_INTERFACE
-    } ISchemaLocalizerSupportVtbl;
-
-    interface ISchemaLocalizerSupport
-    {
-        CONST_VTBL struct ISchemaLocalizerSupportVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define ISchemaLocalizerSupport_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define ISchemaLocalizerSupport_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define ISchemaLocalizerSupport_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define ISchemaLocalizerSupport_Localize(This,pszGlobalString,ppszLocalString)	\
-    ( (This)->lpVtbl -> Localize(This,pszGlobalString,ppszLocalString) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __ISchemaLocalizerSupport_INTERFACE_DEFINED__ */
-
-
-#ifndef __IQueryParserManager_INTERFACE_DEFINED__
-#define __IQueryParserManager_INTERFACE_DEFINED__
-
-/* interface IQueryParserManager */
-/* [unique][object][uuid] */ 
-
-
-EXTERN_C const IID IID_IQueryParserManager;
-
-#if defined(__cplusplus) && !defined(CINTERFACE)
-    
-    MIDL_INTERFACE("A879E3C4-AF77-44fb-8F37-EBD1487CF920")
-    IQueryParserManager : public IUnknown
-    {
-    public:
-        virtual HRESULT STDMETHODCALLTYPE CreateLoadedParser( 
-            /* [in] */ __RPC__in LPCWSTR pszCatalog,
-            /* [in] */ LANGID langidForKeywords,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **ppQueryParser) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE InitializeOptions( 
-            /* [in] */ BOOL fUnderstandNQS,
-            /* [in] */ BOOL fAutoWildCard,
-            /* [in] */ __RPC__in_opt IQueryParser *pQueryParser) = 0;
-        
-        virtual HRESULT STDMETHODCALLTYPE SetOption( 
-            /* [in] */ QUERY_PARSER_MANAGER_OPTION option,
-            /* [in] */ __RPC__in const PROPVARIANT *pOptionValue) = 0;
-        
-    };
-    
-#else 	/* C style interface */
-
-    typedef struct IQueryParserManagerVtbl
-    {
-        BEGIN_INTERFACE
-        
-        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( 
-            IQueryParserManager * This,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][out] */ 
-            __RPC__deref_out  void **ppvObject);
-        
-        ULONG ( STDMETHODCALLTYPE *AddRef )( 
-            IQueryParserManager * This);
-        
-        ULONG ( STDMETHODCALLTYPE *Release )( 
-            IQueryParserManager * This);
-        
-        HRESULT ( STDMETHODCALLTYPE *CreateLoadedParser )( 
-            IQueryParserManager * This,
-            /* [in] */ __RPC__in LPCWSTR pszCatalog,
-            /* [in] */ LANGID langidForKeywords,
-            /* [in] */ __RPC__in REFIID riid,
-            /* [iid_is][retval][out] */ __RPC__deref_out_opt void **ppQueryParser);
-        
-        HRESULT ( STDMETHODCALLTYPE *InitializeOptions )( 
-            IQueryParserManager * This,
-            /* [in] */ BOOL fUnderstandNQS,
-            /* [in] */ BOOL fAutoWildCard,
-            /* [in] */ __RPC__in_opt IQueryParser *pQueryParser);
-        
-        HRESULT ( STDMETHODCALLTYPE *SetOption )( 
-            IQueryParserManager * This,
-            /* [in] */ QUERY_PARSER_MANAGER_OPTION option,
-            /* [in] */ __RPC__in const PROPVARIANT *pOptionValue);
-        
-        END_INTERFACE
-    } IQueryParserManagerVtbl;
-
-    interface IQueryParserManager
-    {
-        CONST_VTBL struct IQueryParserManagerVtbl *lpVtbl;
-    };
-
-    
-
-#ifdef COBJMACROS
-
-
-#define IQueryParserManager_QueryInterface(This,riid,ppvObject)	\
-    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) 
-
-#define IQueryParserManager_AddRef(This)	\
-    ( (This)->lpVtbl -> AddRef(This) ) 
-
-#define IQueryParserManager_Release(This)	\
-    ( (This)->lpVtbl -> Release(This) ) 
-
-
-#define IQueryParserManager_CreateLoadedParser(This,pszCatalog,langidForKeywords,riid,ppQueryParser)	\
-    ( (This)->lpVtbl -> CreateLoadedParser(This,pszCatalog,langidForKeywords,riid,ppQueryParser) ) 
-
-#define IQueryParserManager_InitializeOptions(This,fUnderstandNQS,fAutoWildCard,pQueryParser)	\
-    ( (This)->lpVtbl -> InitializeOptions(This,fUnderstandNQS,fAutoWildCard,pQueryParser) ) 
-
-#define IQueryParserManager_SetOption(This,option,pOptionValue)	\
-    ( (This)->lpVtbl -> SetOption(This,option,pOptionValue) ) 
-
-#endif /* COBJMACROS */
-
-
-#endif 	/* C style interface */
-
-
-
-
-#endif 	/* __IQueryParserManager_INTERFACE_DEFINED__ */
-
-
-
-#ifndef __StructuredQuery1_LIBRARY_DEFINED__
-#define __StructuredQuery1_LIBRARY_DEFINED__
-
-/* library StructuredQuery1 */
-/* [version][uuid] */ 
-
-
-EXTERN_C const IID LIBID_StructuredQuery1;
-
-EXTERN_C const CLSID CLSID_QueryParser;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("B72F8FD8-0FAB-4dd9-BDBF-245A6CE1485B")
-QueryParser;
-#endif
-
-EXTERN_C const CLSID CLSID_NegationCondition;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("8DE9C74C-605A-4acd-BEE3-2B222AA2D23D")
-NegationCondition;
-#endif
-
-EXTERN_C const CLSID CLSID_CompoundCondition;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("116F8D13-101E-4fa5-84D4-FF8279381935")
-CompoundCondition;
-#endif
-
-EXTERN_C const CLSID CLSID_LeafCondition;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("52F15C89-5A17-48e1-BBCD-46A3F89C7CC2")
-LeafCondition;
-#endif
-
-EXTERN_C const CLSID CLSID_ConditionFactory;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("E03E85B0-7BE3-4000-BA98-6C13DE9FA486")
-ConditionFactory;
-#endif
-
-EXTERN_C const CLSID CLSID_Interval;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("D957171F-4BF9-4de2-BCD5-C70A7CA55836")
-Interval;
-#endif
-
-EXTERN_C const CLSID CLSID_QueryParserManager;
-
-#ifdef __cplusplus
-
-class DECLSPEC_UUID("5088B39A-29B4-4d9d-8245-4EE289222F66")
-QueryParserManager;
-#endif
-#endif /* __StructuredQuery1_LIBRARY_DEFINED__ */
-
-/* Additional Prototypes for ALL interfaces */
-
-unsigned long             __RPC_USER  BSTR_UserSize(     unsigned long *, unsigned long            , BSTR * ); 
-unsigned char * __RPC_USER  BSTR_UserMarshal(  unsigned long *, unsigned char *, BSTR * ); 
-unsigned char * __RPC_USER  BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); 
-void                      __RPC_USER  BSTR_UserFree(     unsigned long *, BSTR * ); 
-
-unsigned long             __RPC_USER  LPSAFEARRAY_UserSize(     unsigned long *, unsigned long            , LPSAFEARRAY * ); 
-unsigned char * __RPC_USER  LPSAFEARRAY_UserMarshal(  unsigned long *, unsigned char *, LPSAFEARRAY * ); 
-unsigned char * __RPC_USER  LPSAFEARRAY_UserUnmarshal(unsigned long *, unsigned char *, LPSAFEARRAY * ); 
-void                      __RPC_USER  LPSAFEARRAY_UserFree(     unsigned long *, LPSAFEARRAY * ); 
-
-/* end of Additional Prototypes */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
-
-
diff --git a/portaudio/src/hostapi/wasapi/pa_win_wasapi.c b/portaudio/src/hostapi/wasapi/pa_win_wasapi.c
deleted file mode 100644
index aa03748a5..000000000
--- a/portaudio/src/hostapi/wasapi/pa_win_wasapi.c
+++ /dev/null
@@ -1,4457 +0,0 @@
-/*
- * Portable Audio I/O Library WASAPI implementation
- * Copyright (c) 2006-2010 David Viens, Dmitry Kostjuchenko
- *
- * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however,
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also
- * requested that these non-binding requests be included along with the
- * license above.
- */
-
-/** @file
- @ingroup hostapi_src
- @brief WASAPI implementation of support for a host API.
- @note pa_wasapi currently requires minimum VC 2005, and the latest Vista SDK
-*/
-
-#define WIN32_LEAN_AND_MEAN // exclude rare headers
-#include <windows.h>
-#include <stdio.h>
-#include <process.h>
-#include <mmsystem.h>
-#include <mmreg.h>  // must be before other Wasapi headers
-#if defined(_MSC_VER) && (_MSC_VER >= 1400)
-	#include <Avrt.h>
-	#define COBJMACROS
-	#include <Audioclient.h>
-	#include <endpointvolume.h>
-	#define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
-	#include <mmdeviceapi.h>
-	#include <functiondiscoverykeys.h>
-    #include <devicetopology.h>	// Used to get IKsJackDescription interface
-	#undef INITGUID
-#endif
-#ifndef __MWERKS__
-#include <malloc.h>
-#include <memory.h>
-#endif /* __MWERKS__ */
-
-#include "pa_util.h"
-#include "pa_allocation.h"
-#include "pa_hostapi.h"
-#include "pa_stream.h"
-#include "pa_cpuload.h"
-#include "pa_process.h"
-#include "pa_debugprint.h"
-#include "pa_win_wasapi.h"
-
-#ifndef NTDDI_VERSION
- 
-    #undef WINVER
-    #undef _WIN32_WINNT
-    #define WINVER       0x0600 // VISTA
-	#define _WIN32_WINNT WINVER
-
-	#ifndef _AVRT_ //<< fix MinGW dummy compile by defining missing type: AVRT_PRIORITY
-        typedef enum _AVRT_PRIORITY
-        {
-            AVRT_PRIORITY_LOW = -1,
-            AVRT_PRIORITY_NORMAL,
-            AVRT_PRIORITY_HIGH,
-            AVRT_PRIORITY_CRITICAL
-        } AVRT_PRIORITY, *PAVRT_PRIORITY;
-	#endif
-
-	#include <basetyps.h> // << for IID/CLSID
-    #include <rpcsal.h>
-    #include <sal.h>
-
-	#ifndef __LPCGUID_DEFINED__
-		#define __LPCGUID_DEFINED__
-		typedef const GUID *LPCGUID;
-	#endif
-
-    #ifndef PROPERTYKEY_DEFINED
-        #define PROPERTYKEY_DEFINED
-        typedef struct _tagpropertykey
-        {
-            GUID fmtid;
-            DWORD pid;
-        } 	PROPERTYKEY;
-    #endif
-
-    #ifdef __midl_proxy
-        #define __MIDL_CONST
-    #else
-        #define __MIDL_CONST const
-    #endif
-
-    #ifdef WIN64
-        #include <wtypes.h>
-        typedef LONG NTSTATUS;
-        #define FASTCALL
-        #include <oleidl.h>
-        #include <objidl.h>
-     #else
-        typedef struct _BYTE_BLOB
-        {
-            unsigned long clSize;
-            unsigned char abData[ 1 ];
-        } 	BYTE_BLOB;
-        typedef /* [unique] */  __RPC_unique_pointer BYTE_BLOB *UP_BYTE_BLOB;
-        typedef LONGLONG REFERENCE_TIME;
-        #define NONAMELESSUNION
-    #endif
-    
-    #ifndef WAVE_FORMAT_IEEE_FLOAT
-        #define WAVE_FORMAT_IEEE_FLOAT 0x0003 // 32-bit floating-point
-    #endif    
-    
-    #ifndef __MINGW_EXTENSION
-        #if defined(__GNUC__) || defined(__GNUG__)
-            #define __MINGW_EXTENSION __extension__
-        #else
-            #define __MINGW_EXTENSION
-        #endif
-    #endif 
-
-    #include <sdkddkver.h>
-    #include <propkeydef.h>
-    #define COBJMACROS
-    #define INITGUID // Avoid additional linkage of static libs, excessive code will be optimized out by the compiler
-    #include <audioclient.h>
-    #include <mmdeviceapi.h>
-    #include <endpointvolume.h>
-    #include <functiondiscoverykeys.h>
-	#include <devicetopology.h>	// Used to get IKsJackDescription interface
-    #undef INITGUID
-
-#endif // NTDDI_VERSION
-
-#ifndef GUID_SECT
-    #define GUID_SECT
-#endif
-
-#define __DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#define __DEFINE_IID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const IID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#define __DEFINE_CLSID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) static const CLSID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-#define PA_DEFINE_CLSID(className, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
-    __DEFINE_CLSID(pa_CLSID_##className, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
-#define PA_DEFINE_IID(interfaceName, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
-    __DEFINE_IID(pa_IID_##interfaceName, 0x##l, 0x##w1, 0x##w2, 0x##b1, 0x##b2, 0x##b3, 0x##b4, 0x##b5, 0x##b6, 0x##b7, 0x##b8)
-
-// "1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"
-PA_DEFINE_IID(IAudioClient,         1cb9ad4c, dbfa, 4c32, b1, 78, c2, f5, 68, a7, 03, b2);
-// "1BE09788-6894-4089-8586-9A2A6C265AC5"
-PA_DEFINE_IID(IMMEndpoint,          1be09788, 6894, 4089, 85, 86, 9a, 2a, 6c, 26, 5a, c5);
-// "A95664D2-9614-4F35-A746-DE8DB63617E6"
-PA_DEFINE_IID(IMMDeviceEnumerator,  a95664d2, 9614, 4f35, a7, 46, de, 8d, b6, 36, 17, e6);
-// "BCDE0395-E52F-467C-8E3D-C4579291692E"
-PA_DEFINE_CLSID(IMMDeviceEnumerator,bcde0395, e52f, 467c, 8e, 3d, c4, 57, 92, 91, 69, 2e);
-// "F294ACFC-3146-4483-A7BF-ADDCA7C260E2"
-PA_DEFINE_IID(IAudioRenderClient,   f294acfc, 3146, 4483, a7, bf, ad, dc, a7, c2, 60, e2);
-// "C8ADBD64-E71E-48a0-A4DE-185C395CD317"
-PA_DEFINE_IID(IAudioCaptureClient,  c8adbd64, e71e, 48a0, a4, de, 18, 5c, 39, 5c, d3, 17);
-// *2A07407E-6497-4A18-9787-32F79BD0D98F*  Or this??
-PA_DEFINE_IID(IDeviceTopology,      2A07407E, 6497, 4A18, 97, 87, 32, f7, 9b, d0, d9, 8f);
-// *AE2DE0E4-5BCA-4F2D-AA46-5D13F8FDB3A9*
-PA_DEFINE_IID(IPart,                AE2DE0E4, 5BCA, 4F2D, aa, 46, 5d, 13, f8, fd, b3, a9);
-// *4509F757-2D46-4637-8E62-CE7DB944F57B*
-PA_DEFINE_IID(IKsJackDescription,   4509F757, 2D46, 4637, 8e, 62, ce, 7d, b9, 44, f5, 7b);
-// Media formats:
-__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_PCM,        0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
-__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_ADPCM,      0x00000002, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
-__DEFINE_GUID(pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 );
-
-/* use CreateThread for CYGWIN/Windows Mobile, _beginthreadex for all others */
-#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
-	#define CREATE_THREAD(PROC) (HANDLE)_beginthreadex( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
-	#define PA_THREAD_FUNC static unsigned WINAPI
-	#define PA_THREAD_ID unsigned
-#else
-	#define CREATE_THREAD(PROC) CreateThread( NULL, 0, (PROC), stream, 0, &stream->dwThreadId )
-	#define PA_THREAD_FUNC static DWORD WINAPI
-	#define PA_THREAD_ID DWORD
-#endif
-
-// Thread function forward decl.
-PA_THREAD_FUNC ProcThreadEvent(void *param);
-PA_THREAD_FUNC ProcThreadPoll(void *param);
-
-// Availabe from Windows 7
-#ifndef AUDCLNT_E_BUFFER_ERROR
-	#define AUDCLNT_E_BUFFER_ERROR AUDCLNT_ERR(0x018)
-#endif
-#ifndef AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
-	#define AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED AUDCLNT_ERR(0x019)
-#endif
-#ifndef AUDCLNT_E_INVALID_DEVICE_PERIOD
-	#define AUDCLNT_E_INVALID_DEVICE_PERIOD AUDCLNT_ERR(0x020)
-#endif
-
-#define MAX_STR_LEN 512
-
-enum { S_INPUT = 0, S_OUTPUT = 1, S_COUNT = 2, S_FULLDUPLEX = 0 };
-
-#define STATIC_ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
-
-#define PRINT(x) PA_DEBUG(x);
-
-#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \
-    PaUtil_SetLastHostErrorInfo( paWASAPI, errorCode, errorText )
-
-#define PA_WASAPI__IS_FULLDUPLEX(STREAM) ((STREAM)->in.client && (STREAM)->out.client)
-
-#ifndef IF_FAILED_JUMP
-#define IF_FAILED_JUMP(hr, label) if(FAILED(hr)) goto label;
-#endif
-
-#define SAFE_CLOSE(h) if ((h) != NULL) { CloseHandle((h)); (h) = NULL; }
-#define SAFE_RELEASE(punk) if ((punk) != NULL) { (punk)->lpVtbl->Release((punk)); (punk) = NULL; }
-
-// Mixer function
-typedef void (*MixMonoToStereoF) (void *__to, void *__from, UINT32 count);
-
-// AVRT is the new "multimedia schedulling stuff"
-typedef BOOL   (WINAPI *FAvRtCreateThreadOrderingGroup)  (PHANDLE,PLARGE_INTEGER,GUID*,PLARGE_INTEGER);
-typedef BOOL   (WINAPI *FAvRtDeleteThreadOrderingGroup)  (HANDLE);
-typedef BOOL   (WINAPI *FAvRtWaitOnThreadOrderingGroup)  (HANDLE);
-typedef HANDLE (WINAPI *FAvSetMmThreadCharacteristics)   (LPCTSTR,LPDWORD);
-typedef BOOL   (WINAPI *FAvRevertMmThreadCharacteristics)(HANDLE);
-typedef BOOL   (WINAPI *FAvSetMmThreadPriority)          (HANDLE,AVRT_PRIORITY);
-
-static HMODULE hDInputDLL = 0;
-FAvRtCreateThreadOrderingGroup   pAvRtCreateThreadOrderingGroup = NULL;
-FAvRtDeleteThreadOrderingGroup   pAvRtDeleteThreadOrderingGroup = NULL;
-FAvRtWaitOnThreadOrderingGroup   pAvRtWaitOnThreadOrderingGroup = NULL;
-FAvSetMmThreadCharacteristics    pAvSetMmThreadCharacteristics = NULL;
-FAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
-FAvSetMmThreadPriority           pAvSetMmThreadPriority = NULL;
-
-#define _GetProc(fun, type, name)  {                                                        \
-                                        fun = (type) GetProcAddress(hDInputDLL,name);       \
-                                        if (fun == NULL) {                                  \
-                                            PRINT(("GetProcAddr failed for %s" ,name));     \
-                                            return FALSE;                                   \
-                                        }                                                   \
-                                    }                                                       \
-
-// ------------------------------------------------------------------------------------------
-/* prototypes for functions declared in this file */
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-// dummy entry point for other compilers and sdks
-// currently built using RC1 SDK (5600)
-//#if _MSC_VER < 1400
-//PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
-//{
-    //return paNoError;
-//}
-//#else
-
-// ------------------------------------------------------------------------------------------
-static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
-static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
-                                  const PaStreamParameters *inputParameters,
-                                  const PaStreamParameters *outputParameters,
-                                  double sampleRate );
-static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
-                           PaStream** s,
-                           const PaStreamParameters *inputParameters,
-                           const PaStreamParameters *outputParameters,
-                           double sampleRate,
-                           unsigned long framesPerBuffer,
-                           PaStreamFlags streamFlags,
-                           PaStreamCallback *streamCallback,
-                           void *userData );
-static PaError CloseStream( PaStream* stream );
-static PaError StartStream( PaStream *stream );
-static PaError StopStream( PaStream *stream );
-static PaError AbortStream( PaStream *stream );
-static PaError IsStreamStopped( PaStream *s );
-static PaError IsStreamActive( PaStream *stream );
-static PaTime GetStreamTime( PaStream *stream );
-static double GetStreamCpuLoad( PaStream* stream );
-static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
-static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
-static signed long GetStreamReadAvailable( PaStream* stream );
-static signed long GetStreamWriteAvailable( PaStream* stream );
-
-// ------------------------------------------------------------------------------------------
-/*
- These are fields that can be gathered from IDevice and IAudioDevice PRIOR to Initialize, and
- done in first pass i assume that neither of these will cause the Driver to "load", but again,
- who knows how they implement their stuff
- */
-typedef struct PaWasapiDeviceInfo
-{
-    // Device
-    IMMDevice *device;
-
-	// from GetId
-    WCHAR szDeviceID[MAX_STR_LEN];
-
-	// from GetState
-    DWORD state;
-
-    // Fields filled from IMMEndpoint'sGetDataFlow
-    EDataFlow flow;
-
-    // Fields filled from IAudioDevice (_prior_ to Initialize)
-    // from GetDevicePeriod(
-    REFERENCE_TIME DefaultDevicePeriod;
-    REFERENCE_TIME MinimumDevicePeriod;
-
-    // from GetMixFormat
-    // WAVEFORMATEX *MixFormat;//needs to be CoTaskMemFree'd after use!
-
-	// Default format (setup through Control Panel by user)
-	WAVEFORMATEXTENSIBLE DefaultFormat;
-
-	// Formfactor
-	EndpointFormFactor formFactor;
-}
-PaWasapiDeviceInfo;
-
-// ------------------------------------------------------------------------------------------
-/* PaWasapiHostApiRepresentation - host api datastructure specific to this implementation */
-typedef struct
-{
-    PaUtilHostApiRepresentation inheritedHostApiRep;
-    PaUtilStreamInterface callbackStreamInterface;
-    PaUtilStreamInterface blockingStreamInterface;
-
-    PaUtilAllocationGroup *allocations;
-
-    /* implementation specific data goes here */
-
-    //in case we later need the synch
-    IMMDeviceEnumerator *enumerator;
-
-    //this is the REAL number of devices, whether they are usefull to PA or not!
-    UINT32 deviceCount;
-
-    WCHAR defaultRenderer [MAX_STR_LEN];
-    WCHAR defaultCapturer [MAX_STR_LEN];
-
-    PaWasapiDeviceInfo *devInfo;
-
-	// Is true when WOW64 Vista/7 Workaround is needed
-	BOOL useWOW64Workaround;
-}
-PaWasapiHostApiRepresentation;
-
-// ------------------------------------------------------------------------------------------
-/* PaWasapiStream - a stream data structure specifically for this implementation */
-typedef struct PaWasapiSubStream
-{
-    IAudioClient        *client;
-    WAVEFORMATEXTENSIBLE wavex;
-    UINT32               bufferSize;
-    REFERENCE_TIME       device_latency;
-    REFERENCE_TIME       period;
-	double				 latency_seconds;
-    UINT32				 framesPerHostCallback;
-	AUDCLNT_SHAREMODE    shareMode;
-	UINT32               streamFlags; // AUDCLNT_STREAMFLAGS_EVENTCALLBACK, ...
-	UINT32               flags;
-
-	// Buffers
-	UINT32               buffers;			//!< number of buffers used (from host side)
-	UINT32               framesPerBuffer;	//!< number of frames per 1 buffer
-	BOOL                 userBufferAndHostMatch;
-
-	// Used by blocking interface:
-	UINT32               prevTime;  // time ms between calls of WriteStream
-	UINT32               prevSleep; // time ms to sleep from frames written in previous call
-
-	// Used for Mono >> Stereo workaround, if driver does not support it
-	// (in Exclusive mode WASAPI usually refuses to operate with Mono (1-ch)
-	void                *monoBuffer;	 //!< pointer to buffer
-	UINT32               monoBufferSize; //!< buffer size in bytes
-	MixMonoToStereoF     monoMixer;		 //!< pointer to mixer function
-}
-PaWasapiSubStream;
-
-// ------------------------------------------------------------------------------------------
-/* PaWasapiHostProcessor - redirects processing data */
-typedef struct PaWasapiHostProcessor
-{
-    PaWasapiHostProcessorCallback processor;
-    void *userData;
-}
-PaWasapiHostProcessor;
-
-// ------------------------------------------------------------------------------------------
-typedef struct PaWasapiStream
-{
-	/* IMPLEMENT ME: rename this */
-    PaUtilStreamRepresentation streamRepresentation;
-    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
-    PaUtilBufferProcessor bufferProcessor;
-
-    // input
-	PaWasapiSubStream in;
-    IAudioCaptureClient *cclient;
-    IAudioEndpointVolume *inVol;
-
-	// output
-	PaWasapiSubStream out;
-    IAudioRenderClient  *rclient;
-	IAudioEndpointVolume *outVol;
-
-	// event handles for event-driven processing mode
-	HANDLE event[S_COUNT];
-
-	// buffer mode
-	PaUtilHostBufferSizeMode bufferMode;
-
-	// must be volatile to avoid race condition on user query while
-	// thread is being started
-    volatile BOOL running;
-
-    PA_THREAD_ID dwThreadId;
-    HANDLE hThread;
-	HANDLE hCloseRequest;
-	HANDLE hThreadStart;        //!< signalled by thread on start
-	HANDLE hThreadExit;         //!< signalled by thread on exit
-	HANDLE hBlockingOpStreamRD;
-	HANDLE hBlockingOpStreamWR;
-
-    // Host callback Output overrider
-	PaWasapiHostProcessor hostProcessOverrideOutput;
-
-    // Host callback Input overrider
-	PaWasapiHostProcessor hostProcessOverrideInput;
-
-	// Defines blocking/callback interface used
-	BOOL bBlocking;
-
-	// Av Task (MM thread management)
-	HANDLE hAvTask;
-
-	// Thread priority level
-	PaWasapiThreadPriority nThreadPriority;
-}
-PaWasapiStream;
-
-// Local stream methods
-static void _OnStreamStop(PaWasapiStream *stream);
-static void _FinishStream(PaWasapiStream *stream);
-
-// Local statics
-static volatile BOOL  g_WasapiCOMInit    = FALSE;
-static volatile DWORD g_WasapiInitThread = 0;
-
-// ------------------------------------------------------------------------------------------
-#define LogHostError(HRES) __LogHostError(HRES, __FUNCTION__, __FILE__, __LINE__)
-static HRESULT __LogHostError(HRESULT res, const char *func, const char *file, int line)
-{
-    const char *text = NULL;
-    switch (res)
-	{
-	case S_OK: return res;
-	case E_POINTER                              :text ="E_POINTER"; break;
-	case E_INVALIDARG                           :text ="E_INVALIDARG"; break;
-
-	case AUDCLNT_E_NOT_INITIALIZED              :text ="AUDCLNT_E_NOT_INITIALIZED"; break;
-	case AUDCLNT_E_ALREADY_INITIALIZED          :text ="AUDCLNT_E_ALREADY_INITIALIZED"; break;
-	case AUDCLNT_E_WRONG_ENDPOINT_TYPE          :text ="AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
-	case AUDCLNT_E_DEVICE_INVALIDATED           :text ="AUDCLNT_E_DEVICE_INVALIDATED"; break;
-	case AUDCLNT_E_NOT_STOPPED                  :text ="AUDCLNT_E_NOT_STOPPED"; break;
-	case AUDCLNT_E_BUFFER_TOO_LARGE             :text ="AUDCLNT_E_BUFFER_TOO_LARGE"; break;
-	case AUDCLNT_E_OUT_OF_ORDER                 :text ="AUDCLNT_E_OUT_OF_ORDER"; break;
-	case AUDCLNT_E_UNSUPPORTED_FORMAT           :text ="AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
-	case AUDCLNT_E_INVALID_SIZE                 :text ="AUDCLNT_E_INVALID_SIZE"; break;
-	case AUDCLNT_E_DEVICE_IN_USE                :text ="AUDCLNT_E_DEVICE_IN_USE"; break;
-	case AUDCLNT_E_BUFFER_OPERATION_PENDING     :text ="AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
-	case AUDCLNT_E_THREAD_NOT_REGISTERED        :text ="AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
-	case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED   :text ="AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
-	case AUDCLNT_E_ENDPOINT_CREATE_FAILED       :text ="AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
-	case AUDCLNT_E_SERVICE_NOT_RUNNING          :text ="AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
-	case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED     :text ="AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
-	case AUDCLNT_E_EXCLUSIVE_MODE_ONLY          :text ="AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
-	case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL :text ="AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
-	case AUDCLNT_E_EVENTHANDLE_NOT_SET          :text ="AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
-	case AUDCLNT_E_INCORRECT_BUFFER_SIZE        :text ="AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
-	case AUDCLNT_E_BUFFER_SIZE_ERROR            :text ="AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
-	case AUDCLNT_E_CPUUSAGE_EXCEEDED            :text ="AUDCLNT_E_CPUUSAGE_EXCEEDED"; break;
-	case AUDCLNT_E_BUFFER_ERROR					:text ="AUDCLNT_E_BUFFER_ERROR"; break;
-	case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED		:text ="AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED"; break;
-	case AUDCLNT_E_INVALID_DEVICE_PERIOD		:text ="AUDCLNT_E_INVALID_DEVICE_PERIOD"; break;
-
-	case AUDCLNT_S_BUFFER_EMPTY                 :text ="AUDCLNT_S_BUFFER_EMPTY"; break;
-	case AUDCLNT_S_THREAD_ALREADY_REGISTERED    :text ="AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
-	case AUDCLNT_S_POSITION_STALLED				:text ="AUDCLNT_S_POSITION_STALLED"; break;
-
-	// other windows common errors:
-	case CO_E_NOTINITIALIZED                    :text ="CO_E_NOTINITIALIZED: you must call CoInitialize() before Pa_OpenStream()"; break;
-
-	default:
-		text = "UNKNOWN ERROR";
-    }
-	PRINT(("WASAPI ERROR HRESULT: 0x%X : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", res, text, func, file, line));
-	PA_SKELETON_SET_LAST_HOST_ERROR(res, text);
-	return res;
-}
-
-// ------------------------------------------------------------------------------------------
-#define LogPaError(PAERR) __LogPaError(PAERR, __FUNCTION__, __FILE__, __LINE__)
-static PaError __LogPaError(PaError err, const char *func, const char *file, int line)
-{
-	if (err == paNoError)
-		return err;
-	PRINT(("WASAPI ERROR PAERROR: %i : %s\n [FUNCTION: %s FILE: %s {LINE: %d}]\n", err, Pa_GetErrorText(err), func, file, line));
-	return err;
-}
-
-// ------------------------------------------------------------------------------------------
-/*static double nano100ToMillis(REFERENCE_TIME ref)
-{
-    //  1 nano = 0.000000001 seconds
-    //100 nano = 0.0000001   seconds
-    //100 nano = 0.0001   milliseconds
-    return ((double)ref)*0.0001;
-}*/
-
-// ------------------------------------------------------------------------------------------
-static double nano100ToSeconds(REFERENCE_TIME ref)
-{
-    //  1 nano = 0.000000001 seconds
-    //100 nano = 0.0000001   seconds
-    //100 nano = 0.0001   milliseconds
-    return ((double)ref)*0.0000001;
-}
-
-// ------------------------------------------------------------------------------------------
-/*static REFERENCE_TIME MillisTonano100(double ref)
-{
-    //  1 nano = 0.000000001 seconds
-    //100 nano = 0.0000001   seconds
-    //100 nano = 0.0001   milliseconds
-    return (REFERENCE_TIME)(ref/0.0001);
-}*/
-
-// ------------------------------------------------------------------------------------------
-static REFERENCE_TIME SecondsTonano100(double ref)
-{
-    //  1 nano = 0.000000001 seconds
-    //100 nano = 0.0000001   seconds
-    //100 nano = 0.0001   milliseconds
-    return (REFERENCE_TIME)(ref/0.0000001);
-}
-
-// ------------------------------------------------------------------------------------------
-// Makes Hns period from frames and sample rate
-static REFERENCE_TIME MakeHnsPeriod(UINT32 nFrames, DWORD nSamplesPerSec)
-{
-	return (REFERENCE_TIME)((10000.0 * 1000 / nSamplesPerSec * nFrames) + 0.5);
-}
-
-// ------------------------------------------------------------------------------------------
-// Converts PaSampleFormat to bits per sample value
-static WORD PaSampleFormatToBitsPerSample(PaSampleFormat format_id)
-{
-	switch (format_id & ~paNonInterleaved)
-	{
-		case paFloat32:
-		case paInt32: return 32;
-		case paInt24: return 24;
-		case paInt16: return 16;
-		case paInt8:
-		case paUInt8: return 8;
-	}
-	return 0;
-}
-
-// ------------------------------------------------------------------------------------------
-// Converts PaSampleFormat to bits per sample value
-/*static WORD PaSampleFormatToBytesPerSample(PaSampleFormat format_id)
-{
-	return PaSampleFormatToBitsPerSample(format_id) >> 3; // 'bits/8'
-}*/
-
-// ------------------------------------------------------------------------------------------
-// Converts Hns period into number of frames
-static UINT32 MakeFramesFromHns(REFERENCE_TIME hnsPeriod, UINT32 nSamplesPerSec)
-{
-    UINT32 nFrames = (UINT32)(	// frames =
-        1.0 * hnsPeriod *		// hns *
-        nSamplesPerSec /		// (frames / s) /
-        1000 /					// (ms / s) /
-        10000					// (hns / s) /
-        + 0.5					// rounding
-    );
-	return nFrames;
-}
-
-// Aligning function type
-typedef UINT32 (*ALIGN_FUNC) (UINT32 v, UINT32 align);
-
-// ------------------------------------------------------------------------------------------
-// Aligns 'v' backwards
-static UINT32 ALIGN_BWD(UINT32 v, UINT32 align)
-{
-	return ((v - (align ? v % align : 0)));
-}
-
-// ------------------------------------------------------------------------------------------
-// Aligns 'v' forward
-/*static UINT32 ALIGN_FWD(UINT32 v, UINT32 align)
-{
-	UINT32 remainder = (align ? (v % align) : 0);
-	if (remainder == 0)
-		return v;
-	return v + (align - remainder);
-}*/
-
-// ------------------------------------------------------------------------------------------
-// Aligns WASAPI buffer to 128 byte packet boundary. HD Audio will fail to play if buffer
-// is misaligned. This problem was solved in Windows 7 were AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED
-// is thrown although we must align for Vista anyway.
-static UINT32 AlignFramesPerBuffer(UINT32 nFrames, UINT32 nSamplesPerSec, UINT32 nBlockAlign,
-								   ALIGN_FUNC pAlignFunc)
-{
-#define HDA_PACKET_SIZE (128)
-
-	long frame_bytes = nFrames * nBlockAlign;
-	long packets;
-
-	// align to packet size
-	frame_bytes  = pAlignFunc(frame_bytes, HDA_PACKET_SIZE); // use ALIGN_FWD if bigger but safer period is more desired
-	nFrames      = frame_bytes / nBlockAlign;
-	packets      = frame_bytes / HDA_PACKET_SIZE;
-
-	frame_bytes = packets * HDA_PACKET_SIZE;
-	nFrames     = frame_bytes / nBlockAlign;
-
-	return nFrames;
-
-#undef HDA_PACKET_SIZE
-}
-
-// ------------------------------------------------------------------------------------------
-static UINT32 GetFramesSleepTime(UINT32 nFrames, UINT32 nSamplesPerSec)
-{
-	REFERENCE_TIME nDuration;
-	if (nSamplesPerSec == 0)
-		return 0;
-#define REFTIMES_PER_SEC  10000000
-#define REFTIMES_PER_MILLISEC  10000
-	// Calculate the actual duration of the allocated buffer.
-	nDuration = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * nFrames / nSamplesPerSec);
-	return (UINT32)(nDuration/REFTIMES_PER_MILLISEC/2);
-}
-
-// ------------------------------------------------------------------------------------------
-static BOOL SetupAVRT()
-{
-    hDInputDLL = LoadLibraryA("avrt.dll");
-    if (hDInputDLL == NULL)
-        return FALSE;
-
-    _GetProc(pAvRtCreateThreadOrderingGroup,  FAvRtCreateThreadOrderingGroup,  "AvRtCreateThreadOrderingGroup");
-    _GetProc(pAvRtDeleteThreadOrderingGroup,  FAvRtDeleteThreadOrderingGroup,  "AvRtDeleteThreadOrderingGroup");
-    _GetProc(pAvRtWaitOnThreadOrderingGroup,  FAvRtWaitOnThreadOrderingGroup,  "AvRtWaitOnThreadOrderingGroup");
-    _GetProc(pAvSetMmThreadCharacteristics,   FAvSetMmThreadCharacteristics,   "AvSetMmThreadCharacteristicsA");
-	_GetProc(pAvRevertMmThreadCharacteristics,FAvRevertMmThreadCharacteristics,"AvRevertMmThreadCharacteristics");
-    _GetProc(pAvSetMmThreadPriority,          FAvSetMmThreadPriority,          "AvSetMmThreadPriority");
-
-	return pAvRtCreateThreadOrderingGroup &&
-		pAvRtDeleteThreadOrderingGroup &&
-		pAvRtWaitOnThreadOrderingGroup &&
-		pAvSetMmThreadCharacteristics &&
-		pAvRevertMmThreadCharacteristics &&
-		pAvSetMmThreadPriority;
-}
-
-// ------------------------------------------------------------------------------------------
-static void CloseAVRT()
-{
-	if (hDInputDLL != NULL)
-		FreeLibrary(hDInputDLL);
-	hDInputDLL = NULL;
-}
-
-// ------------------------------------------------------------------------------------------
-static BOOL IsWow64()
-{
-	// http://msdn.microsoft.com/en-us/library/ms684139(VS.85).aspx
-
-	typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
-	LPFN_ISWOW64PROCESS fnIsWow64Process;
-
-    BOOL bIsWow64 = FALSE;
-
-    // IsWow64Process is not available on all supported versions of Windows.
-    // Use GetModuleHandle to get a handle to the DLL that contains the function
-    // and GetProcAddress to get a pointer to the function if available.
-
-    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(
-        GetModuleHandle(TEXT("kernel32")), TEXT("IsWow64Process"));
-
-    if (fnIsWow64Process == NULL)
-		return FALSE;
-
-    if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
-		return FALSE;
-
-    return bIsWow64;
-}
-
-// ------------------------------------------------------------------------------------------
-typedef enum EWindowsVersion
-{
-	WINDOWS_UNKNOWN			 = 0,
-	WINDOWS_VISTA_SERVER2008 = (1 << 0),
-	WINDOWS_7_SERVER2008R2	 = (1 << 1),
-	WINDOWS_FUTURE           = (1 << 2)
-}
-EWindowsVersion;
-// Defines Windows 7/Windows Server 2008 R2 and up (future versions)
-#define WINDOWS_7_SERVER2008R2_AND_UP (WINDOWS_7_SERVER2008R2|WINDOWS_FUTURE)
-// The function is limited to Vista/7 mostly as we need just to find out Vista/WOW64 combination
-// in order to use WASAPI WOW64 workarounds.
-static UINT32 GetWindowsVersion()
-{
-	static UINT32 version = WINDOWS_UNKNOWN;
-
-	if (version == WINDOWS_UNKNOWN)
-	{
-		DWORD dwVersion = 0;
-		DWORD dwMajorVersion = 0;
-		DWORD dwMinorVersion = 0;
-		DWORD dwBuild = 0;
-
-		typedef DWORD (WINAPI *LPFN_GETVERSION)(VOID);
-		LPFN_GETVERSION fnGetVersion;
-
-		fnGetVersion = (LPFN_GETVERSION) GetProcAddress(GetModuleHandle(TEXT("kernel32")), TEXT("GetVersion"));
-		if (fnGetVersion == NULL)
-			return WINDOWS_UNKNOWN;
-
-		dwVersion = fnGetVersion();
-
-		// Get the Windows version
-		dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
-		dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
-
-		// Get the build number
-		if (dwVersion < 0x80000000)
-			dwBuild = (DWORD)(HIWORD(dwVersion));
-
-		switch (dwMajorVersion)
-		{
-		case 0:
-		case 1:
-		case 2:
-		case 3:
-		case 4:
-		case 5:
-			break; // skip lower
-		case 6:
-			switch (dwMinorVersion)
-			{
-			case 0:
-				version |= WINDOWS_VISTA_SERVER2008;
-				break;
-			case 1:
-				version |= WINDOWS_7_SERVER2008R2;
-				break;
-			default:
-				version |= WINDOWS_FUTURE;
-			}
-			break;
-		default:
-			version |= WINDOWS_FUTURE;
-		}
-	}
-
-	return version;
-}
-
-// ------------------------------------------------------------------------------------------
-static BOOL UseWOW64Workaround()
-{
-	// note: WOW64 bug is common to Windows Vista x64, thus we fall back to safe Poll-driven
-	//       method. Windows 7 x64 seems has WOW64 bug fixed.
-
-	return (IsWow64() && (GetWindowsVersion() & WINDOWS_VISTA_SERVER2008));
-}
-
-// ------------------------------------------------------------------------------------------
-typedef enum EMixerDir { MIX_DIR__1TO2, MIX_DIR__2TO1 } EMixerDir;
-
-// ------------------------------------------------------------------------------------------
-#define _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(TYPE)\
-	TYPE * __restrict to   = __to;\
-	TYPE * __restrict from = __from;\
-	TYPE * __restrict end  = from + count;\
-	while (from != end)\
-	{\
-		*to ++ = *from;\
-		*to ++ = *from;\
-		++ from;\
-	}
-
-// ------------------------------------------------------------------------------------------
-#define _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1(TYPE)\
-	TYPE * __restrict to   = (TYPE *)__to;\
-	TYPE * __restrict from = (TYPE *)__from;\
-	TYPE * __restrict end  = to + count;\
-	while (to != end)\
-	{\
-		*to ++ = (TYPE)((float)(from[0] + from[1]) * 0.5f);\
-		from += 2;\
-	}
-
-// ------------------------------------------------------------------------------------------
-static void _MixMonoToStereo_1TO2_8(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(BYTE); }
-static void _MixMonoToStereo_1TO2_16(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(short); }
-static void _MixMonoToStereo_1TO2_24(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); /* !!! int24 data is contained in 32-bit containers*/ }
-static void _MixMonoToStereo_1TO2_32(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(int); }
-static void _MixMonoToStereo_1TO2_32f(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_1_TO_2(float); }
-
-// ------------------------------------------------------------------------------------------
-static void _MixMonoToStereo_2TO1_8(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1(BYTE); }
-static void _MixMonoToStereo_2TO1_16(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1(short); }
-static void _MixMonoToStereo_2TO1_24(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1(int); /* !!! int24 data is contained in 32-bit containers*/ }
-static void _MixMonoToStereo_2TO1_32(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1(int); }
-static void _MixMonoToStereo_2TO1_32f(void *__to, void *__from, UINT32 count) { _WASAPI_MONO_TO_STEREO_MIXER_2_TO_1(float); }
-
-// ------------------------------------------------------------------------------------------
-static MixMonoToStereoF _GetMonoToStereoMixer(PaSampleFormat format, EMixerDir dir)
-{
-	switch (dir)
-	{
-	case MIX_DIR__1TO2:
-		switch (format & ~paNonInterleaved)
-		{
-		case paUInt8:	return _MixMonoToStereo_1TO2_8;
-		case paInt16:	return _MixMonoToStereo_1TO2_16;
-		case paInt24:	return _MixMonoToStereo_1TO2_24;
-		case paInt32:	return _MixMonoToStereo_1TO2_32;
-		case paFloat32: return _MixMonoToStereo_1TO2_32f;
-		}
-		break;
-
-	case MIX_DIR__2TO1:
-		switch (format & ~paNonInterleaved)
-		{
-		case paUInt8:	return _MixMonoToStereo_2TO1_8;
-		case paInt16:	return _MixMonoToStereo_2TO1_16;
-		case paInt24:	return _MixMonoToStereo_2TO1_24;
-		case paInt32:	return _MixMonoToStereo_2TO1_32;
-		case paFloat32: return _MixMonoToStereo_2TO1_32f;
-		}
-		break;
-	}
-
-	return NULL;
-}
-
-// ------------------------------------------------------------------------------------------
-PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
-{
-    PaError result = paNoError;
-    PaWasapiHostApiRepresentation *paWasapi;
-    PaDeviceInfo *deviceInfoArray;
-    HRESULT hr = S_OK;
-    IMMDeviceCollection* pEndPoints = NULL;
-	UINT i;
-
-    if (!SetupAVRT())
-	{
-        PRINT(("WASAPI: No AVRT! (not VISTA?)"));
-        return paNoError;
-    }
-
-    /*
-        If COM is already initialized CoInitialize will either return
-        FALSE, or RPC_E_CHANGED_MODE if it was initialised in a different
-        threading mode. In either case we shouldn't consider it an error
-        but we need to be careful to not call CoUninitialize() if
-        RPC_E_CHANGED_MODE was returned.
-    */
-    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
-    if (FAILED(hr) && (hr != RPC_E_CHANGED_MODE))
-	{
-		PRINT(("WASAPI: failed CoInitialize"));
-        return paUnanticipatedHostError;
-	}
-    if (hr != RPC_E_CHANGED_MODE)
-        g_WasapiCOMInit = TRUE;
-
-	// Memorize calling thread id and report warning on Uninitialize if calling thread is different
-	// as CoInitialize must match CoUninitialize in the same thread.
-	g_WasapiInitThread = GetCurrentThreadId();
-
-    paWasapi = (PaWasapiHostApiRepresentation *)PaUtil_AllocateMemory( sizeof(PaWasapiHostApiRepresentation) );
-    if (paWasapi == NULL)
-	{
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    paWasapi->allocations = PaUtil_CreateAllocationGroup();
-    if (paWasapi->allocations == NULL)
-	{
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    *hostApi                             = &paWasapi->inheritedHostApiRep;
-    (*hostApi)->info.structVersion		 = 1;
-    (*hostApi)->info.type				 = paWASAPI;
-    (*hostApi)->info.name				 = "Windows WASAPI";
-    (*hostApi)->info.deviceCount		 = 0;
-    (*hostApi)->info.defaultInputDevice	 = paNoDevice;
-    (*hostApi)->info.defaultOutputDevice = paNoDevice;
-
-    paWasapi->enumerator = NULL;
-    hr = CoCreateInstance(&pa_CLSID_IMMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER,
-             &pa_IID_IMMDeviceEnumerator, (void **)&paWasapi->enumerator);
-    IF_FAILED_JUMP(hr, error);
-
-    // getting default device ids in the eMultimedia "role"
-    {
-        {
-            IMMDevice *defaultRenderer = NULL;
-            hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(paWasapi->enumerator, eRender, eMultimedia, &defaultRenderer);
-            if (hr != S_OK)
-			{
-				if (hr != E_NOTFOUND)
-					IF_FAILED_JUMP(hr, error);
-			}
-			else
-			{
-				WCHAR *pszDeviceId = NULL;
-				hr = IMMDevice_GetId(defaultRenderer, &pszDeviceId);
-				IF_FAILED_JUMP(hr, error);
-				wcsncpy(paWasapi->defaultRenderer, pszDeviceId, MAX_STR_LEN-1);
-				CoTaskMemFree(pszDeviceId);
-				IMMDevice_Release(defaultRenderer);
-			}
-        }
-
-        {
-            IMMDevice *defaultCapturer = NULL;
-            hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(paWasapi->enumerator, eCapture, eMultimedia, &defaultCapturer);
-            if (hr != S_OK)
-			{
-				if (hr != E_NOTFOUND)
-					IF_FAILED_JUMP(hr, error);
-			}
-			else
-			{
-				WCHAR *pszDeviceId = NULL;
-				hr = IMMDevice_GetId(defaultCapturer, &pszDeviceId);
-				IF_FAILED_JUMP(hr, error);
-				wcsncpy(paWasapi->defaultCapturer, pszDeviceId, MAX_STR_LEN-1);
-				CoTaskMemFree(pszDeviceId);
-				IMMDevice_Release(defaultCapturer);
-			}
-        }
-    }
-
-    hr = IMMDeviceEnumerator_EnumAudioEndpoints(paWasapi->enumerator, eAll, DEVICE_STATE_ACTIVE, &pEndPoints);
-    IF_FAILED_JUMP(hr, error);
-
-    hr = IMMDeviceCollection_GetCount(pEndPoints, &paWasapi->deviceCount);
-    IF_FAILED_JUMP(hr, error);
-
-    paWasapi->devInfo = (PaWasapiDeviceInfo *)malloc(sizeof(PaWasapiDeviceInfo) * paWasapi->deviceCount);
-	for (i = 0; i < paWasapi->deviceCount; ++i)
-		memset(&paWasapi->devInfo[i], 0, sizeof(PaWasapiDeviceInfo));
-
-    if (paWasapi->deviceCount > 0)
-    {
-        (*hostApi)->deviceInfos = (PaDeviceInfo **)PaUtil_GroupAllocateMemory(
-                paWasapi->allocations, sizeof(PaDeviceInfo *) * paWasapi->deviceCount);
-        if ((*hostApi)->deviceInfos == NULL)
-		{
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-        /* allocate all device info structs in a contiguous block */
-        deviceInfoArray = (PaDeviceInfo *)PaUtil_GroupAllocateMemory(
-                paWasapi->allocations, sizeof(PaDeviceInfo) * paWasapi->deviceCount);
-        if (deviceInfoArray == NULL)
-		{
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-        for (i = 0; i < paWasapi->deviceCount; ++i)
-		{
-			DWORD state				  = 0;
-            PaDeviceInfo *deviceInfo  = &deviceInfoArray[i];
-            deviceInfo->structVersion = 2;
-            deviceInfo->hostApi       = hostApiIndex;
-
-			PA_DEBUG(("WASAPI: device idx: %02d\n", i));
-			PA_DEBUG(("WASAPI: ---------------\n"));
-
-            hr = IMMDeviceCollection_Item(pEndPoints, i, &paWasapi->devInfo[i].device);
-            IF_FAILED_JUMP(hr, error);
-
-            // getting ID
-            {
-                WCHAR *pszDeviceId = NULL;
-                hr = IMMDevice_GetId(paWasapi->devInfo[i].device, &pszDeviceId);
-                IF_FAILED_JUMP(hr, error);
-                wcsncpy(paWasapi->devInfo[i].szDeviceID, pszDeviceId, MAX_STR_LEN-1);
-                CoTaskMemFree(pszDeviceId);
-
-                if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultCapturer) == 0)
-				{// we found the default input!
-                    (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
-                }
-                if (lstrcmpW(paWasapi->devInfo[i].szDeviceID, paWasapi->defaultRenderer) == 0)
-				{// we found the default output!
-                    (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
-                }
-            }
-
-            hr = IMMDevice_GetState(paWasapi->devInfo[i].device, &paWasapi->devInfo[i].state);
-            IF_FAILED_JUMP(hr, error);
-
-            if (paWasapi->devInfo[i].state != DEVICE_STATE_ACTIVE)
-			{
-                PRINT(("WASAPI device: %d is not currently available (state:%d)\n",i,state));
-            }
-
-            {
-                IPropertyStore *pProperty;
-                hr = IMMDevice_OpenPropertyStore(paWasapi->devInfo[i].device, STGM_READ, &pProperty);
-                IF_FAILED_JUMP(hr, error);
-
-                // "Friendly" Name
-                {
-					char *deviceName;
-                    PROPVARIANT value;
-                    PropVariantInit(&value);
-                    hr = IPropertyStore_GetValue(pProperty, &PKEY_Device_FriendlyName, &value);
-                    IF_FAILED_JUMP(hr, error);
-                    deviceInfo->name = NULL;
-                    deviceName = (char *)PaUtil_GroupAllocateMemory(paWasapi->allocations, MAX_STR_LEN + 1);
-                    if (deviceName == NULL)
-					{
-                        result = paInsufficientMemory;
-                        goto error;
-                    }
-					if (value.pwszVal)
-						wcstombs(deviceName, value.pwszVal, MAX_STR_LEN-1);
-					else
-						_snprintf(deviceName, MAX_STR_LEN-1, "baddev%d", i);
-                    deviceInfo->name = deviceName;
-                    PropVariantClear(&value);
-					PA_DEBUG(("WASAPI:%d| name[%s]\n", i, deviceInfo->name));
-                }
-
-                // Default format
-                {
-                    PROPVARIANT value;
-                    PropVariantInit(&value);
-                    hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEngine_DeviceFormat, &value);
-                    IF_FAILED_JUMP(hr, error);
-					memcpy(&paWasapi->devInfo[i].DefaultFormat, value.blob.pBlobData, min(sizeof(paWasapi->devInfo[i].DefaultFormat), value.blob.cbSize));
-                    // cleanup
-                    PropVariantClear(&value);
-                }
-
-                // Formfactor
-                {
-                    PROPVARIANT value;
-                    PropVariantInit(&value);
-                    hr = IPropertyStore_GetValue(pProperty, &PKEY_AudioEndpoint_FormFactor, &value);
-                    IF_FAILED_JUMP(hr, error);
-					// set
-					#if defined(DUMMYUNIONNAME) && defined(NONAMELESSUNION)
-						// avoid breaking strict-aliasing rules in such line: (EndpointFormFactor)(*((UINT *)(((WORD *)&value.wReserved3)+1)));
-						UINT v;
-						memcpy(&v, (((WORD *)&value.wReserved3)+1), sizeof(v));
-						paWasapi->devInfo[i].formFactor = (EndpointFormFactor)v;
-					#else
-						paWasapi->devInfo[i].formFactor = (EndpointFormFactor)value.uintVal;
-					#endif
-					PA_DEBUG(("WASAPI:%d| form-factor[%d]\n", i, paWasapi->devInfo[i].formFactor));
-                    // cleanup
-                    PropVariantClear(&value);
-                }
-
-				SAFE_RELEASE(pProperty);
-            }
-
-
-            // Endpoint data
-            {
-                IMMEndpoint *endpoint = NULL;
-                hr = IMMDevice_QueryInterface(paWasapi->devInfo[i].device, &pa_IID_IMMEndpoint, (void **)&endpoint);
-                if (SUCCEEDED(hr))
-				{
-                    hr = IMMEndpoint_GetDataFlow(endpoint, &paWasapi->devInfo[i].flow);
-                    SAFE_RELEASE(endpoint);
-                }
-            }
-
-            // Getting a temporary IAudioClient for more fields
-            // we make sure NOT to call Initialize yet!
-            {
-                IAudioClient *tmpClient = NULL;
-
-                hr = IMMDevice_Activate(paWasapi->devInfo[i].device, &pa_IID_IAudioClient,
-					CLSCTX_INPROC_SERVER, NULL, (void **)&tmpClient);
-                IF_FAILED_JUMP(hr, error);
-
-                hr = IAudioClient_GetDevicePeriod(tmpClient,
-                    &paWasapi->devInfo[i].DefaultDevicePeriod,
-                    &paWasapi->devInfo[i].MinimumDevicePeriod);
-                IF_FAILED_JUMP(hr, error);
-
-                //hr = tmpClient->GetMixFormat(&paWasapi->devInfo[i].MixFormat);
-
-				// Release client
-				SAFE_RELEASE(tmpClient);
-
-				if (hr != S_OK)
-				{
-					//davidv: this happened with my hardware, previously for that same device in DirectSound:
-					//Digital Output (Realtek AC'97 Audio)'s GUID: {0x38f2cf50,0x7b4c,0x4740,0x86,0xeb,0xd4,0x38,0x66,0xd8,0xc8, 0x9f}
-					//so something must be _really_ wrong with this device, TODO handle this better. We kind of need GetMixFormat
-					LogHostError(hr);
-					goto error;
-				}
-            }
-
-            // we can now fill in portaudio device data
-            deviceInfo->maxInputChannels  = 0;
-            deviceInfo->maxOutputChannels = 0;
-			deviceInfo->defaultSampleRate = paWasapi->devInfo[i].DefaultFormat.Format.nSamplesPerSec;
-            switch (paWasapi->devInfo[i].flow)
-			{
-			case eRender: {
-                deviceInfo->maxOutputChannels		 = paWasapi->devInfo[i].DefaultFormat.Format.nChannels;
-                deviceInfo->defaultHighOutputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod);
-                deviceInfo->defaultLowOutputLatency  = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod);
-				PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", i, (UINT32)deviceInfo->defaultSampleRate,
-					deviceInfo->maxOutputChannels, (float)deviceInfo->defaultHighOutputLatency, (float)deviceInfo->defaultLowOutputLatency));
-				break;}
-			case eCapture: {
-                deviceInfo->maxInputChannels		= paWasapi->devInfo[i].DefaultFormat.Format.nChannels;
-                deviceInfo->defaultHighInputLatency = nano100ToSeconds(paWasapi->devInfo[i].DefaultDevicePeriod);
-                deviceInfo->defaultLowInputLatency  = nano100ToSeconds(paWasapi->devInfo[i].MinimumDevicePeriod);
-				PA_DEBUG(("WASAPI:%d| def.SR[%d] max.CH[%d] latency{hi[%f] lo[%f]}\n", i, (UINT32)deviceInfo->defaultSampleRate,
-					deviceInfo->maxInputChannels, (float)deviceInfo->defaultHighInputLatency, (float)deviceInfo->defaultLowInputLatency));
-				break; }
-            default:
-                PRINT(("WASAPI:%d| bad Data Flow!\n", i));
-                //continue; // do not skip from list, allow to initialize
-            break;
-            }
-
-            (*hostApi)->deviceInfos[i] = deviceInfo;
-            ++(*hostApi)->info.deviceCount;
-        }
-    }
-
-    (*hostApi)->Terminate = Terminate;
-    (*hostApi)->OpenStream = OpenStream;
-    (*hostApi)->IsFormatSupported = IsFormatSupported;
-
-    PaUtil_InitializeStreamInterface( &paWasapi->callbackStreamInterface, CloseStream, StartStream,
-                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
-                                      GetStreamTime, GetStreamCpuLoad,
-                                      PaUtil_DummyRead, PaUtil_DummyWrite,
-                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
-
-    PaUtil_InitializeStreamInterface( &paWasapi->blockingStreamInterface, CloseStream, StartStream,
-                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
-                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
-                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
-
-
-	// findout if platform workaround is required
-	paWasapi->useWOW64Workaround = UseWOW64Workaround();
-
-    SAFE_RELEASE(pEndPoints);
-
-	PRINT(("WASAPI: initialized ok\n"));
-
-    return paNoError;
-
-error:
-
-	PRINT(("WASAPI: failed %s error[%d|%s]\n", __FUNCTION__, result, Pa_GetErrorText(result)));
-
-    SAFE_RELEASE(pEndPoints);
-
-	Terminate((PaUtilHostApiRepresentation *)paWasapi);
-
-    return result;
-}
-
-// ------------------------------------------------------------------------------------------
-static void Terminate( PaUtilHostApiRepresentation *hostApi )
-{
-	UINT i;
-    PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
-	if (paWasapi == NULL)
-		return;
-
-	// Release IMMDeviceEnumerator
-    SAFE_RELEASE(paWasapi->enumerator);
-
-    for (i = 0; i < paWasapi->deviceCount; ++i)
-	{
-        PaWasapiDeviceInfo *info = &paWasapi->devInfo[i];
-        SAFE_RELEASE(info->device);
-
-		//if (info->MixFormat)
-        //    CoTaskMemFree(info->MixFormat);
-    }
-    free(paWasapi->devInfo);
-
-    if (paWasapi->allocations)
-	{
-        PaUtil_FreeAllAllocations(paWasapi->allocations);
-        PaUtil_DestroyAllocationGroup(paWasapi->allocations);
-    }
-
-    PaUtil_FreeMemory(paWasapi);
-
-	// Close AVRT
-	CloseAVRT();
-
-	// Uninit COM (checking calling thread we won't unitialize user's COM if one is calling
-	//             Pa_Unitialize by mistake from not initializing thread)
-    if (g_WasapiCOMInit)
-	{
-		DWORD calling_thread_id = GetCurrentThreadId();
-		if (g_WasapiInitThread != calling_thread_id)
-		{
-			PRINT(("WASAPI: failed CoUninitializes calling thread[%d] does not match initializing thread[%d]\n",
-				calling_thread_id, g_WasapiInitThread));
-		}
-		else
-		{
-			CoUninitialize();
-		}
-	}
-}
-
-// ------------------------------------------------------------------------------------------
-static PaWasapiHostApiRepresentation *_GetHostApi(PaError *_error)
-{
-	PaError error;
-
-	PaUtilHostApiRepresentation *pApi;
-	if ((error = PaUtil_GetHostApiRepresentation(&pApi, paWASAPI)) != paNoError)
-	{
-		if (_error != NULL)
-			(*_error) = error;
-
-		return NULL;
-	}
-	return (PaWasapiHostApiRepresentation *)pApi;
-}
-
-// ------------------------------------------------------------------------------------------
-int PaWasapi_GetDeviceDefaultFormat( void *pFormat, unsigned int nFormatSize, PaDeviceIndex nDevice )
-{
-	PaError ret;
-	PaWasapiHostApiRepresentation *paWasapi;
-	UINT32 size;
-	PaDeviceIndex index;
-
-	if (pFormat == NULL)
-		return paBadBufferPtr;
-	if (nFormatSize <= 0)
-		return paBufferTooSmall;
-
-	// Get API
-	paWasapi = _GetHostApi(&ret);
-	if (paWasapi == NULL)
-		return ret;
-
-	// Get device index
-	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
-    if (ret != paNoError)
-        return ret;
-
-	// Validate index
-	if ((UINT32)index >= paWasapi->deviceCount)
-		return paInvalidDevice;
-
-	size = min(nFormatSize, (UINT32)sizeof(paWasapi->devInfo[ index ].DefaultFormat));
-	memcpy(pFormat, &paWasapi->devInfo[ index ].DefaultFormat, size);
-
-	return size;
-}
-
-// ------------------------------------------------------------------------------------------
-int PaWasapi_GetDeviceRole( PaDeviceIndex nDevice )
-{
-	PaError ret;
-	PaDeviceIndex index;
-
-	// Get API
-	PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
-	if (paWasapi == NULL)
-		return paNotInitialized;
-
-	// Get device index
-	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
-    if (ret != paNoError)
-        return ret;
-
-	// Validate index
-	if ((UINT32)index >= paWasapi->deviceCount)
-		return paInvalidDevice;
-
-	return paWasapi->devInfo[ index ].formFactor;
-}
-
-// ------------------------------------------------------------------------------------------
-PaError PaWasapi_GetFramesPerHostBuffer( PaStream *pStream, unsigned int *nInput, unsigned int *nOutput )
-{
-    PaWasapiStream *stream = (PaWasapiStream *)pStream;
-	if (stream == NULL)
-		return paBadStreamPtr;
-
-	if (nInput != NULL)
-		(*nInput) = stream->in.framesPerHostCallback;
-
-	if (nOutput != NULL)
-		(*nOutput) = stream->out.framesPerHostCallback;
-
-	return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-static void LogWAVEFORMATEXTENSIBLE(const WAVEFORMATEXTENSIBLE *in)
-{
-    const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
-	switch (old->wFormatTag)
-	{
-	case WAVE_FORMAT_EXTENSIBLE: {
-
-		PRINT(("wFormatTag=WAVE_FORMAT_EXTENSIBLE\n"));
-
-		if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
-		{
-			PRINT(("SubFormat=KSDATAFORMAT_SUBTYPE_IEEE_FLOAT\n"));
-		}
-		else
-		if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
-		{
-			PRINT(("SubFormat=KSDATAFORMAT_SUBTYPE_PCM\n"));
-		}
-		else
-		{
-			PRINT(("SubFormat=CUSTOM GUID{%d:%d:%d:%d%d%d%d%d%d%d%d}\n",
-										in->SubFormat.Data1,
-										in->SubFormat.Data2,
-										in->SubFormat.Data3,
-										(int)in->SubFormat.Data4[0],
-										(int)in->SubFormat.Data4[1],
-										(int)in->SubFormat.Data4[2],
-										(int)in->SubFormat.Data4[3],
-										(int)in->SubFormat.Data4[4],
-										(int)in->SubFormat.Data4[5],
-										(int)in->SubFormat.Data4[6],
-										(int)in->SubFormat.Data4[7]));
-		}
-		PRINT(("Samples.wValidBitsPerSample=%d\n",  in->Samples.wValidBitsPerSample));
-		PRINT(("dwChannelMask  =0x%X\n",in->dwChannelMask));
-
-		break; }
-
-	case WAVE_FORMAT_PCM:        PRINT(("wFormatTag=WAVE_FORMAT_PCM\n")); break;
-	case WAVE_FORMAT_IEEE_FLOAT: PRINT(("wFormatTag=WAVE_FORMAT_IEEE_FLOAT\n")); break;
-	default : PRINT(("wFormatTag=UNKNOWN(%d)\n",old->wFormatTag)); break;
-	}
-
-	PRINT(("nChannels      =%d\n",old->nChannels));
-	PRINT(("nSamplesPerSec =%d\n",old->nSamplesPerSec));
-	PRINT(("nAvgBytesPerSec=%d\n",old->nAvgBytesPerSec));
-	PRINT(("nBlockAlign    =%d\n",old->nBlockAlign));
-	PRINT(("wBitsPerSample =%d\n",old->wBitsPerSample));
-	PRINT(("cbSize         =%d\n",old->cbSize));
-}
-
-// ------------------------------------------------------------------------------------------
-static PaSampleFormat WaveToPaFormat(const WAVEFORMATEXTENSIBLE *in)
-{
-    const WAVEFORMATEX *old = (WAVEFORMATEX *)in;
-
-    switch (old->wFormatTag)
-	{
-    case WAVE_FORMAT_EXTENSIBLE: {
-        if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
-		{
-            if (in->Samples.wValidBitsPerSample == 32)
-                return paFloat32;
-        }
-        else
-		if (IsEqualGUID(&in->SubFormat, &pa_KSDATAFORMAT_SUBTYPE_PCM))
-		{
-            switch (old->wBitsPerSample)
-			{
-                case 32: return paInt32;
-                case 24: return paInt24;
-                case  8: return paUInt8;
-                case 16: return paInt16;
-            }
-        }
-		break; }
-
-    case WAVE_FORMAT_IEEE_FLOAT:
-		return paFloat32;
-
-    case WAVE_FORMAT_PCM: {
-        switch (old->wBitsPerSample)
-		{
-            case 32: return paInt32;
-            case 24: return paInt24;
-            case  8: return paUInt8;
-            case 16: return paInt16;
-        }
-		break; }
-    }
-
-    return paCustomFormat;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError MakeWaveFormatFromParams(WAVEFORMATEXTENSIBLE *wavex, const PaStreamParameters *params,
-									double sampleRate)
-{
-	WORD bitsPerSample;
-	WAVEFORMATEX *old;
-	DWORD channelMask = 0;
-	PaWasapiStreamInfo *streamInfo = (PaWasapiStreamInfo *)params->hostApiSpecificStreamInfo;
-
-	// Get user assigned channel mask
-	if ((streamInfo != NULL) && (streamInfo->flags & paWinWasapiUseChannelMask))
-		channelMask = streamInfo->channelMask;
-
-	// Convert PaSampleFormat to bits per sample
-	if ((bitsPerSample = PaSampleFormatToBitsPerSample(params->sampleFormat)) == 0)
-		return paSampleFormatNotSupported;
-
-    memset(wavex, 0, sizeof(*wavex));
-
-    old					 = (WAVEFORMATEX *)wavex;
-    old->nChannels       = (WORD)params->channelCount;
-    old->nSamplesPerSec  = (DWORD)sampleRate;
-	if ((old->wBitsPerSample = bitsPerSample) > 16)
-	{
-		old->wBitsPerSample = 32; // 20 or 24 bits must go in 32 bit containers (ints)
-	}
-    old->nBlockAlign     = (old->nChannels * (old->wBitsPerSample/8));
-    old->nAvgBytesPerSec = (old->nSamplesPerSec * old->nBlockAlign);
-
-    //WAVEFORMATEX
-    /*if ((params->channelCount <= 2) && ((bitsPerSample == 16) || (bitsPerSample == 8)))
-	{
-        old->cbSize		= 0;
-        old->wFormatTag	= WAVE_FORMAT_PCM;
-    }
-    //WAVEFORMATEXTENSIBLE
-    else*/
-	{
-        old->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
-        old->cbSize		= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
-
-        if ((params->sampleFormat & ~paNonInterleaved) == paFloat32)
-            wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
-        else
-            wavex->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
-
-        wavex->Samples.wValidBitsPerSample = bitsPerSample; //no extra padding!
-
-		// Set channel mask
-		if (channelMask != 0)
-		{
-			wavex->dwChannelMask = channelMask;
-		}
-		else
-		{
-			switch (params->channelCount)
-			{
-			case 1:  wavex->dwChannelMask = KSAUDIO_SPEAKER_MONO; break;
-			case 2:  wavex->dwChannelMask = KSAUDIO_SPEAKER_STEREO; break;
-			case 4:  wavex->dwChannelMask = KSAUDIO_SPEAKER_QUAD; break;
-			case 6:  wavex->dwChannelMask = KSAUDIO_SPEAKER_5POINT1; break;
-			case 8:  wavex->dwChannelMask = KSAUDIO_SPEAKER_7POINT1; break;
-			default: wavex->dwChannelMask = 0; break;
-			}
-		}
-	}
-    return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-/*static void wasapiFillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount)
-{
-    PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat ));
-    PA_DEBUG(( "sampleRate = %f\n" , sampleRate ));
-    PA_DEBUG(( "chanelCount = %d\n", channelCount ));
-
-    pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
-    pwfext->Format.nChannels = (WORD)channelCount;
-    pwfext->Format.nSamplesPerSec = (DWORD)sampleRate;
-    if(channelCount == 1)
-        pwfext->dwChannelMask = KSAUDIO_SPEAKER_DIRECTOUT;
-    else
-        pwfext->dwChannelMask = KSAUDIO_SPEAKER_STEREO;
-    if(sampleFormat == paFloat32)
-    {
-        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
-        pwfext->Format.wBitsPerSample = 32;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 32;
-        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
-    }
-    else if(sampleFormat == paInt32)
-    {
-        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
-        pwfext->Format.wBitsPerSample = 32;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 32;
-        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
-    }
-    else if(sampleFormat == paInt24)
-    {
-        pwfext->Format.nBlockAlign = (WORD)(channelCount * 4);
-        pwfext->Format.wBitsPerSample = 32; // 24-bit in 32-bit int container
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 24;
-        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
-    }
-    else if(sampleFormat == paInt16)
-    {
-        pwfext->Format.nBlockAlign = (WORD)(channelCount * 2);
-        pwfext->Format.wBitsPerSample = 16;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 16;
-        pwfext->SubFormat = pa_KSDATAFORMAT_SUBTYPE_PCM;
-    }
-    pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign;
-}*/
-
-// ------------------------------------------------------------------------------------------
-static PaError GetClosestFormat(IAudioClient *myClient, double sampleRate,
-	const PaStreamParameters *_params, AUDCLNT_SHAREMODE shareMode, WAVEFORMATEXTENSIBLE *outWavex,
-	BOOL output)
-{
-	PaError answer                   = paInvalidSampleRate;
-	WAVEFORMATEX *sharedClosestMatch = NULL;
-	HRESULT hr                       = !S_OK;
-	PaStreamParameters params       = (*_params);
-
-	/* It was not noticed that 24-bit Input producing no output while device accepts this format.
-	   To fix this issue let's ask for 32-bits and let PA converters convert host 32-bit data
-	   to 24-bit for user-space. The bug concerns Vista, if Windows 7 supports 24-bits for Input
-	   please report to PortAudio developers to exclude Windows 7.
-	*/
-	if ((params.sampleFormat == paInt24) && (output == FALSE))
-		params.sampleFormat = paFloat32;
-
-    MakeWaveFormatFromParams(outWavex, &params, sampleRate);
-
-	hr = IAudioClient_IsFormatSupported(myClient, shareMode, &outWavex->Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
-	if (hr == S_OK)
-		answer = paFormatIsSupported;
-    else
-	if (sharedClosestMatch)
-	{
-		WORD bitsPerSample;
-        WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE*)sharedClosestMatch;
-
-		GUID subf_guid = GUID_NULL;
-		if (sharedClosestMatch->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
-		{
-			memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEXTENSIBLE));
-			subf_guid = ext->SubFormat;
-		}
-		else
-			memcpy(outWavex, sharedClosestMatch, sizeof(WAVEFORMATEX));
-
-        CoTaskMemFree(sharedClosestMatch);
-
-		// Make supported by default
-		answer = paFormatIsSupported;
-
-		// Validate SampleRate
-		if ((DWORD)sampleRate != outWavex->Format.nSamplesPerSec)
-			return paInvalidSampleRate;
-
-		// Validate Channel count
-		if ((WORD)params.channelCount != outWavex->Format.nChannels)
-		{
-			// If mono, then driver does not support 1 channel, we use internal workaround
-			// of tiny software mixing functionality, e.g. we provide to user buffer 1 channel
-			// but then mix into 2 for device buffer
-			if ((params.channelCount == 1) && (outWavex->Format.nChannels == 2))
-				return paFormatIsSupported;
-			else
-				return paInvalidChannelCount;
-		}
-
-		// Validate Sample format
-		if ((bitsPerSample = PaSampleFormatToBitsPerSample(params.sampleFormat)) == 0)
-			return paSampleFormatNotSupported;
-
-		// Validate Sample format: bit size (WASAPI does not limit 'bit size')
-		//if (bitsPerSample != outWavex->Format.wBitsPerSample)
-		//	return paSampleFormatNotSupported;
-
-		// Validate Sample format: paFloat32 (WASAPI does not limit 'bit type')
-		//if ((params->sampleFormat == paFloat32) && (subf_guid != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
-		//	return paSampleFormatNotSupported;
-
-		// Validate Sample format: paInt32 (WASAPI does not limit 'bit type')
-		//if ((params->sampleFormat == paInt32) && (subf_guid != KSDATAFORMAT_SUBTYPE_PCM))
-		//	return paSampleFormatNotSupported;
-	}
-	else
-	{
-		static const int BestToWorst[] = { paFloat32, paInt24, paInt16 };
-		int i;
-
-		// Try combination stereo and we will use built-in mono-stereo mixer then
-		if (params.channelCount == 1)
-		{
-			WAVEFORMATEXTENSIBLE stereo = { 0 };
-
-			PaStreamParameters stereo_params = params;
-			stereo_params.channelCount = 2;
-
-			MakeWaveFormatFromParams(&stereo, &stereo_params, sampleRate);
-
-			hr = IAudioClient_IsFormatSupported(myClient, shareMode, &stereo.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
-			if (hr == S_OK)
-			{
-				memcpy(outWavex, &stereo, sizeof(WAVEFORMATEXTENSIBLE));
-				CoTaskMemFree(sharedClosestMatch);
-				return (answer = paFormatIsSupported);
-			}
-
-			// Try selecting suitable sample type
-			for (i = 0; i < STATIC_ARRAY_SIZE(BestToWorst); ++i)
-			{
-				WAVEFORMATEXTENSIBLE sample = { 0 };
-
-				PaStreamParameters sample_params = stereo_params;
-				sample_params.sampleFormat = BestToWorst[i];
-
-				MakeWaveFormatFromParams(&sample, &sample_params, sampleRate);
-
-				hr = IAudioClient_IsFormatSupported(myClient, shareMode, &sample.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
-				if (hr == S_OK)
-				{
-					memcpy(outWavex, &sample, sizeof(WAVEFORMATEXTENSIBLE));
-					CoTaskMemFree(sharedClosestMatch);
-					return (answer = paFormatIsSupported);
-				}
-			}
-		}
-
-		// Try selecting suitable sample type
-		for (i = 0; i < STATIC_ARRAY_SIZE(BestToWorst); ++i)
-		{
-			WAVEFORMATEXTENSIBLE spfmt = { 0 };
-
-			PaStreamParameters spfmt_params = params;
-			spfmt_params.sampleFormat = BestToWorst[i];
-
-			MakeWaveFormatFromParams(&spfmt, &spfmt_params, sampleRate);
-
-			hr = IAudioClient_IsFormatSupported(myClient, shareMode, &spfmt.Format, (shareMode == AUDCLNT_SHAREMODE_SHARED ? &sharedClosestMatch : NULL));
-			if (hr == S_OK)
-			{
-				memcpy(outWavex, &spfmt, sizeof(WAVEFORMATEXTENSIBLE));
-				CoTaskMemFree(sharedClosestMatch);
-				answer = paFormatIsSupported;
-				break;
-			}
-		}
-
-		// Nothing helped
-		LogHostError(hr);
-	}
-
-	return answer;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError IsStreamParamsValid(struct PaUtilHostApiRepresentation *hostApi,
-                                   const  PaStreamParameters *inputParameters,
-                                   const  PaStreamParameters *outputParameters,
-                                   double sampleRate)
-{
-	if (hostApi == NULL)
-		return paHostApiNotFound;
-	if ((UINT32)sampleRate == 0)
-		return paInvalidSampleRate;
-
-	if (inputParameters != NULL)
-    {
-        /* all standard sample formats are supported by the buffer adapter,
-            this implementation doesn't support any custom sample formats */
-		if (inputParameters->sampleFormat & paCustomFormat)
-            return paSampleFormatNotSupported;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-        if (inputParameters->device == paUseHostApiSpecificDeviceSpecification)
-            return paInvalidDevice;
-
-        /* check that input device can support inputChannelCount */
-        if (inputParameters->channelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels)
-            return paInvalidChannelCount;
-
-        /* validate inputStreamInfo */
-        if (inputParameters->hostApiSpecificStreamInfo)
-		{
-			PaWasapiStreamInfo *inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
-	        if ((inputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
-	            (inputStreamInfo->version != 1) ||
-                (inputStreamInfo->hostApiType != paWASAPI))
-	        {
-	            return paIncompatibleHostApiSpecificStreamInfo;
-	        }
-		}
-
-        return paNoError;
-    }
-
-    if (outputParameters != NULL)
-    {
-        /* all standard sample formats are supported by the buffer adapter,
-            this implementation doesn't support any custom sample formats */
-        if (outputParameters->sampleFormat & paCustomFormat)
-            return paSampleFormatNotSupported;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-        if (outputParameters->device == paUseHostApiSpecificDeviceSpecification)
-            return paInvalidDevice;
-
-        /* check that output device can support outputChannelCount */
-        if (outputParameters->channelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels)
-            return paInvalidChannelCount;
-
-        /* validate outputStreamInfo */
-        if(outputParameters->hostApiSpecificStreamInfo)
-        {
-			PaWasapiStreamInfo *outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
-	        if ((outputStreamInfo->size != sizeof(PaWasapiStreamInfo)) ||
-	            (outputStreamInfo->version != 1) ||
-                (outputStreamInfo->hostApiType != paWASAPI))
-	        {
-	            return paIncompatibleHostApiSpecificStreamInfo;
-	        }
-        }
-
-		return paNoError;
-    }
-
-	return (inputParameters || outputParameters ? paNoError : paInternalError);
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
-                                  const  PaStreamParameters *inputParameters,
-                                  const  PaStreamParameters *outputParameters,
-                                  double sampleRate )
-{
-	IAudioClient *tmpClient = NULL;
-	PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
-	PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
-
-	// Validate PaStreamParameters
-	PaError error;
-	if ((error = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
-		return error;
-
-    if (inputParameters != NULL)
-    {
-		WAVEFORMATEXTENSIBLE wavex;
-		HRESULT hr;
-		PaError answer;
-		AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
-		inputStreamInfo = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
-
-		if (inputStreamInfo && (inputStreamInfo->flags & paWinWasapiExclusive))
-			shareMode  = AUDCLNT_SHAREMODE_EXCLUSIVE;
-
-		hr = IMMDevice_Activate(paWasapi->devInfo[inputParameters->device].device,
-			&pa_IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, (void **)&tmpClient);
-		if (hr != S_OK)
-		{
-			LogHostError(hr);
-			return paInvalidDevice;
-		}
-
-		answer = GetClosestFormat(tmpClient, sampleRate, inputParameters, shareMode, &wavex, FALSE);
-		SAFE_RELEASE(tmpClient);
-
-		if (answer != paFormatIsSupported)
-			return answer;
-    }
-
-    if (outputParameters != NULL)
-    {
-		HRESULT hr;
-		WAVEFORMATEXTENSIBLE wavex;
-		PaError answer;
-		AUDCLNT_SHAREMODE shareMode = AUDCLNT_SHAREMODE_SHARED;
-        outputStreamInfo = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
-
-		if (outputStreamInfo && (outputStreamInfo->flags & paWinWasapiExclusive))
-			shareMode  = AUDCLNT_SHAREMODE_EXCLUSIVE;
-
-		hr = IMMDevice_Activate(paWasapi->devInfo[outputParameters->device].device,
-			&pa_IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, (void **)&tmpClient);
-		if (hr != S_OK)
-		{
-			LogHostError(hr);
-			return paInvalidDevice;
-		}
-
-		answer = GetClosestFormat(tmpClient, sampleRate, outputParameters, shareMode, &wavex, TRUE);
-		SAFE_RELEASE(tmpClient);
-
-		if (answer != paFormatIsSupported)
-			return answer;
-    }
-
-    return paFormatIsSupported;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaUint32 PaUtil_GetFramesPerHostBuffer(PaUint32 userFramesPerBuffer, PaTime suggestedLatency, double sampleRate, PaUint32 TimerJitterMs)
-{
-	PaUint32 frames = userFramesPerBuffer + max( userFramesPerBuffer, (PaUint32)(suggestedLatency * sampleRate) );
-    frames += (PaUint32)((sampleRate * 0.001) * TimerJitterMs);
-	return frames;
-}
-
-// ------------------------------------------------------------------------------------------
-static void _RecalculateBuffersCount(PaWasapiSubStream *sub, UINT32 userFramesPerBuffer, UINT32 framesPerLatency, BOOL fullDuplex)
-{
-	// Count buffers (must be at least 1)
-	sub->buffers = (userFramesPerBuffer ? framesPerLatency / userFramesPerBuffer : 0);
-	if (sub->buffers == 0)
-		sub->buffers = 1;
-
-	// Determine amount of buffers used:
-	// - Full-duplex mode will lead to period difference, thus only 1.
-	// - Input mode, only 1, as WASAPI allows extraction of only 1 packet.
-	// - For Shared mode we use double buffering.
-	if ((sub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) || fullDuplex)
-	{
-		// Exclusive mode does not allow >1 buffers be used for Event interface, e.g. GetBuffer
-		// call must acquire max buffer size and it all must be processed.
-		if (sub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)
-			sub->userBufferAndHostMatch = 1;
-
-		// Use paUtilBoundedHostBufferSize because exclusive mode will starve and produce
-		// bad quality of audio
-		sub->buffers = 1;
-	}
-}
-
-// ------------------------------------------------------------------------------------------
-static void _CalculateAlignedPeriod(PaWasapiSubStream *pSub, UINT32 *nFramesPerLatency,
-									ALIGN_FUNC pAlignFunc)
-{
-	// Align frames to HD Audio packet size of 128 bytes for Exclusive mode only.
-	// Not aligning on Windows Vista will cause Event timeout, although Windows 7 will
-	// return AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED error to realign buffer. Aligning is necessary
-	// for Exclusive mode only! when audio data is feeded directly to hardware.
-	if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
-	{
-		(*nFramesPerLatency) = AlignFramesPerBuffer((*nFramesPerLatency),
-			pSub->wavex.Format.nSamplesPerSec, pSub->wavex.Format.nBlockAlign, pAlignFunc);
-	}
-
-	// Calculate period
-	pSub->period = MakeHnsPeriod((*nFramesPerLatency), pSub->wavex.Format.nSamplesPerSec);
-}
-
-// ------------------------------------------------------------------------------------------
-static HRESULT CreateAudioClient(PaWasapiStream *pStream, PaWasapiSubStream *pSub,
-	PaWasapiDeviceInfo *pInfo, const PaStreamParameters *params, UINT32 framesPerLatency,
-	double sampleRate, BOOL blocking, BOOL output, BOOL fullDuplex, PaError *pa_error)
-{
-	PaError error;
-    HRESULT hr;
-	const UINT32 userFramesPerBuffer = framesPerLatency;
-    IAudioClient *audioClient	     = NULL;
-
-	// Validate parameters
-    if (!pSub || !pInfo || !params)
-        return E_POINTER;
-	if ((UINT32)sampleRate == 0)
-        return E_INVALIDARG;
-
-    // Get the audio client
-    hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&audioClient);
-	if (hr != S_OK)
-	{
-		LogHostError(hr);
-		goto done;
-	}
-
-	// Get closest format
-	if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
-	{
-		if (pa_error)
-			(*pa_error) = error;
-
-		LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
-		goto done; // fail, format not supported
-	}
-
-	// Check for Mono <<>> Stereo workaround
-	if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
-	{
-		if (blocking)
-		{
-			LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
-			goto done; // fail, blocking mode not supported
-		}
-
-		// select mixer
-		pSub->monoMixer = _GetMonoToStereoMixer(WaveToPaFormat(&pSub->wavex), (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1));
-		if (pSub->monoMixer == NULL)
-		{
-			LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
-			goto done; // fail, no mixer for format
-		}
-	}
-
-#if 0
-	// Add suggestd latency
-	framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
-#else
-	// Calculate host buffer size
-	if ((pSub->shareMode != AUDCLNT_SHAREMODE_EXCLUSIVE) &&
-		(!pSub->streamFlags || ((pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
-	{
-		framesPerLatency = PaUtil_GetFramesPerHostBuffer(userFramesPerBuffer,
-			params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
-			(pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
-	}
-	else
-	{
-		REFERENCE_TIME overall;
-
-		// Work 1:1 with user buffer (only polling allows to use >1)
-		framesPerLatency += MakeFramesFromHns(SecondsTonano100(params->suggestedLatency), pSub->wavex.Format.nSamplesPerSec);
-
-		// Use Polling if overall latency is > 5ms as it allows to use 100% CPU in a callback,
-		// or user specified latency parameter
-		overall = MakeHnsPeriod(framesPerLatency, pSub->wavex.Format.nSamplesPerSec);
-		if ((overall >= (106667*2)/*21.33ms*/) || ((INT32)(params->suggestedLatency*100000.0) != 0/*0.01 msec granularity*/))
-		{
-			framesPerLatency = PaUtil_GetFramesPerHostBuffer(userFramesPerBuffer,
-				params->suggestedLatency, pSub->wavex.Format.nSamplesPerSec, 0/*,
-				(streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? 0 : 1)*/);
-
-			// Use Polling interface
-			pSub->streamFlags &= ~AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
-			PRINT(("WASAPI: CreateAudioClient: forcing POLL mode\n"));
-		}
-	}
-#endif
-
-	// For full-duplex output resize buffer to be the same as for input
-	if (output && fullDuplex)
-		framesPerLatency = pStream->in.framesPerHostCallback;
-
-	// Avoid 0 frames
-	if (framesPerLatency == 0)
-		framesPerLatency = MakeFramesFromHns(pInfo->DefaultDevicePeriod, pSub->wavex.Format.nSamplesPerSec);
-
-	// Calculate aligned period
-	_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
-
-	/*! Enforce min/max period for device in Shared mode to avoid bad audio quality.
-        Avoid doing so for Exclusive mode as alignment will suffer.
-	*/
-	if (pSub->shareMode == AUDCLNT_SHAREMODE_SHARED)
-	{
-		if (pSub->period < pInfo->DefaultDevicePeriod)
-		{
-			pSub->period = pInfo->DefaultDevicePeriod;
-			// Recalculate aligned period
-			framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
-			_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
-		}
-	}
-	else
-	{
-		if (pSub->period < pInfo->MinimumDevicePeriod)
-		{
-			pSub->period = pInfo->MinimumDevicePeriod;
-			// Recalculate aligned period
-			framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
-			_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
-		}
-	}
-
-	/*! Windows 7 does not allow to set latency lower than minimal device period and will
-	    return error: AUDCLNT_E_INVALID_DEVICE_PERIOD. Under Vista we enforce the same behavior
-	    manually for unified behavior on all platforms.
-	*/
-	{
-		/*!	AUDCLNT_E_BUFFER_SIZE_ERROR: Applies to Windows 7 and later.
-			Indicates that the buffer duration value requested by an exclusive-mode client is
-			out of range. The requested duration value for pull mode must not be greater than
-			500 milliseconds; for push mode the duration value must not be greater than 2 seconds.
-		*/
-		if (pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
-		{
-			static const REFERENCE_TIME MAX_BUFFER_EVENT_DURATION = 500  * 10000;
-			static const REFERENCE_TIME MAX_BUFFER_POLL_DURATION  = 2000 * 10000;
-
-			if (pSub->streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)	// pull mode, max 500ms
-			{
-				if (pSub->period > MAX_BUFFER_EVENT_DURATION)
-				{
-					pSub->period = MAX_BUFFER_EVENT_DURATION;
-					// Recalculate aligned period
-					framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
-					_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
-				}
-			}
-			else														// push mode, max 2000ms
-			{
-				if (pSub->period > MAX_BUFFER_POLL_DURATION)
-				{
-					pSub->period = MAX_BUFFER_POLL_DURATION;
-					// Recalculate aligned period
-					framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
-					_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
-				}
-			}
-		}
-	}
-
-	// Open the stream and associate it with an audio session
-    hr = IAudioClient_Initialize(audioClient,
-        pSub->shareMode,
-        pSub->streamFlags,
-		pSub->period,
-		(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
-		&pSub->wavex.Format,
-        NULL);
-
-	/*! WASAPI is tricky on large device buffer, sometimes 2000ms can be allocated sometimes
-	    less. There is no known guaranteed level thus we make subsequent tries by decreasing
-		buffer by 100ms per try.
-	*/
-	while ((hr == E_OUTOFMEMORY) && (pSub->period > (100 * 10000)))
-	{
-		PRINT(("WASAPI: CreateAudioClient: decreasing buffer size to %d milliseconds\n", (pSub->period / 10000)));
-
-		// Decrease by 100ms and try again
-		pSub->period -= (100 * 10000);
-
-		// Recalculate aligned period
-		framesPerLatency = MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec);
-		_CalculateAlignedPeriod(pSub, &framesPerLatency, ALIGN_BWD);
-
-        // Release the previous allocations
-        SAFE_RELEASE(audioClient);
-
-        // Create a new audio client
-        hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&audioClient);
-    	if (hr != S_OK)
-		{
-			LogHostError(hr);
-			goto done;
-		}
-
-		// Open the stream and associate it with an audio session
-		hr = IAudioClient_Initialize(audioClient,
-			pSub->shareMode,
-			pSub->streamFlags,
-			pSub->period,
-			(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
-			&pSub->wavex.Format,
-			NULL);
-	}
-
-	/*! WASAPI buffer size failure. Fallback to using default size.
-	*/
-	if (hr == AUDCLNT_E_BUFFER_SIZE_ERROR)
-	{
-		// Use default
-		pSub->period = pInfo->DefaultDevicePeriod;
-
-		PRINT(("WASAPI: CreateAudioClient: correcting buffer size to device default\n"));
-
-        // Release the previous allocations
-        SAFE_RELEASE(audioClient);
-
-        // Create a new audio client
-        hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&audioClient);
-    	if (hr != S_OK)
-		{
-			LogHostError(hr);
-			goto done;
-		}
-
-		// Open the stream and associate it with an audio session
-		hr = IAudioClient_Initialize(audioClient,
-			pSub->shareMode,
-			pSub->streamFlags,
-			pSub->period,
-			(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
-			&pSub->wavex.Format,
-			NULL);
-	}
-
-    /*! If the requested buffer size is not aligned. Can be triggered by Windows 7 and up.
-	    Should not be be triggered ever as we do align buffers always with _CalculateAlignedPeriod.
-	*/
-    if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
-    {
-		UINT32 frames = 0;
-
-        // Get the next aligned frame
-        hr = IAudioClient_GetBufferSize(audioClient, &frames);
-		if (hr != S_OK)
-		{
-			LogHostError(hr);
-			goto done;
-		}
-
-		PRINT(("WASAPI: CreateAudioClient: aligning buffer size to % frames\n", frames));
-
-        // Release the previous allocations
-        SAFE_RELEASE(audioClient);
-
-        // Create a new audio client
-        hr = IMMDevice_Activate(pInfo->device, &pa_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&audioClient);
-    	if (hr != S_OK)
-		{
-			LogHostError(hr);
-			goto done;
-		}
-
-		// Get closest format
-		if ((error = GetClosestFormat(audioClient, sampleRate, params, pSub->shareMode, &pSub->wavex, output)) != paFormatIsSupported)
-		{
-			if (pa_error)
-				(*pa_error) = error;
-
-			LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT); // fail, format not supported
-			goto done;
-		}
-
-		// Check for Mono >> Stereo workaround
-		if ((params->channelCount == 1) && (pSub->wavex.Format.nChannels == 2))
-		{
-			if (blocking)
-			{
-				LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
-				goto done; // fail, blocking mode not supported
-			}
-
-			// Select mixer
-			pSub->monoMixer = _GetMonoToStereoMixer(WaveToPaFormat(&pSub->wavex), (pInfo->flow == eRender ? MIX_DIR__1TO2 : MIX_DIR__2TO1));
-			if (pSub->monoMixer == NULL)
-			{
-				LogHostError(hr = AUDCLNT_E_UNSUPPORTED_FORMAT);
-				goto done; // fail, no mixer for format
-			}
-		}
-
-		// Calculate period
-		pSub->period = MakeHnsPeriod(frames, pSub->wavex.Format.nSamplesPerSec);
-
-        // Open the stream and associate it with an audio session
-        hr = IAudioClient_Initialize(audioClient,
-            pSub->shareMode,
-            pSub->streamFlags,
-			pSub->period,
-			(pSub->shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? pSub->period : 0),
-            &pSub->wavex.Format,
-            NULL);
-    	if (hr != S_OK)
-		{
-			LogHostError(hr);
-			goto done;
-		}
-    }
-    else
-	if (hr != S_OK)
-    {
-		LogHostError(hr);
-		goto done;
-    }
-
-    // Set client
-	pSub->client = audioClient;
-    IAudioClient_AddRef(pSub->client);
-
-	// Recalculate buffers count
-	_RecalculateBuffersCount(pSub,
-		userFramesPerBuffer,
-		MakeFramesFromHns(pSub->period, pSub->wavex.Format.nSamplesPerSec),
-		fullDuplex);
-
-done:
-
-    // Clean up
-    SAFE_RELEASE(audioClient);
-    return hr;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
-                           PaStream** s,
-                           const PaStreamParameters *inputParameters,
-                           const PaStreamParameters *outputParameters,
-                           double sampleRate,
-                           unsigned long framesPerBuffer,
-                           PaStreamFlags streamFlags,
-                           PaStreamCallback *streamCallback,
-                           void *userData )
-{
-    PaError result = paNoError;
-	HRESULT hr;
-    PaWasapiHostApiRepresentation *paWasapi = (PaWasapiHostApiRepresentation*)hostApi;
-    PaWasapiStream *stream = NULL;
-    int inputChannelCount, outputChannelCount;
-    PaSampleFormat inputSampleFormat, outputSampleFormat;
-    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
-	PaWasapiStreamInfo *inputStreamInfo = NULL, *outputStreamInfo = NULL;
-	PaWasapiDeviceInfo *info = NULL;
-	UINT32 maxBufferSize;
-	PaTime buffer_latency;
-	ULONG framesPerHostCallback;
-	PaUtilHostBufferSizeMode bufferMode;
-	const BOOL fullDuplex = ((inputParameters != NULL) && (outputParameters != NULL));
-
-	// validate PaStreamParameters
-	if ((result = IsStreamParamsValid(hostApi, inputParameters, outputParameters, sampleRate)) != paNoError)
-		return LogPaError(result);
-
-    // Validate platform specific flags
-    if ((streamFlags & paPlatformSpecificFlags) != 0)
-	{
-		LogPaError(result = paInvalidFlag); /* unexpected platform specific flag */
-		goto error;
-	}
-
-	// Allocate memory for PaWasapiStream
-    if ((stream = (PaWasapiStream *)PaUtil_AllocateMemory(sizeof(PaWasapiStream))) == NULL)
-	{
-        LogPaError(result = paInsufficientMemory);
-        goto error;
-    }
-
-	// Default thread priority is Audio: for exclusive mode we will use Pro Audio.
-	stream->nThreadPriority = eThreadPriorityAudio;
-
-	// Set default number of frames: paFramesPerBufferUnspecified
-	if (framesPerBuffer == paFramesPerBufferUnspecified)
-	{
-		UINT32 framesPerBufferIn  = 0, framesPerBufferOut = 0;
-		if (inputParameters != NULL)
-		{
-			info = &paWasapi->devInfo[inputParameters->device];
-			framesPerBufferIn = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
-		}
-		if (outputParameters != NULL)
-		{
-			info = &paWasapi->devInfo[outputParameters->device];
-			framesPerBufferOut = MakeFramesFromHns(info->DefaultDevicePeriod, (UINT32)sampleRate);
-		}
-		// choosing maximum default size
-		framesPerBuffer = max(framesPerBufferIn, framesPerBufferOut);
-	}
-	if (framesPerBuffer == 0)
-		framesPerBuffer = ((UINT32)sampleRate / 100) * 2;
-
-	// Try create device: Input
-	if (inputParameters != NULL)
-    {
-        inputChannelCount = inputParameters->channelCount;
-        inputSampleFormat = inputParameters->sampleFormat;
-		inputStreamInfo   = (PaWasapiStreamInfo *)inputParameters->hostApiSpecificStreamInfo;
-        info              = &paWasapi->devInfo[inputParameters->device];
-		stream->in.flags  = (inputStreamInfo ? inputStreamInfo->flags : 0);
-
-		// Select Exclusive/Shared mode
-		stream->in.shareMode = AUDCLNT_SHAREMODE_SHARED;
-        if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiExclusive))
-		{
-			// Boost thread priority
-			stream->nThreadPriority = eThreadPriorityProAudio;
-			// Make Exclusive
-			stream->in.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
-		}
-
-		// If user provided explicit thread priority level, use it
-        if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiThreadPriority))
-		{
-			if ((inputStreamInfo->threadPriority > eThreadPriorityNone) &&
-				(inputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
-				stream->nThreadPriority = inputStreamInfo->threadPriority;
-		}
-
-		// Choose processing mode
-		stream->in.streamFlags = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
-		if (paWasapi->useWOW64Workaround)
-			stream->in.streamFlags = 0; // polling interface
-		else
-		if (streamCallback == NULL)
-			stream->in.streamFlags = 0; // polling interface
-		else
-		if ((inputStreamInfo != NULL) && (inputStreamInfo->flags & paWinWasapiPolling))
-			stream->in.streamFlags = 0; // polling interface
-		else
-		if (fullDuplex)
-			stream->in.streamFlags = 0; // polling interface is implemented for full-duplex mode also
-
-		// Create Audio client
-		hr = CreateAudioClient(stream, &stream->in, info, inputParameters, framesPerBuffer/*framesPerLatency*/,
-			sampleRate, (streamCallback == NULL), FALSE, fullDuplex, &result);
-        if (hr != S_OK)
-		{
-			LogPaError(result = paInvalidDevice);
-			goto error;
-        }
-		LogWAVEFORMATEXTENSIBLE(&stream->in.wavex);
-
-		// Get closest format
-        hostInputSampleFormat = PaUtil_SelectClosestAvailableFormat( WaveToPaFormat(&stream->in.wavex), inputSampleFormat );
-
-		// Create volume mgr
-		stream->inVol = NULL;
-        /*hr = info->device->Activate(
-            __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
-            (void**)&stream->inVol);
-        if (hr != S_OK)
-            return paInvalidDevice;*/
-
-        // Set user-side custom host processor
-        if ((inputStreamInfo != NULL) &&
-            (inputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
-        {
-            stream->hostProcessOverrideInput.processor = inputStreamInfo->hostProcessorInput;
-            stream->hostProcessOverrideInput.userData = userData;
-        }
-
-        // Get max possible buffer size to check if it is not less than that we request
-        hr = IAudioClient_GetBufferSize(stream->in.client, &maxBufferSize);
-        if (hr != S_OK)
-		{
-			LogHostError(hr);
- 			LogPaError(result = paInvalidDevice);
-			goto error;
-		}
-
-        // Correct buffer to max size if it maxed out result of GetBufferSize
-		stream->in.bufferSize = maxBufferSize;
-
-		// Get interface latency (actually uneeded as we calculate latency from the size
-		// of maxBufferSize).
-        hr = IAudioClient_GetStreamLatency(stream->in.client, &stream->in.device_latency);
-        if (hr != S_OK)
-		{
-			LogHostError(hr);
- 			LogPaError(result = paInvalidDevice);
-			goto error;
-		}
-		//stream->in.latency_seconds = nano100ToSeconds(stream->in.device_latency);
-
-        // Number of frames that are required at each period
-		stream->in.framesPerHostCallback = maxBufferSize;
-
-		// Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
-		stream->in.framesPerBuffer =
-			(stream->in.userBufferAndHostMatch ? stream->in.framesPerHostCallback : framesPerBuffer);
-
-		// Calculate buffer latency
-		buffer_latency = (PaTime)maxBufferSize / stream->in.wavex.Format.nSamplesPerSec;
-
-		// Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
-		stream->in.latency_seconds += buffer_latency;
-
-		PRINT(("WASAPI::OpenStream(input): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->in.framesPerHostCallback, (float)(stream->in.latency_seconds*1000.0f), (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (paWasapi->useWOW64Workaround ? "YES" : "NO"), (stream->in.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
-	}
-    else
-    {
-        inputChannelCount = 0;
-        inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */
-    }
-
-	// Try create device: Output
-    if (outputParameters != NULL)
-    {
-        outputChannelCount = outputParameters->channelCount;
-        outputSampleFormat = outputParameters->sampleFormat;
-		outputStreamInfo   = (PaWasapiStreamInfo *)outputParameters->hostApiSpecificStreamInfo;
-		info               = &paWasapi->devInfo[outputParameters->device];
-		stream->out.flags  = (outputStreamInfo ? outputStreamInfo->flags : 0);
-
-		// Select Exclusive/Shared mode
-		stream->out.shareMode = AUDCLNT_SHAREMODE_SHARED;
-        if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiExclusive))
-		{
-			// Boost thread priority
-			stream->nThreadPriority = eThreadPriorityProAudio;
-			// Make Exclusive
-			stream->out.shareMode = AUDCLNT_SHAREMODE_EXCLUSIVE;
-		}
-
-		// If user provided explicit thread priority level, use it
-        if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiThreadPriority))
-		{
-			if ((outputStreamInfo->threadPriority > eThreadPriorityNone) &&
-				(outputStreamInfo->threadPriority <= eThreadPriorityWindowManager))
-				stream->nThreadPriority = outputStreamInfo->threadPriority;
-		}
-
-		// Choose processing mode
-		stream->out.streamFlags = (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? AUDCLNT_STREAMFLAGS_EVENTCALLBACK : 0);
-		if (paWasapi->useWOW64Workaround)
-			stream->out.streamFlags = 0; // polling interface
-		else
-		if (streamCallback == NULL)
-			stream->out.streamFlags = 0; // polling interface
-		else
-		if ((outputStreamInfo != NULL) && (outputStreamInfo->flags & paWinWasapiPolling))
-			stream->out.streamFlags = 0; // polling interface
-		else
-		if (fullDuplex)
-			stream->out.streamFlags = 0; // polling interface is implemented for full-duplex mode also
-
-		// Create Audio client
-		hr = CreateAudioClient(stream, &stream->out, info, outputParameters, framesPerBuffer/*framesPerLatency*/,
-			sampleRate, (streamCallback == NULL), TRUE, fullDuplex, &result);
-        if (hr != S_OK)
-		{
-			LogPaError(result = paInvalidDevice);
-			goto error;
-        }
-		LogWAVEFORMATEXTENSIBLE(&stream->out.wavex);
-
-        // Get closest format
-        hostOutputSampleFormat = PaUtil_SelectClosestAvailableFormat( WaveToPaFormat(&stream->out.wavex), outputSampleFormat );
-
-		// Activate volume
-		stream->outVol = NULL;
-        /*hr = info->device->Activate(
-            __uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL,
-            (void**)&stream->outVol);
-        if (hr != S_OK)
-            return paInvalidDevice;*/
-
-       // Set user-side custom host processor
-        if ((outputStreamInfo != NULL) &&
-            (outputStreamInfo->flags & paWinWasapiRedirectHostProcessor))
-        {
-            stream->hostProcessOverrideOutput.processor = outputStreamInfo->hostProcessorOutput;
-            stream->hostProcessOverrideOutput.userData = userData;
-        }
-
-        // Get max possible buffer size to check if it is not less than that we request
-        hr = IAudioClient_GetBufferSize(stream->out.client, &maxBufferSize);
-        if (hr != S_OK)
-		{
-			LogHostError(hr);
- 			LogPaError(result = paInvalidDevice);
-			goto error;
-		}
-
-        // Correct buffer to max size if it maxed out result of GetBufferSize
-		stream->out.bufferSize = maxBufferSize;
-
-		// Get interface latency (actually uneeded as we calculate latency from the size
-		// of maxBufferSize).
-        hr = IAudioClient_GetStreamLatency(stream->out.client, &stream->out.device_latency);
-        if (hr != S_OK)
-		{
-			LogHostError(hr);
- 			LogPaError(result = paInvalidDevice);
-			goto error;
-		}
-		//stream->out.latency_seconds = nano100ToSeconds(stream->out.device_latency);
-
-        // Number of frames that are required at each period
-		stream->out.framesPerHostCallback = maxBufferSize;
-
-		// Calculate frames per single buffer, if buffers > 1 then always framesPerBuffer
-		stream->out.framesPerBuffer =
-			(stream->out.userBufferAndHostMatch ? stream->out.framesPerHostCallback : framesPerBuffer);
-
-		// Calculate buffer latency
-		buffer_latency = (PaTime)maxBufferSize / stream->out.wavex.Format.nSamplesPerSec;
-
-		// Append buffer latency to interface latency in shared mode (see GetStreamLatency notes)
-		stream->out.latency_seconds += buffer_latency;
-
-		PRINT(("WASAPI::OpenStream(output): framesPerUser[ %d ] framesPerHost[ %d ] latency[ %.02fms ] exclusive[ %s ] wow64_fix[ %s ] mode[ %s ]\n", (UINT32)framesPerBuffer, (UINT32)stream->out.framesPerHostCallback, (float)(stream->out.latency_seconds*1000.0f), (stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE ? "YES" : "NO"), (paWasapi->useWOW64Workaround ? "YES" : "NO"), (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK ? "EVENT" : "POLL")));
-	}
-    else
-    {
-        outputChannelCount = 0;
-        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */
-    }
-
-	// log full-duplex
-	if (fullDuplex)
-		PRINT(("WASAPI::OpenStream: full-duplex mode\n"));
-
-	// paWinWasapiPolling must be on/or not on both streams
-	if ((inputParameters != NULL) && (outputParameters != NULL))
-	{
-		if ((inputStreamInfo != NULL) && (outputStreamInfo != NULL))
-		{
-			if (((inputStreamInfo->flags & paWinWasapiPolling) &&
-				!(outputStreamInfo->flags & paWinWasapiPolling))
-				||
-				(!(inputStreamInfo->flags & paWinWasapiPolling) &&
-				 (outputStreamInfo->flags & paWinWasapiPolling)))
-			{
-				LogPaError(result = paInvalidFlag);
-				goto error;
-			}
-		}
-	}
-
-	// Initialize stream representation
-    if (streamCallback)
-    {
-		stream->bBlocking = FALSE;
-        PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
-                                              &paWasapi->callbackStreamInterface,
-											  streamCallback, userData);
-    }
-    else
-    {
-		stream->bBlocking = TRUE;
-        PaUtil_InitializeStreamRepresentation(&stream->streamRepresentation,
-                                              &paWasapi->blockingStreamInterface,
-											  streamCallback, userData);
-    }
-
-	// Initialize CPU measurer
-    PaUtil_InitializeCpuLoadMeasurer(&stream->cpuLoadMeasurer, sampleRate);
-
-	if (outputParameters && inputParameters)
-	{
-		// serious problem #1 - No, Not a problem, especially concerning Exclusive mode.
-		// Input device in exclusive mode somehow is getting large buffer always, thus we
-		// adjust Output latency to reflect it, thus period will differ but playback will be
-		// normal.
-		/*if (stream->in.period != stream->out.period)
-		{
-			PRINT(("WASAPI: OpenStream: period discrepancy\n"));
-			LogPaError(result = paBadIODeviceCombination);
-			goto error;
-		}*/
-
-		// serious problem #2 - No, Not a problem, as framesPerHostCallback take into account
-		// sample size while it is not a problem for PA full-duplex, we must care of
-		// preriod only!
-		/*if (stream->out.framesPerHostCallback != stream->in.framesPerHostCallback)
-		{
-			PRINT(("WASAPI: OpenStream: framesPerHostCallback discrepancy\n"));
-			goto error;
-		}*/
-	}
-
-	// Calculate frames per host for processor
-	framesPerHostCallback = (outputParameters ? stream->out.framesPerBuffer : stream->in.framesPerBuffer);
-
-	// Choose correct mode of buffer processing:
-	// Exclusive/Shared non paWinWasapiPolling mode: paUtilFixedHostBufferSize - always fixed
-	// Exclusive/Shared paWinWasapiPolling mode: paUtilBoundedHostBufferSize - may vary for Exclusive or Full-duplex
-	bufferMode = paUtilFixedHostBufferSize;
-	if (inputParameters) // !!! WASAPI IAudioCaptureClient::GetBuffer extracts not number of frames but 1 packet, thus we always must adapt
-		bufferMode = paUtilBoundedHostBufferSize;
-	else
-	if (outputParameters)
-	{
-		if ((stream->out.buffers == 1) &&
-			(!stream->out.streamFlags || ((stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK) == 0)))
-			bufferMode = paUtilBoundedHostBufferSize;
-	}
-	stream->bufferMode = bufferMode;
-
-    // Initialize buffer processor
-    result =  PaUtil_InitializeBufferProcessor(
-		&stream->bufferProcessor,
-        inputChannelCount,
-		inputSampleFormat,
-		hostInputSampleFormat,
-        outputChannelCount,
-		outputSampleFormat,
-		hostOutputSampleFormat,
-        sampleRate,
-		streamFlags,
-		framesPerBuffer,
-        framesPerHostCallback,
-		bufferMode,
-        streamCallback,
-		userData);
-    if (result != paNoError)
-	{
-		LogPaError(result);
-        goto error;
-	}
-
-	// Set Input latency
-    stream->streamRepresentation.streamInfo.inputLatency =
-            ((double)PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor) / sampleRate)
-			+ ((inputParameters)?stream->in.latency_seconds : 0);
-
-	// Set Output latency
-    stream->streamRepresentation.streamInfo.outputLatency =
-            ((double)PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor) / sampleRate)
-			+ ((outputParameters)?stream->out.latency_seconds : 0);
-
-	// Set SR
-    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
-
-    (*s) = (PaStream *)stream;
-    return result;
-
-error:
-
-    if (stream != NULL)
-		CloseStream(stream);
-
-    return result;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError CloseStream( PaStream* s )
-{
-    PaError result = paNoError;
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-
-	// abort active stream
-	if (IsStreamActive(s))
-	{
-		if ((result = AbortStream(s)) != paNoError)
-			return result;
-	}
-
-    SAFE_RELEASE(stream->cclient);
-    SAFE_RELEASE(stream->rclient);
-    SAFE_RELEASE(stream->out.client);
-    SAFE_RELEASE(stream->in.client);
-	SAFE_RELEASE(stream->inVol);
-	SAFE_RELEASE(stream->outVol);
-
-	CloseHandle(stream->event[S_INPUT]);
-	CloseHandle(stream->event[S_OUTPUT]);
-
-    SAFE_CLOSE(stream->hThread);
-	SAFE_CLOSE(stream->hThreadStart);
-	SAFE_CLOSE(stream->hThreadExit);
-	SAFE_CLOSE(stream->hCloseRequest);
-	SAFE_CLOSE(stream->hBlockingOpStreamRD);
-	SAFE_CLOSE(stream->hBlockingOpStreamWR);
-
-	free(stream->in.monoBuffer);
-	free(stream->out.monoBuffer);
-
-    PaUtil_TerminateBufferProcessor(&stream->bufferProcessor);
-    PaUtil_TerminateStreamRepresentation(&stream->streamRepresentation);
-    PaUtil_FreeMemory(stream);
-
-    return result;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError StartStream( PaStream *s )
-{
-	HRESULT hr;
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-
-	// check if stream is active already
-	if (IsStreamActive(s))
-		return paStreamIsNotStopped;
-
-    PaUtil_ResetBufferProcessor(&stream->bufferProcessor);
-
-	// Create close event
-	stream->hCloseRequest = CreateEvent(NULL, TRUE, FALSE, NULL);
-
-	// Create thread
-	if (!stream->bBlocking)
-	{
-		// Create thread events
-		stream->hThreadStart = CreateEvent(NULL, TRUE, FALSE, NULL);
-		stream->hThreadExit  = CreateEvent(NULL, TRUE, FALSE, NULL);
-
-		if ((stream->in.client && (stream->in.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)) ||
-			(stream->out.client && (stream->out.streamFlags & AUDCLNT_STREAMFLAGS_EVENTCALLBACK)))
-		{
-			if ((stream->hThread = CREATE_THREAD(ProcThreadEvent)) == NULL)
-			   return paUnanticipatedHostError;
-		}
-		else
-		{
-			if ((stream->hThread = CREATE_THREAD(ProcThreadPoll)) == NULL)
-			   return paUnanticipatedHostError;
-		}
-
-		// Wait for thread to start
-		if (WaitForSingleObject(stream->hThreadStart, 60*1000) == WAIT_TIMEOUT)
-			return paUnanticipatedHostError;
-	}
-	else
-	{
-		// Create blocking operation events (non-signaled event means - blocking operation is pending)
-		if (stream->out.client)
-			stream->hBlockingOpStreamWR = CreateEvent(NULL, TRUE, TRUE, NULL);
-		if (stream->in.client)
-			stream->hBlockingOpStreamRD = CreateEvent(NULL, TRUE, TRUE, NULL);
-
-		// Initialize event & start INPUT stream
-		if (stream->in.client)
-		{
-			if ((hr = IAudioClient_GetService(stream->in.client, &pa_IID_IAudioCaptureClient, (void **)&stream->cclient)) != S_OK)
-			{
-				LogHostError(hr);
-				return paUnanticipatedHostError;
-			}
-
-			if ((hr = IAudioClient_Start(stream->in.client)) != S_OK)
-			{
-				LogHostError(hr);
-				return paUnanticipatedHostError;
-			}
-		}
-
-
-		// Initialize event & start OUTPUT stream
-		if (stream->out.client)
-		{
-			if ((hr = IAudioClient_GetService(stream->out.client, &pa_IID_IAudioRenderClient, (void **)&stream->rclient)) != S_OK)
-			{
-				LogHostError(hr);
-				return paUnanticipatedHostError;
-			}
-
-			// Start
-			if ((hr = IAudioClient_Start(stream->out.client)) != S_OK)
-			{
-				LogHostError(hr);
-				return paUnanticipatedHostError;
-			}
-		}
-
-		// Signal: stream running
-		stream->running = TRUE;
-
-		// Set current time
-		stream->out.prevTime  = timeGetTime();
-		stream->out.prevSleep = 0;
-	}
-
-    return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-static void _FinishStream(PaWasapiStream *stream)
-{
-	// Issue command to thread to stop processing and wait for thread exit
-	if (!stream->bBlocking)
-	{
-		SignalObjectAndWait(stream->hCloseRequest, stream->hThreadExit, INFINITE, FALSE);
-	}
-	else
-	// Blocking mode does not own thread
-	{
-		// Signal close event and wait for each of 2 blocking operations to complete
-		if (stream->out.client)
-			SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamWR, INFINITE, TRUE);
-		if (stream->out.client)
-			SignalObjectAndWait(stream->hCloseRequest, stream->hBlockingOpStreamRD, INFINITE, TRUE);
-
-		// Process stop
-		_OnStreamStop(stream);
-	}
-
-	// Close thread handles to allow restart
-	SAFE_CLOSE(stream->hThread);
-	SAFE_CLOSE(stream->hThreadStart);
-	SAFE_CLOSE(stream->hThreadExit);
-	SAFE_CLOSE(stream->hCloseRequest);
-	SAFE_CLOSE(stream->hBlockingOpStreamRD);
-	SAFE_CLOSE(stream->hBlockingOpStreamWR);
-
-    stream->running = FALSE;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError StopStream( PaStream *s )
-{
-	// Finish stream
-	_FinishStream((PaWasapiStream *)s);
-    return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError AbortStream( PaStream *s )
-{
-	// Finish stream
-	_FinishStream((PaWasapiStream *)s);
-    return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError IsStreamStopped( PaStream *s )
-{
-	return !((PaWasapiStream *)s)->running;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError IsStreamActive( PaStream *s )
-{
-    return ((PaWasapiStream *)s)->running;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaTime GetStreamTime( PaStream *s )
-{
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-
-    /* suppress unused variable warnings */
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-
-	//this is lame ds and mme does the same thing, quite useless method imho
-	//why dont we fetch the time in the pa callbacks?
-	//at least its doing to be clocked to something
-    return PaUtil_GetTime();
-}
-
-// ------------------------------------------------------------------------------------------
-static double GetStreamCpuLoad( PaStream* s )
-{
-	return PaUtil_GetCpuLoad(&((PaWasapiStream *)s)->cpuLoadMeasurer);
-}
-
-// ------------------------------------------------------------------------------------------
-/* NOT TESTED */
-static PaError ReadStream( PaStream* s, void *_buffer, unsigned long _frames )
-{
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-
-	HRESULT hr = S_OK;
-	UINT32 frames;
-	BYTE *user_buffer = (BYTE *)_buffer;
-	BYTE *wasapi_buffer = NULL;
-	DWORD flags = 0;
-	UINT32 i;
-
-	// validate
-	if (!stream->running)
-		return paStreamIsStopped;
-	if (stream->cclient == NULL)
-		return paBadStreamPtr;
-
-	// Notify blocking op has begun
-	ResetEvent(stream->hBlockingOpStreamRD);
-
-    // make a local copy of the user buffer pointer(s), this is necessary
-	// because PaUtil_CopyOutput() advances these pointers every time it is called
-    if (!stream->bufferProcessor.userInputIsInterleaved)
-    {
-		user_buffer = (BYTE *)alloca(sizeof(BYTE *) * stream->bufferProcessor.inputChannelCount);
-        if (user_buffer == NULL)
-            return paInsufficientMemory;
-
-        for (i = 0; i < stream->bufferProcessor.inputChannelCount; ++i)
-            ((BYTE **)user_buffer)[i] = ((BYTE **)_buffer)[i];
-    }
-
-	while (_frames != 0)
-	{
-		UINT32 processed, processed_size;
-
-		// Get the available data in the shared buffer.
-		if ((hr = IAudioCaptureClient_GetBuffer(stream->cclient, &wasapi_buffer, &frames, &flags, NULL, NULL)) != S_OK)
-		{
-			if (hr == AUDCLNT_S_BUFFER_EMPTY)
-			{
-				// Check if blocking call must be interrupted
-				if (WaitForSingleObject(stream->hCloseRequest, 1) != WAIT_TIMEOUT)
-					break;
-			}
-
-			return LogHostError(hr);
-			goto stream_rd_end;
-		}
-
-		// Detect silence
-		// if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
-		//	data = NULL;
-
-		// Check if frames <= _frames
-		if (frames > _frames)
-			frames = _frames;
-
-		// Register available frames to processor
-        PaUtil_SetInputFrameCount(&stream->bufferProcessor, frames);
-
-		// Register host buffer pointer to processor
-        PaUtil_SetInterleavedInputChannels(&stream->bufferProcessor, 0, wasapi_buffer,	stream->bufferProcessor.inputChannelCount);
-
-		// Copy user data to host buffer (with conversion if applicable)
-		processed = PaUtil_CopyInput(&stream->bufferProcessor, (void **)&user_buffer, frames);
-
-		// Advance user buffer to consumed portion
-		processed_size = processed * stream->in.wavex.Format.nBlockAlign;
-		if (stream->bufferProcessor.userInputIsInterleaved)
-		{
-			user_buffer += processed_size;
-		}
-		else
-		{
-			for (i = 0; i < stream->bufferProcessor.inputChannelCount; ++i)
-				((BYTE **)user_buffer)[i] = ((BYTE **)user_buffer)[i] + processed_size;
-		}
-
-		// Release host buffer
-		if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->cclient, processed)) != S_OK)
-		{
-			LogHostError(hr);
-			goto stream_rd_end;
-		}
-
-		_frames -= processed;
-	}
-
-stream_rd_end:
-
-	// Notify blocking op has ended
-	SetEvent(stream->hBlockingOpStreamRD);
-
-	return (hr != S_OK ? paUnanticipatedHostError : paNoError);
-}
-
-// ------------------------------------------------------------------------------------------
-static PaError WriteStream( PaStream* s, const void *_buffer, unsigned long _frames )
-{
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-
-	UINT32 frames;
-	const BYTE *user_buffer = (const BYTE *)_buffer;
-	BYTE *wasapi_buffer;
-	HRESULT hr = S_OK;
-	UINT32 next_rev_sleep, blocks, block_sleep_ms;
-	UINT32 i;
-
-	// validate
-	if (!stream->running)
-		return paStreamIsStopped;
-	if (stream->rclient == NULL)
-		return paBadStreamPtr;
-
-	// Notify blocking op has begun
-	ResetEvent(stream->hBlockingOpStreamWR);
-
-	// Calculate sleep time for next call
-	{
-		UINT32 remainder = 0;
-		UINT32 sleep_ms = 0;
-		DWORD elapsed_ms;
-		blocks = _frames / stream->out.framesPerHostCallback;
-		block_sleep_ms = GetFramesSleepTime(stream->out.framesPerHostCallback, stream->out.wavex.Format.nSamplesPerSec);
-		if (blocks == 0)
-		{
-			blocks = 1;
-			sleep_ms = GetFramesSleepTime(_frames, stream->out.wavex.Format.nSamplesPerSec); // partial
-		}
-		else
-		{
-			remainder = _frames - blocks * stream->out.framesPerHostCallback;
-			sleep_ms = block_sleep_ms; // full
-		}
-
-		// Sleep for remainder
-		elapsed_ms = timeGetTime() - stream->out.prevTime;
-		if (sleep_ms >= elapsed_ms)
-			sleep_ms -= elapsed_ms;
-
-		next_rev_sleep = sleep_ms;
-	}
-
-	// Sleep diff from last call
-	if (stream->out.prevSleep)
-		Sleep(stream->out.prevSleep);
-	stream->out.prevSleep = next_rev_sleep;
-
-    // make a local copy of the user buffer pointer(s), this is necessary
-	// because PaUtil_CopyOutput() advances these pointers every time it is called
-    if (!stream->bufferProcessor.userOutputIsInterleaved)
-    {
-        user_buffer = (const BYTE *)alloca(sizeof(const BYTE *) * stream->bufferProcessor.outputChannelCount);
-        if (user_buffer == NULL)
-            return paInsufficientMemory;
-
-        for (i = 0; i < stream->bufferProcessor.outputChannelCount; ++i)
-            ((const BYTE **)user_buffer)[i] = ((const BYTE **)_buffer)[i];
-    }
-
-	// Feed engine
-	for (i = 0; i < blocks; ++i)
-	{
-		UINT32 available, processed;
-
-		// Get block frames
-		frames = stream->out.framesPerHostCallback;
-		if (frames > _frames)
-			frames = _frames;
-
-		if (i)
-			Sleep(block_sleep_ms);
-
-		while (frames != 0)
-		{
-			UINT32 padding = 0;
-			UINT32 processed_size;
-
-			// Check if blocking call must be interrupted
-			if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
-				break;
-
-			// Get Read position
-			hr = IAudioClient_GetCurrentPadding(stream->out.client, &padding);
-			if (hr != S_OK)
-			{
-				LogHostError(hr);
-				goto stream_wr_end;
-			}
-
-			// Calculate frames available
-			if (frames >= padding)
-				available = frames - padding;
-			else
-				available = frames;
-
-			// Get pointer to host buffer
-			if ((hr = IAudioRenderClient_GetBuffer(stream->rclient, available, &wasapi_buffer)) != S_OK)
-			{
-				// Buffer size is too big, waiting
-				if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
-					continue;
-				LogHostError(hr);
-				goto stream_wr_end;
-			}
-
-			// Register available frames to processor
-            PaUtil_SetOutputFrameCount(&stream->bufferProcessor, available);
-
-			// Register host buffer pointer to processor
-            PaUtil_SetInterleavedOutputChannels(&stream->bufferProcessor, 0, wasapi_buffer,	stream->bufferProcessor.outputChannelCount);
-
-			// Copy user data to host buffer (with conversion if applicable)
-			processed = PaUtil_CopyOutput(&stream->bufferProcessor, (const void **)&user_buffer, available);
-
-			// Advance user buffer to consumed portion
-			processed_size = processed * stream->out.wavex.Format.nBlockAlign;
-			if (stream->bufferProcessor.userOutputIsInterleaved)
-			{
-				user_buffer += processed_size;
-			}
-			else
-			{
-				for (i = 0; i < stream->bufferProcessor.outputChannelCount; ++i)
-					((const BYTE **)user_buffer)[i] = ((const BYTE **)user_buffer)[i] + processed_size;
-			}
-
-			// Release host buffer
-			if ((hr = IAudioRenderClient_ReleaseBuffer(stream->rclient, processed, 0)) != S_OK)
-			{
-				LogHostError(hr);
-				goto stream_wr_end;
-			}
-
-			// Deduct frames
-			frames -= processed;
-		}
-
-		_frames -= frames;
-	}
-
-stream_wr_end:
-
-	// Set prev time
-	stream->out.prevTime = timeGetTime();
-
-	// Notify blocking op has ended
-	SetEvent(stream->hBlockingOpStreamWR);
-
-	return (hr != S_OK ? paUnanticipatedHostError : paNoError);
-}
-
-// ------------------------------------------------------------------------------------------
-/* NOT TESTED */
-static signed long GetStreamReadAvailable( PaStream* s )
-{
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-	HRESULT hr;
-	UINT32 pending = 0;
-
-	// validate
-	if (!stream->running)
-		return paStreamIsStopped;
-	if (stream->cclient == NULL)
-		return paBadStreamPtr;
-
-	hr = IAudioClient_GetCurrentPadding(stream->in.client, &pending);
-	if (hr != S_OK)
-	{
-		LogHostError(hr);
-		return paUnanticipatedHostError;
-	}
-
-    return (long)pending;
-}
-
-// ------------------------------------------------------------------------------------------
-static signed long GetStreamWriteAvailable( PaStream* s )
-{
-    PaWasapiStream *stream = (PaWasapiStream*)s;
-
-	UINT32 frames = stream->out.framesPerHostCallback;
-	HRESULT hr;
-	UINT32 padding = 0;
-
-	// validate
-	if (!stream->running)
-		return paStreamIsStopped;
-	if (stream->rclient == NULL)
-		return paBadStreamPtr;
-
-	hr = IAudioClient_GetCurrentPadding(stream->out.client, &padding);
-	if (hr != S_OK)
-	{
-		LogHostError(hr);
-		return paUnanticipatedHostError;
-	}
-
-	// Calculate
-	frames -= padding;
-
-    return frames;
-}
-
-// ------------------------------------------------------------------------------------------
-static void WaspiHostProcessingLoop( void *inputBuffer,  long inputFrames,
-                                     void *outputBuffer, long outputFrames,
-                                     void *userData )
-{
-    PaWasapiStream *stream = (PaWasapiStream*)userData;
-    PaStreamCallbackTimeInfo timeInfo = {0,0,0};
-	PaStreamCallbackFlags flags = 0;
-    int callbackResult;
-    unsigned long framesProcessed;
-	HRESULT hr;
-	UINT32 pending;
-
-    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
-
-    /*
-		Pa_GetStreamTime:
-            - generate timing information
-            - handle buffer slips
-    */
-	timeInfo.currentTime = PaUtil_GetTime();
-	// Query input latency
-	if (stream->in.client != NULL)
-	{
-		PaTime pending_time;
-		if ((hr = IAudioClient_GetCurrentPadding(stream->in.client, &pending)) == S_OK)
-			pending_time = (PaTime)pending / (PaTime)stream->in.wavex.Format.nSamplesPerSec;
-		else
-			pending_time = (PaTime)stream->in.latency_seconds;
-
-		timeInfo.inputBufferAdcTime = timeInfo.currentTime + pending_time;
-	}
-	// Query output current latency
-	if (stream->out.client != NULL)
-	{
-		PaTime pending_time;
-		if ((hr = IAudioClient_GetCurrentPadding(stream->out.client, &pending)) == S_OK)
-			pending_time = (PaTime)pending / (PaTime)stream->out.wavex.Format.nSamplesPerSec;
-		else
-			pending_time = (PaTime)stream->out.latency_seconds;
-
-		timeInfo.outputBufferDacTime = timeInfo.currentTime + pending_time;
-	}
-
-    /*
-        If you need to byte swap or shift inputBuffer to convert it into a
-        portaudio format, do it here.
-    */
-
-    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, flags );
-
-    /*
-        depending on whether the host buffers are interleaved, non-interleaved
-        or a mixture, you will want to call PaUtil_SetInterleaved*Channels(),
-        PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here.
-    */
-
-    if (stream->bufferProcessor.inputChannelCount > 0)
-    {
-        PaUtil_SetInputFrameCount( &stream->bufferProcessor, inputFrames );
-        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,
-            0, /* first channel of inputBuffer is channel 0 */
-            inputBuffer,
-            0 ); /* 0 - use inputChannelCount passed to init buffer processor */
-    }
-
-    if (stream->bufferProcessor.outputChannelCount > 0)
-    {
-        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, outputFrames);
-        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,
-            0, /* first channel of outputBuffer is channel 0 */
-            outputBuffer,
-            0 ); /* 0 - use outputChannelCount passed to init buffer processor */
-    }
-
-    /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing()
-        in general you would pass paContinue for normal operation, and
-        paComplete to drain the buffer processor's internal output buffer.
-        You can check whether the buffer processor's output buffer is empty
-        using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor )
-    */
-    callbackResult = paContinue;
-    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
-
-    /*
-        If you need to byte swap or shift outputBuffer to convert it to
-        host format, do it here.
-    */
-
-	PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
-
-    if (callbackResult == paContinue)
-    {
-        /* nothing special to do */
-    }
-    else
-	if (callbackResult == paAbort)
-    {
-		// stop stream
-        SetEvent(stream->hCloseRequest);
-    }
-    else
-    {
-		// stop stream
-        SetEvent(stream->hCloseRequest);
-    }
-}
-
-// ------------------------------------------------------------------------------------------
-HANDLE MMCSS_activate(const char *name)
-{
-    DWORD task_idx = 0;
-    HANDLE hTask = pAvSetMmThreadCharacteristics(name, &task_idx);
-    if (hTask == NULL)
-	{
-        PRINT(("WASAPI: AvSetMmThreadCharacteristics failed!\n"));
-    }
-
-    /*BOOL priority_ok = pAvSetMmThreadPriority(hTask, AVRT_PRIORITY_NORMAL);
-    if (priority_ok == FALSE)
-	{
-        PRINT(("WASAPI: AvSetMmThreadPriority failed!\n"));
-    }*/
-
-	// debug
-    {
-        int    cur_priority		  = GetThreadPriority(GetCurrentThread());
-        DWORD  cur_priority_class = GetPriorityClass(GetCurrentProcess());
-		PRINT(("WASAPI: thread[ priority-0x%X class-0x%X ]\n", cur_priority, cur_priority_class));
-    }
-
-	return hTask;
-}
-
-// ------------------------------------------------------------------------------------------
-void MMCSS_deactivate(HANDLE hTask)
-{
-	if (!hTask)
-		return;
-
-	if (pAvRevertMmThreadCharacteristics(hTask) == FALSE)
-	{
-        PRINT(("WASAPI: AvRevertMmThreadCharacteristics failed!\n"));
-    }
-}
-
-// ------------------------------------------------------------------------------------------
-PaError PaWasapi_ThreadPriorityBoost(void **hTask, PaWasapiThreadPriority nPriorityClass)
-{
-	static const char *mmcs_name[] =
-	{
-		NULL,
-		"Audio",
-		"Capture",
-		"Distribution",
-		"Games",
-		"Playback",
-		"Pro Audio",
-		"Window Manager"
-	};
-	HANDLE task;
-
-	if (hTask == NULL)
-		return paUnanticipatedHostError;
-
-	if ((UINT32)nPriorityClass >= STATIC_ARRAY_SIZE(mmcs_name))
-		return paUnanticipatedHostError;
-
-	task = MMCSS_activate(mmcs_name[nPriorityClass]);
-	if (task == NULL)
-		return paUnanticipatedHostError;
-
-	(*hTask) = task;
-	return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-PaError PaWasapi_ThreadPriorityRevert(void *hTask)
-{
-	if (hTask == NULL)
-		return paUnanticipatedHostError;
-
-	MMCSS_deactivate((HANDLE)hTask);
-
-	return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-// Described at:
-// http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
-
-PaError PaWasapi_GetJackCount(PaDeviceIndex nDevice, int *jcount)
-{
-	PaError ret;
-	HRESULT hr = S_OK;
-	PaDeviceIndex index;
-    IDeviceTopology *pDeviceTopology = NULL;
-    IConnector *pConnFrom = NULL;
-    IConnector *pConnTo = NULL;
-    IPart *pPart = NULL;
-    IKsJackDescription *pJackDesc = NULL;
-	UINT jackCount = 0;
-
-	PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
-	if (paWasapi == NULL)
-		return paNotInitialized;
-
-	// Get device index.
-	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
-    if (ret != paNoError)
-        return ret;
-
-	// Validate index.
-	if ((UINT32)index >= paWasapi->deviceCount)
-		return paInvalidDevice;
-
-	// Get the endpoint device's IDeviceTopology interface.
-	hr = IMMDevice_Activate(paWasapi->devInfo[index].device, &pa_IID_IDeviceTopology,
-		CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
-	IF_FAILED_JUMP(hr, error);
-
-    // The device topology for an endpoint device always contains just one connector (connector number 0).
-	hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
-	IF_FAILED_JUMP(hr, error);
-
-    // Step across the connection to the jack on the adapter.
-	hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
-    if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
-    {
-        // The adapter device is not currently active.
-        hr = E_NOINTERFACE;
-    }
-	IF_FAILED_JUMP(hr, error);
-
-	// Get the connector's IPart interface.
-	hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
-	IF_FAILED_JUMP(hr, error);
-
-	// Activate the connector's IKsJackDescription interface.
-	hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
-	IF_FAILED_JUMP(hr, error);
-
-	// Return jack count for this device.
-	hr = IKsJackDescription_GetJackCount(pJackDesc, &jackCount);
-	IF_FAILED_JUMP(hr, error);
-
-	// Set.
-	(*jcount) = jackCount;
-
-	// Ok.
-	ret = paNoError;
-
-error:
-
-	SAFE_RELEASE(pDeviceTopology);
-	SAFE_RELEASE(pConnFrom);
-	SAFE_RELEASE(pConnTo);
-	SAFE_RELEASE(pPart);
-	SAFE_RELEASE(pJackDesc);
-
-	LogHostError(hr);
-	return paNoError;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaWasapiJackConnectionType ConvertJackConnectionTypeWASAPIToPA(int connType)
-{
-	switch (connType)
-	{
-		case eConnTypeUnknown:			return eJackConnTypeUnknown;
-#ifdef _KS_
-		case eConnType3Point5mm:		return eJackConnType3Point5mm;
-#else
-		case eConnTypeEighth:		    return eJackConnType3Point5mm;
-#endif
-		case eConnTypeQuarter:			return eJackConnTypeQuarter;
-		case eConnTypeAtapiInternal:	return eJackConnTypeAtapiInternal;
-		case eConnTypeRCA:				return eJackConnTypeRCA;
-		case eConnTypeOptical:			return eJackConnTypeOptical;
-		case eConnTypeOtherDigital:		return eJackConnTypeOtherDigital;
-		case eConnTypeOtherAnalog:		return eJackConnTypeOtherAnalog;
-		case eConnTypeMultichannelAnalogDIN: return eJackConnTypeMultichannelAnalogDIN;
-		case eConnTypeXlrProfessional:	return eJackConnTypeXlrProfessional;
-		case eConnTypeRJ11Modem:		return eJackConnTypeRJ11Modem;
-		case eConnTypeCombination:		return eJackConnTypeCombination;
-	}
-	return eJackConnTypeUnknown;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaWasapiJackGeoLocation ConvertJackGeoLocationWASAPIToPA(int geoLoc)
-{
-	switch (geoLoc)
-	{
-	case eGeoLocRear:				return eJackGeoLocRear;
-	case eGeoLocFront:				return eJackGeoLocFront;
-	case eGeoLocLeft:				return eJackGeoLocLeft;
-	case eGeoLocRight:				return eJackGeoLocRight;
-	case eGeoLocTop:				return eJackGeoLocTop;
-	case eGeoLocBottom:				return eJackGeoLocBottom;
-#ifdef _KS_
-	case eGeoLocRearPanel:			return eJackGeoLocRearPanel;
-#else
-	case eGeoLocRearOPanel:         return eJackGeoLocRearPanel;
-#endif
-	case eGeoLocRiser:				return eJackGeoLocRiser;
-	case eGeoLocInsideMobileLid:	return eJackGeoLocInsideMobileLid;
-	case eGeoLocDrivebay:			return eJackGeoLocDrivebay;
-	case eGeoLocHDMI:				return eJackGeoLocHDMI;
-	case eGeoLocOutsideMobileLid:	return eJackGeoLocOutsideMobileLid;
-	case eGeoLocATAPI:				return eJackGeoLocATAPI;
-	}
-	return eJackGeoLocUnk;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaWasapiJackGenLocation ConvertJackGenLocationWASAPIToPA(int genLoc)
-{
-	switch (genLoc)
-	{
-	case eGenLocPrimaryBox:	return eJackGenLocPrimaryBox;
-	case eGenLocInternal:	return eJackGenLocInternal;
-#ifdef _KS_
-	case eGenLocSeparate:	return eJackGenLocSeparate;
-#else
-	case eGenLocSeperate:	return eJackGenLocSeparate;
-#endif
-	case eGenLocOther:		return eJackGenLocOther;
-	}
-	return eJackGenLocPrimaryBox;
-}
-
-// ------------------------------------------------------------------------------------------
-static PaWasapiJackPortConnection ConvertJackPortConnectionWASAPIToPA(int portConn)
-{
-	switch (portConn)
-	{
-	case ePortConnJack:					return eJackPortConnJack;
-	case ePortConnIntegratedDevice:		return eJackPortConnIntegratedDevice;
-	case ePortConnBothIntegratedAndJack:return eJackPortConnBothIntegratedAndJack;
-	case ePortConnUnknown:				return eJackPortConnUnknown;
-	}
-	return eJackPortConnJack;
-}
-
-// ------------------------------------------------------------------------------------------
-// Described at:
-// http://msdn.microsoft.com/en-us/library/dd371387(v=VS.85).aspx
-
-PaError PaWasapi_GetJackDescription(PaDeviceIndex nDevice, int jindex, PaWasapiJackDescription *pJackDescription)
-{
-	PaError ret;
-	HRESULT hr = S_OK;
-	PaDeviceIndex index;
-    IDeviceTopology *pDeviceTopology = NULL;
-    IConnector *pConnFrom = NULL;
-    IConnector *pConnTo = NULL;
-    IPart *pPart = NULL;
-    IKsJackDescription *pJackDesc = NULL;
-	KSJACK_DESCRIPTION jack = { 0 };
-
-	PaWasapiHostApiRepresentation *paWasapi = _GetHostApi(&ret);
-	if (paWasapi == NULL)
-		return paNotInitialized;
-
-	// Get device index.
-	ret = PaUtil_DeviceIndexToHostApiDeviceIndex(&index, nDevice, &paWasapi->inheritedHostApiRep);
-    if (ret != paNoError)
-        return ret;
-
-	// Validate index.
-	if ((UINT32)index >= paWasapi->deviceCount)
-		return paInvalidDevice;
-
-	// Get the endpoint device's IDeviceTopology interface.
-	hr = IMMDevice_Activate(paWasapi->devInfo[index].device, &pa_IID_IDeviceTopology,
-		CLSCTX_INPROC_SERVER, NULL, (void**)&pDeviceTopology);
-	IF_FAILED_JUMP(hr, error);
-
-    // The device topology for an endpoint device always contains just one connector (connector number 0).
-	hr = IDeviceTopology_GetConnector(pDeviceTopology, 0, &pConnFrom);
-	IF_FAILED_JUMP(hr, error);
-
-    // Step across the connection to the jack on the adapter.
-	hr = IConnector_GetConnectedTo(pConnFrom, &pConnTo);
-    if (HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND) == hr)
-    {
-        // The adapter device is not currently active.
-        hr = E_NOINTERFACE;
-    }
-	IF_FAILED_JUMP(hr, error);
-
-	// Get the connector's IPart interface.
-	hr = IConnector_QueryInterface(pConnTo, &pa_IID_IPart, (void**)&pPart);
-	IF_FAILED_JUMP(hr, error);
-
-	// Activate the connector's IKsJackDescription interface.
-	hr = IPart_Activate(pPart, CLSCTX_INPROC_SERVER, &pa_IID_IKsJackDescription, (void**)&pJackDesc);
-	IF_FAILED_JUMP(hr, error);
-
-	// Test to return jack description struct for index 0.
-	hr = IKsJackDescription_GetJackDescription(pJackDesc, jindex, &jack);
-	IF_FAILED_JUMP(hr, error);
-
-	// Convert WASAPI values to PA format.
-	pJackDescription->channelMapping = jack.ChannelMapping;
-	pJackDescription->color          = jack.Color;
-	pJackDescription->connectionType = ConvertJackConnectionTypeWASAPIToPA(jack.ConnectionType);
-	pJackDescription->genLocation    = ConvertJackGenLocationWASAPIToPA(jack.GenLocation);
-	pJackDescription->geoLocation    = ConvertJackGeoLocationWASAPIToPA(jack.GeoLocation);
-	pJackDescription->isConnected    = jack.IsConnected;
-	pJackDescription->portConnection = ConvertJackPortConnectionWASAPIToPA(jack.PortConnection);
-
-	// Ok.
-	ret = paNoError;
-
-error:
-
-	SAFE_RELEASE(pDeviceTopology);
-	SAFE_RELEASE(pConnFrom);
-	SAFE_RELEASE(pConnTo);
-	SAFE_RELEASE(pPart);
-	SAFE_RELEASE(pJackDesc);
-
-	LogHostError(hr);
-	return ret;
-}
-
-// ------------------------------------------------------------------------------------------
-static HRESULT ProcessOutputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor, UINT32 frames)
-{
-	HRESULT hr;
-	BYTE *data = NULL;
-
-	// Get buffer
-	if ((hr = IAudioRenderClient_GetBuffer(stream->rclient, frames, &data)) != S_OK)
-	{
-		if (stream->out.shareMode == AUDCLNT_SHAREMODE_SHARED)
-		{
-			// Using GetCurrentPadding to overcome AUDCLNT_E_BUFFER_TOO_LARGE in
-			// shared mode results in no sound in Event-driven mode (MSDN does not
-			// document this, or is it WASAPI bug?), thus we better
-			// try to acquire buffer next time when GetBuffer allows to do so.
-#if 0
-			// Get Read position
-			UINT32 padding = 0;
-			hr = stream->out.client->GetCurrentPadding(&padding);
-			if (hr != S_OK)
-				return LogHostError(hr);
-
-			// Get frames to write
-			frames -= padding;
-			if (frames == 0)
-				return S_OK;
-
-			if ((hr = stream->rclient->GetBuffer(frames, &data)) != S_OK)
-				return LogHostError(hr);
-#else
-			if (hr == AUDCLNT_E_BUFFER_TOO_LARGE)
-				return S_OK; // be silent in shared mode, try again next time
-#endif
-		}
-		else
-			return LogHostError(hr);
-	}
-
-	// Process data
-	if (stream->out.monoMixer != NULL)
-	{
-#define __DIV_8(v)  ((v) >> 3) //!< (v / 8)
-
-		// expand buffer (one way only for better performancedue to no calls to realloc)
-		UINT32 mono_frames_size = frames * __DIV_8(stream->out.wavex.Format.wBitsPerSample);
-		if (mono_frames_size > stream->out.monoBufferSize)
-			stream->out.monoBuffer = realloc(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
-
-		// process
-		processor[S_OUTPUT].processor(NULL, 0, (BYTE *)stream->out.monoBuffer, frames, processor[S_OUTPUT].userData);
-
-		// mix 1 to 2 channels
-		stream->out.monoMixer(data, stream->out.monoBuffer, frames);
-
-#undef __DIV_8
-	}
-	else
-	{
-		processor[S_OUTPUT].processor(NULL, 0, data, frames, processor[S_OUTPUT].userData);
-	}
-
-	// Release buffer
-	if ((hr = IAudioRenderClient_ReleaseBuffer(stream->rclient, frames, 0)) != S_OK)
-		LogHostError(hr);
-
-	return hr;
-}
-
-// ------------------------------------------------------------------------------------------
-static HRESULT ProcessInputBuffer(PaWasapiStream *stream, PaWasapiHostProcessor *processor)
-{
-	HRESULT hr = S_OK;
-	UINT32 frames;
-	BYTE *data = NULL;
-	DWORD flags = 0;
-
-	for (;;)
-	{
-		// Check if blocking call must be interrupted
-		if (WaitForSingleObject(stream->hCloseRequest, 1) != WAIT_TIMEOUT)
-			break;
-
-		// Get the available data in the shared buffer.
-		if ((hr = IAudioCaptureClient_GetBuffer(stream->cclient, &data, &frames, &flags, NULL, NULL)) != S_OK)
-		{
-			if (hr == AUDCLNT_S_BUFFER_EMPTY)
-				break; // capture buffer exhausted
-
-			return LogHostError(hr);
-			break;
-		}
-
-		// Detect silence
-		// if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
-		//	data = NULL;
-
-		// Process data
-		if (stream->in.monoMixer != NULL)
-		{
-#define __DIV_8(v)  ((v) >> 3) //!< (v / 8)
-
-			// expand buffer (one way only for better performancedue to no calls to realloc)
-			UINT32 mono_frames_size = frames * __DIV_8(stream->in.wavex.Format.wBitsPerSample);
-			if (mono_frames_size > stream->in.monoBufferSize)
-				stream->in.monoBuffer = realloc(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
-
-			// mix 1 to 2 channels
-			stream->in.monoMixer(stream->in.monoBuffer, data, frames);
-
-			// process
-			processor[S_INPUT].processor((BYTE *)stream->in.monoBuffer, frames, NULL, 0, processor[S_INPUT].userData);
-
-#undef __DIV_8
-		}
-		else
-		{
-			processor[S_INPUT].processor(data, frames, NULL, 0, processor[S_INPUT].userData);
-		}
-
-		// Release buffer
-		if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->cclient, frames)) != S_OK)
-			return LogHostError(hr);
-	}
-
-	return hr;
-}
-
-// ------------------------------------------------------------------------------------------
-void _OnStreamStop(PaWasapiStream *stream)
-{
-	// Stop INPUT client
-	if (stream->in.client != NULL)
-		IAudioClient_Stop(stream->in.client);
-
-	// Stop OUTPUT client
-	if (stream->out.client != NULL)
-		IAudioClient_Stop(stream->out.client);
-
-	// Restore thread priority
-	if (stream->hAvTask != NULL)
-	{
-		PaWasapi_ThreadPriorityRevert(stream->hAvTask);
-		stream->hAvTask = NULL;
-	}
-
-    // Notify
-    if (stream->streamRepresentation.streamFinishedCallback != NULL)
-        stream->streamRepresentation.streamFinishedCallback(stream->streamRepresentation.userData);
-}
-
-// ------------------------------------------------------------------------------------------
-PA_THREAD_FUNC ProcThreadEvent(void *param)
-{
-    PaWasapiHostProcessor processor[S_COUNT];
-	HRESULT hr;
-	DWORD dwResult;
-    PaWasapiStream *stream = (PaWasapiStream *)param;
-	PaWasapiHostProcessor defaultProcessor;
-	BOOL set_event[S_COUNT] = { FALSE, FALSE };
-
-	// Waiting on all events in case of Full-Duplex/Exclusive mode.
-	BOOL bWaitAllEvents = FALSE;
-	if ((stream->in.client != NULL) && (stream->out.client != NULL))
-	{
-		bWaitAllEvents = (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE) &&
-			(stream->out.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE);
-	}
-
-    // Setup data processors
-    defaultProcessor.processor = WaspiHostProcessingLoop;
-    defaultProcessor.userData  = stream;
-    processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
-    processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
-
-	// Boost thread priority
-	PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
-
-	// Create events
-	if (stream->event[S_OUTPUT] == NULL)
-	{
-		stream->event[S_OUTPUT] = CreateEvent(NULL, FALSE, FALSE, NULL);
-		set_event[S_OUTPUT] = TRUE;
-	}
-	if (stream->event[S_INPUT] == NULL)
-	{
-		stream->event[S_INPUT]  = CreateEvent(NULL, FALSE, FALSE, NULL);
-		set_event[S_INPUT] = TRUE;
-	}
-	if ((stream->event[S_OUTPUT] == NULL) || (stream->event[S_INPUT] == NULL))
-	{
-		PRINT(("WASAPI Thread: failed creating Input/Output event handle\n"));
-		goto thread_error;
-	}
-
-	// Initialize event & start INPUT stream
-	if (stream->in.client)
-	{
-		// Create & set handle
-		if (set_event[S_INPUT])
-		{
-			if ((hr = IAudioClient_SetEventHandle(stream->in.client, stream->event[S_INPUT])) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-		}
-
-		// Create Capture client
-		if (stream->cclient == NULL)
-		{
-			if ((hr = IAudioClient_GetService(stream->in.client, &pa_IID_IAudioCaptureClient, (void **)&stream->cclient)) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-		}
-
-		// Start
-		if ((hr = IAudioClient_Start(stream->in.client)) != S_OK)
-		{
-			LogHostError(hr);
-			goto thread_error;
-		}
-	}
-
-	// Initialize event & start OUTPUT stream
-	if (stream->out.client)
-	{
-		// Create & set handle
-		if (set_event[S_OUTPUT])
-		{
-			if ((hr = IAudioClient_SetEventHandle(stream->out.client, stream->event[S_OUTPUT])) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-		}
-
-		// Create Render client
-		if (stream->rclient == NULL)
-		{
-			if ((hr = IAudioClient_GetService(stream->out.client, &pa_IID_IAudioRenderClient, (void **)&stream->rclient)) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-		}
-
-		// Preload buffer before start
-		if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
-		{
-			LogHostError(hr);
-			goto thread_error;
-		}
-
-		// Start
-		if ((hr = IAudioClient_Start(stream->out.client)) != S_OK)
-		{
-			LogHostError(hr);
-			goto thread_error;
-		}
-
-	}
-
-	// Signal: stream running
-	stream->running = TRUE;
-
-	// Notify: thread started
-	SetEvent(stream->hThreadStart);
-
-	// Processing Loop
-	for (;;)
-    {
-	    // 2 sec timeout
-        dwResult = WaitForMultipleObjects(S_COUNT, stream->event, bWaitAllEvents, 10000);
-
-		// Check for close event (after wait for buffers to avoid any calls to user
-		// callback when hCloseRequest was set)
-		if (WaitForSingleObject(stream->hCloseRequest, 0) != WAIT_TIMEOUT)
-			break;
-
-		// Process S_INPUT/S_OUTPUT
-		switch (dwResult)
-		{
-		case WAIT_TIMEOUT: {
-			PRINT(("WASAPI Thread: WAIT_TIMEOUT - probably bad audio driver or Vista x64 bug: use paWinWasapiPolling instead\n"));
-			goto thread_end;
-			break; }
-
-		// Input stream
-		case WAIT_OBJECT_0 + S_INPUT: {
-            if (stream->cclient == NULL)
-                break;
-			if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-			break; }
-
-		// Output stream
-		case WAIT_OBJECT_0 + S_OUTPUT: {
-            if (stream->rclient == NULL)
-                break;
-			if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-			break; }
-		}
-	}
-
-thread_end:
-
-	// Process stop
-	_OnStreamStop(stream);
-
-	// Notify: thread exited
-	SetEvent(stream->hThreadExit);
-
-	// Notify: not running
-	stream->running = FALSE;
-
-	return 0;
-
-thread_error:
-
-	// Prevent deadlocking in Pa_StreamStart
-	SetEvent(stream->hThreadStart);
-
-	// Exit
-	goto thread_end;
-}
-
-// ------------------------------------------------------------------------------------------
-static HRESULT PollGetOutputFramesAvailable(PaWasapiStream *stream, UINT32 *available)
-{
-	HRESULT hr;
-	UINT32 frames  = stream->out.framesPerHostCallback,
-		   padding = 0;
-
-	(*available) = 0;
-
-	// get read position
-	if ((hr = IAudioClient_GetCurrentPadding(stream->out.client, &padding)) != S_OK)
-		return LogHostError(hr);
-
-	// get available
-	frames -= padding;
-
-	// set
-	(*available) = frames;
-	return hr;
-}
-
-// ------------------------------------------------------------------------------------------
-PA_THREAD_FUNC ProcThreadPoll(void *param)
-{
-    PaWasapiHostProcessor processor[S_COUNT];
-	HRESULT hr;
-    PaWasapiStream *stream = (PaWasapiStream *)param;
-	PaWasapiHostProcessor defaultProcessor;
-	INT32 i;
-
-	// Calculate the actual duration of the allocated buffer.
-	DWORD sleep_ms     = 0;
-	DWORD sleep_ms_in  = GetFramesSleepTime(stream->in.framesPerBuffer, stream->in.wavex.Format.nSamplesPerSec);
-	DWORD sleep_ms_out = GetFramesSleepTime(stream->out.framesPerBuffer, stream->out.wavex.Format.nSamplesPerSec);
-
-	// Adjust polling time
-	if (stream->bufferMode != paUtilFixedHostBufferSize)
-	{
-		sleep_ms_in  = GetFramesSleepTime(stream->bufferProcessor.framesPerUserBuffer, stream->in.wavex.Format.nSamplesPerSec);
-		sleep_ms_out = GetFramesSleepTime(stream->bufferProcessor.framesPerUserBuffer, stream->out.wavex.Format.nSamplesPerSec);
-	}
-
-	// Choose smallest
-	if ((sleep_ms_in != 0) && (sleep_ms_out != 0))
-		sleep_ms = min(sleep_ms_in, sleep_ms_out);
-	else
-	{
-		sleep_ms = (sleep_ms_in ? sleep_ms_in : sleep_ms_out);
-	}
-	// Make sure not 0
-	if (sleep_ms == 0)
-		sleep_ms = 1;
-
-    // Setup data processors
-    defaultProcessor.processor = WaspiHostProcessingLoop;
-    defaultProcessor.userData  = stream;
-    processor[S_INPUT] = (stream->hostProcessOverrideInput.processor != NULL ? stream->hostProcessOverrideInput : defaultProcessor);
-    processor[S_OUTPUT] = (stream->hostProcessOverrideOutput.processor != NULL ? stream->hostProcessOverrideOutput : defaultProcessor);
-
-	// Boost thread priority
-	PaWasapi_ThreadPriorityBoost((void **)&stream->hAvTask, stream->nThreadPriority);
-
-	// Initialize event & start INPUT stream
-	if (stream->in.client)
-	{
-		if (stream->cclient == NULL)
-		{
-			if ((hr = IAudioClient_GetService(stream->in.client, &pa_IID_IAudioCaptureClient, (void **)&stream->cclient)) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-		}
-
-		if ((hr = IAudioClient_Start(stream->in.client)) != S_OK)
-		{
-			LogHostError(hr);
-			goto thread_error;
-		}
-	}
-
-
-	// Initialize event & start OUTPUT stream
-	if (stream->out.client)
-	{
-		if (stream->rclient == NULL)
-		{
-			if ((hr = IAudioClient_GetService(stream->out.client, &pa_IID_IAudioRenderClient, (void **)&stream->rclient)) != S_OK)
-			{
-				LogHostError(hr);
-				goto thread_error;
-			}
-		}
-
-		// Preload buffer (obligatory, othervise ->Start() will fail), avoid processing
-		// when in full-duplex mode as it requires input processing as well
-		if (!PA_WASAPI__IS_FULLDUPLEX(stream))
-		{
-			UINT32 frames = 0;
-			if ((hr = PollGetOutputFramesAvailable(stream, &frames)) == S_OK)
-            {
-				if (stream->bufferMode == paUtilFixedHostBufferSize)
-				{
-					if (frames >= stream->out.framesPerBuffer)
-						frames = stream->out.framesPerBuffer;
-				}
-
-                if (frames != 0)
-                {
-                    if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
-                    {
-                        LogHostError(hr); // not fatal, just log
-                    }
-                }
-            }
-            else
-			{
-				LogHostError(hr); // not fatal, just log
-			}
-		}
-
-		// Start
-		if ((hr = IAudioClient_Start(stream->out.client)) != S_OK)
-		{
-			LogHostError(hr);
-			goto thread_error;
-		}
-	}
-
-	// Signal: stream running
-	stream->running = TRUE;
-
-	// Notify: thread started
-	SetEvent(stream->hThreadStart);
-
-	if (!PA_WASAPI__IS_FULLDUPLEX(stream))
-	{
-		// Processing Loop
-		while (WaitForSingleObject(stream->hCloseRequest, sleep_ms) == WAIT_TIMEOUT)
-		{
-			for (i = 0; i < S_COUNT; ++i)
-			{
-				// Process S_INPUT/S_OUTPUT
-				switch (i)
-				{
-				// Input stream
-				case S_INPUT: {
-					if (stream->cclient == NULL)
-						break;
-					if ((hr = ProcessInputBuffer(stream, processor)) != S_OK)
-					{
-						LogHostError(hr);
-						goto thread_error;
-					}
-					break; }
-
-				// Output stream
-				case S_OUTPUT: {
-
-					UINT32 frames;
-					if (stream->rclient == NULL)
-						break;
-
-					// get available frames
-					if ((hr = PollGetOutputFramesAvailable(stream, &frames)) != S_OK)
-					{
-						LogHostError(hr);
-						goto thread_error;
-					}
-
-					// output
-					if (stream->bufferMode == paUtilFixedHostBufferSize)
-					{
-						if (frames >= stream->out.framesPerBuffer)
-						{
-							if ((hr = ProcessOutputBuffer(stream, processor, stream->out.framesPerBuffer)) != S_OK)
-							{
-								LogHostError(hr);
-								goto thread_error;
-							}
-						}
-					}
-					else
-					{
-						if (frames != 0)
-						{
-							if ((hr = ProcessOutputBuffer(stream, processor, frames)) != S_OK)
-							{
-								LogHostError(hr);
-								goto thread_error;
-							}
-						}
-					}
-
-					break; }
-				}
-			}
-		}
-	}
-	else
-	{
-#if 0
-		// Processing Loop
-		while (WaitForSingleObject(stream->hCloseRequest, 1) == WAIT_TIMEOUT)
-		{
-			UINT32 i_frames = 0, i_processed = 0;
-			BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
-			DWORD i_flags = 0;
-			UINT32 o_frames = 0;
-
-			// get host input buffer
-			if ((hr = IAudioCaptureClient_GetBuffer(stream->cclient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
-			{
-				if (hr == AUDCLNT_S_BUFFER_EMPTY)
-					continue; // no data in capture buffer
-
-				LogHostError(hr);
-				break;
-			}
-
-			// get available frames
-			if ((hr = PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
-			{
-				LogHostError(hr);
-				break;
-			}
-
-			// process equal ammount of frames
-			if (o_frames >= i_frames)
-			{
-				// process input ammount of frames
-				UINT32 o_processed = i_frames;
-
-				// get host output buffer
-				if ((hr = IAudioRenderClient_GetBuffer(stream->rclient, o_processed, &o_data)) == S_OK)
-				{
-					// processed amount of i_frames
-					i_processed = i_frames;
-					o_data_host = o_data;
-
-					// convert output mono
-					if (stream->out.monoMixer)
-					{
-						#define __DIV_8(v)  ((v) >> 3) //!< (v / 8)
-						UINT32 mono_frames_size = o_processed * __DIV_8(stream->out.wavex.Format.wBitsPerSample);
-						#undef __DIV_8
-						// expand buffer (one way only for better performance due to no calls to realloc)
-						if (mono_frames_size > stream->out.monoBufferSize)
-						{
-							stream->out.monoBuffer = realloc(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
-							if (stream->out.monoBuffer == NULL)
-							{
-								LogPaError(paInsufficientMemory);
-								break;
-							}
-						}
-
-						// replace buffer pointer
-						o_data = (BYTE *)stream->out.monoBuffer;
-					}
-
-					// convert input mono
-					if (stream->in.monoMixer)
-					{
-						#define __DIV_8(v)  ((v) >> 3) //!< (v / 8)
-						UINT32 mono_frames_size = i_processed * __DIV_8(stream->in.wavex.Format.wBitsPerSample);
-						#undef __DIV_8
-						// expand buffer (one way only for better performance due to no calls to realloc)
-						if (mono_frames_size > stream->in.monoBufferSize)
-						{
-							stream->in.monoBuffer = realloc(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
-							if (stream->in.monoBuffer == NULL)
-							{
-								LogPaError(paInsufficientMemory);
-								break;
-							}
-						}
-
-						// mix 2 to 1 input channels
-						stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
-
-						// replace buffer pointer
-						i_data = (BYTE *)stream->in.monoBuffer;
-					}
-
-					// process
-					processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
-
-					// mix 1 to 2 output channels
-					if (stream->out.monoBuffer)
-						stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
-
-					// release host output buffer
-					if ((hr = IAudioRenderClient_ReleaseBuffer(stream->rclient, o_processed, 0)) != S_OK)
-						LogHostError(hr);
-				}
-				else
-				{
-					if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
-						LogHostError(hr); // be silent in shared mode, try again next time
-				}
-			}
-
-			// release host input buffer
-			if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->cclient, i_processed)) != S_OK)
-			{
-				LogHostError(hr);
-				break;
-			}
-		}
-#else
-		// Processing Loop
-		//sleep_ms = 1;
-		while (WaitForSingleObject(stream->hCloseRequest, sleep_ms) == WAIT_TIMEOUT)
-		{
-			UINT32 i_frames = 0, i_processed = 0;
-			BYTE *i_data = NULL, *o_data = NULL, *o_data_host = NULL;
-			DWORD i_flags = 0;
-			UINT32 o_frames = 0;
-			//BOOL repeat = FALSE;
-
-			// going below 1 msec resolution, switching between 1 ms and no waiting
-			//if (stream->in.shareMode == AUDCLNT_SHAREMODE_EXCLUSIVE)
-			//	sleep_ms = !sleep_ms;
-
-			// get available frames
-			if ((hr = PollGetOutputFramesAvailable(stream, &o_frames)) != S_OK)
-			{
-				LogHostError(hr);
-				break;
-			}
-
-			while (o_frames != 0)
-			{
-				// get host input buffer
-				if ((hr = IAudioCaptureClient_GetBuffer(stream->cclient, &i_data, &i_frames, &i_flags, NULL, NULL)) != S_OK)
-				{
-					if (hr == AUDCLNT_S_BUFFER_EMPTY)
-						break; // no data in capture buffer
-
-					LogHostError(hr);
-					break;
-				}
-
-				//PA_DEBUG(("full-duplex: o_frames[%d] i_frames[%d] repeat[%d]\n", o_frames, i_frames, repeat));
-				//repeat = TRUE;
-
-				// process equal ammount of frames
-				if (o_frames >= i_frames)
-				{
-					// process input ammount of frames
-					UINT32 o_processed = i_frames;
-
-					// get host output buffer
-					if ((hr = IAudioRenderClient_GetBuffer(stream->rclient, o_processed, &o_data)) == S_OK)
-					{
-						// processed amount of i_frames
-						i_processed = i_frames;
-						o_data_host = o_data;
-
-						// convert output mono
-						if (stream->out.monoMixer)
-						{
-							#define __DIV_8(v)  ((v) >> 3) //!< (v / 8)
-							UINT32 mono_frames_size = o_processed * __DIV_8(stream->out.wavex.Format.wBitsPerSample);
-							#undef __DIV_8
-							// expand buffer (one way only for better performance due to no calls to realloc)
-							if (mono_frames_size > stream->out.monoBufferSize)
-							{
-								stream->out.monoBuffer = realloc(stream->out.monoBuffer, (stream->out.monoBufferSize = mono_frames_size));
-								if (stream->out.monoBuffer == NULL)
-								{
-									LogPaError(paInsufficientMemory);
-									goto thread_error;
-								}
-							}
-
-							// replace buffer pointer
-							o_data = (BYTE *)stream->out.monoBuffer;
-						}
-
-						// convert input mono
-						if (stream->in.monoMixer)
-						{
-							#define __DIV_8(v)  ((v) >> 3) //!< (v / 8)
-							UINT32 mono_frames_size = i_processed * __DIV_8(stream->in.wavex.Format.wBitsPerSample);
-							#undef __DIV_8
-							// expand buffer (one way only for better performance due to no calls to realloc)
-							if (mono_frames_size > stream->in.monoBufferSize)
-							{
-								stream->in.monoBuffer = realloc(stream->in.monoBuffer, (stream->in.monoBufferSize = mono_frames_size));
-								if (stream->in.monoBuffer == NULL)
-								{
-									LogPaError(paInsufficientMemory);
-									goto thread_error;
-								}
-							}
-
-							// mix 2 to 1 input channels
-							stream->in.monoMixer(stream->in.monoBuffer, i_data, i_processed);
-
-							// replace buffer pointer
-							i_data = (BYTE *)stream->in.monoBuffer;
-						}
-
-						// process
-						processor[S_FULLDUPLEX].processor(i_data, i_processed, o_data, o_processed, processor[S_FULLDUPLEX].userData);
-
-						// mix 1 to 2 output channels
-						if (stream->out.monoBuffer)
-							stream->out.monoMixer(o_data_host, stream->out.monoBuffer, o_processed);
-
-						// release host output buffer
-						if ((hr = IAudioRenderClient_ReleaseBuffer(stream->rclient, o_processed, 0)) != S_OK)
-							LogHostError(hr);
-
-						o_frames -= o_processed;
-					}
-					else
-					{
-						if (stream->out.shareMode != AUDCLNT_SHAREMODE_SHARED)
-							LogHostError(hr); // be silent in shared mode, try again next time
-					}
-				}
-				else
-				{
-					i_processed = 0;
-					goto fd_release_buffer_in;
-				}
-
-fd_release_buffer_in:
-
-				// release host input buffer
-				if ((hr = IAudioCaptureClient_ReleaseBuffer(stream->cclient, i_processed)) != S_OK)
-				{
-					LogHostError(hr);
-					break;
-				}
-
-				// break processing, input hasn't been accumulated yet
-				if (i_processed == 0)
-					break;
-			}
-		}
-#endif
-	}
-
-thread_end:
-
-	// Process stop
-	_OnStreamStop(stream);
-
-	// Notify: thread exited
-	SetEvent(stream->hThreadExit);
-
-	// Notify: not running
-	stream->running = FALSE;
-
-	return 0;
-
-thread_error:
-
-	// Prevent deadlocking in Pa_StreamStart
-	SetEvent(stream->hThreadStart);
-
-	// Exit
-	goto thread_end;
-}
-
-//#endif //VC 2005
-
-
-
-
-#if 0
-			if(bFirst) {
-				float masteur;
-				hr = stream->outVol->GetMasterVolumeLevelScalar(&masteur);
-				if (hr != S_OK)
-					LogHostError(hr);
-				float chan1, chan2;
-				hr = stream->outVol->GetChannelVolumeLevelScalar(0, &chan1);
-				if (hr != S_OK)
-					LogHostError(hr);
-				hr = stream->outVol->GetChannelVolumeLevelScalar(1, &chan2);
-				if (hr != S_OK)
-					LogHostError(hr);
-
-				BOOL bMute;
-				hr = stream->outVol->GetMute(&bMute);
-				if (hr != S_OK)
-					LogHostError(hr);
-
-				stream->outVol->SetMasterVolumeLevelScalar(0.5, NULL);
-				stream->outVol->SetChannelVolumeLevelScalar(0, 0.5, NULL);
-				stream->outVol->SetChannelVolumeLevelScalar(1, 0.5, NULL);
-				stream->outVol->SetMute(FALSE, NULL);
-				bFirst = FALSE;
-			}
-#endif
diff --git a/portaudio/src/hostapi/wasapi/readme.txt b/portaudio/src/hostapi/wasapi/readme.txt
deleted file mode 100644
index 7d4082b6e..000000000
--- a/portaudio/src/hostapi/wasapi/readme.txt
+++ /dev/null
@@ -1,25 +0,0 @@
-**************
-* WASAPI API *
-**************
-
-----------------------------------------
-Microsoft Visual Studio 2005SP1/2008/10
-----------------------------------------
-No specific actions are needed to compile WASAPI API under Visual Studio.
-You are only required to install min. Windows Vista SDK (v6.0A) prior
-compilation.
-
-----------------------------------------
-MinGW (GCC 32-bit)/ MinGW64 (GCC 64-bit)
-----------------------------------------
-To compile under MinGW you are required to include 'mingw-include' directory
-which contains necessary files with WASAPI API. These files are modified
-in order to be compiled by MinGW compiler. These files are taken from 
-Windows Vista SDK (v6.0A). MinGW compilation is tested and proved to be
-fully working under 32-bit and 64-bit modes.
-MinGW   (32-bit) tested: gcc version 4.4.0 (GCC)
-MinGW64 (64-bit) tested: gcc version 4.4.4 20100226 (prerelease) (GCC)
-
-PortAudio
-/Dmitry Kostjuchenko/
-04.03.2010
\ No newline at end of file
diff --git a/portaudio/src/hostapi/wdmks/pa_win_wdmks.c b/portaudio/src/hostapi/wdmks/pa_win_wdmks.c
deleted file mode 100644
index caddfd52d..000000000
--- a/portaudio/src/hostapi/wdmks/pa_win_wdmks.c
+++ /dev/null
@@ -1,3304 +0,0 @@
-/*
- * $Id: pa_win_wdmks.c 1411 2009-05-14 14:37:37Z rossb $
- * PortAudio Windows WDM-KS interface
- *
- * Author: Andrew Baldwin
- * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2004 Andrew Baldwin, Ross Bencina, Phil Burk
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/** @file
- @ingroup hostapi_src
- @brief Portaudio WDM-KS host API.
-
- @note This is the implementation of the Portaudio host API using the
- Windows WDM/Kernel Streaming API in order to enable very low latency
- playback and recording on all modern Windows platforms (e.g. 2K, XP)
- Note: This API accesses the device drivers below the usual KMIXER
- component which is normally used to enable multi-client mixing and
- format conversion. That means that it will lock out all other users
- of a device for the duration of active stream using those devices
-*/
-
-#include <stdio.h>
-
-/* Debugging/tracing support */
-
-#define PA_LOGE_
-#define PA_LOGL_
-
-#ifdef __GNUC__
-    #include <initguid.h>
-    #define _WIN32_WINNT 0x0501
-    #define WINVER 0x0501
-#endif
-
-#include <string.h> /* strlen() */
-#include <assert.h>
-
-#include "pa_util.h"
-#include "pa_allocation.h"
-#include "pa_hostapi.h"
-#include "pa_stream.h"
-#include "pa_cpuload.h"
-#include "pa_process.h"
-#include "portaudio.h"
-#include "pa_debugprint.h"
-
-#include <windows.h>
-#include <winioctl.h>
-#include <process.h>
-
-#ifdef __GNUC__
-    #undef PA_LOGE_
-    #define PA_LOGE_ PA_DEBUG(("%s {\n",__FUNCTION__))
-    #undef PA_LOGL_
-    #define PA_LOGL_ PA_DEBUG(("} %s\n",__FUNCTION__))
-    /* These defines are set in order to allow the WIndows DirectX
-     * headers to compile with a GCC compiler such as MinGW
-     * NOTE: The headers may generate a few warning in GCC, but
-     * they should compile */
-    #define _INC_MMSYSTEM
-    #define _INC_MMREG
-    #define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */
-    #define DEFINE_GUID_THUNK(name,guid) DEFINE_GUID(name,guid)
-    #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK( n, STATIC_##n )
-    #if !defined( DEFINE_WAVEFORMATEX_GUID )
-        #define DEFINE_WAVEFORMATEX_GUID(x) (USHORT)(x), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71
-    #endif
-    #define  WAVE_FORMAT_ADPCM      0x0002
-    #define  WAVE_FORMAT_IEEE_FLOAT 0x0003
-    #define  WAVE_FORMAT_ALAW       0x0006
-    #define  WAVE_FORMAT_MULAW      0x0007
-    #define  WAVE_FORMAT_MPEG       0x0050
-    #define  WAVE_FORMAT_DRM        0x0009
-    #define DYNAMIC_GUID_THUNK(l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}
-    #define DYNAMIC_GUID(data) DYNAMIC_GUID_THUNK(data)
-#endif
-
-/* use CreateThread for CYGWIN, _beginthreadex for all others */
-#ifndef __CYGWIN__
-#define CREATE_THREAD (HANDLE)_beginthreadex( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
-#else
-#define CREATE_THREAD CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
-#endif
-
-/* use ExitThread for CYGWIN, _endthreadex for all others */
-#ifndef __CYGWIN__
-#define EXIT_THREAD _endthreadex(0)
-#else
-#define EXIT_THREAD ExitThread(0)
-#endif
-
-#ifdef _MSC_VER
-    #define NOMMIDS
-    #define DYNAMIC_GUID(data) {data}
-    #define _NTRTL_ /* Turn off default definition of DEFINE_GUIDEX */
-    #undef DEFINE_GUID
-    #define DEFINE_GUID(n,data) EXTERN_C const GUID n = {data}
-    #define DEFINE_GUID_THUNK(n,data) DEFINE_GUID(n,data)
-    #define DEFINE_GUIDEX(n) DEFINE_GUID_THUNK(n, STATIC_##n)
-#endif
-
-#include <mmreg.h>
-#include <ks.h>
-#include <ksmedia.h>
-#include <tchar.h>
-#include <assert.h>
-#include <stdio.h>
-
-/* These next definitions allow the use of the KSUSER DLL */
-typedef KSDDKAPI DWORD WINAPI KSCREATEPIN(HANDLE, PKSPIN_CONNECT, ACCESS_MASK, PHANDLE);
-extern HMODULE      DllKsUser;
-extern KSCREATEPIN* FunctionKsCreatePin;
-
-/* Forward definition to break circular type reference between pin and filter */
-struct __PaWinWdmFilter;
-typedef struct __PaWinWdmFilter PaWinWdmFilter;
-
-/* The Pin structure
- * A pin is an input or output node, e.g. for audio flow */
-typedef struct __PaWinWdmPin
-{
-    HANDLE                      handle;
-    PaWinWdmFilter*             parentFilter;
-    unsigned long               pinId;
-    KSPIN_CONNECT*              pinConnect;
-    unsigned long               pinConnectSize;
-    KSDATAFORMAT_WAVEFORMATEX*  ksDataFormatWfx;
-    KSPIN_COMMUNICATION         communication;
-    KSDATARANGE*                dataRanges;
-    KSMULTIPLE_ITEM*            dataRangesItem;
-    KSPIN_DATAFLOW              dataFlow;
-    KSPIN_CINSTANCES            instances;
-    unsigned long               frameSize;
-    int                         maxChannels;
-    unsigned long               formats;
-    int                         bestSampleRate;
-}
-PaWinWdmPin;
-
-/* The Filter structure
- * A filter has a number of pins and a "friendly name" */
-struct __PaWinWdmFilter
-{
-    HANDLE         handle;
-    int            pinCount;
-    PaWinWdmPin**  pins;
-    TCHAR          filterName[MAX_PATH];
-    TCHAR          friendlyName[MAX_PATH];
-    int            maxInputChannels;
-    int            maxOutputChannels;
-    unsigned long  formats;
-    int            usageCount;
-    int            bestSampleRate;
-};
-
-/* PaWinWdmHostApiRepresentation - host api datastructure specific to this implementation */
-typedef struct __PaWinWdmHostApiRepresentation
-{
-    PaUtilHostApiRepresentation  inheritedHostApiRep;
-    PaUtilStreamInterface        callbackStreamInterface;
-    PaUtilStreamInterface        blockingStreamInterface;
-
-    PaUtilAllocationGroup*       allocations;
-    PaWinWdmFilter**             filters;
-    int                          filterCount;
-}
-PaWinWdmHostApiRepresentation;
-
-typedef struct __PaWinWdmDeviceInfo
-{
-    PaDeviceInfo     inheritedDeviceInfo;
-    PaWinWdmFilter*  filter;
-}
-PaWinWdmDeviceInfo;
-
-typedef struct __DATAPACKET
-{
-    KSSTREAM_HEADER  Header;
-    OVERLAPPED       Signal;
-} DATAPACKET;
-
-/* PaWinWdmStream - a stream data structure specifically for this implementation */
-typedef struct __PaWinWdmStream
-{
-    PaUtilStreamRepresentation  streamRepresentation;
-    PaUtilCpuLoadMeasurer       cpuLoadMeasurer;
-    PaUtilBufferProcessor       bufferProcessor;
-
-    PaWinWdmPin*                recordingPin;
-    PaWinWdmPin*                playbackPin;
-    char*                       hostBuffer;
-    unsigned long               framesPerHostIBuffer;
-    unsigned long               framesPerHostOBuffer;
-    int                         bytesPerInputFrame;
-    int                         bytesPerOutputFrame;
-    int                         streamStarted;
-    int                         streamActive;
-    int                         streamStop;
-    int                         streamAbort;
-    int                         oldProcessPriority;
-    HANDLE                      streamThread;
-    HANDLE                      events[5];  /* 2 play + 2 record packets + abort events */
-    DATAPACKET                  packets[4]; /* 2 play + 2 record */
-    PaStreamFlags               streamFlags;
-    /* These values handle the case where the user wants to use fewer
-     * channels than the device has */
-    int                         userInputChannels;
-    int                         deviceInputChannels;
-    int                         userOutputChannels;
-    int                         deviceOutputChannels;
-    int                         inputSampleSize;
-    int                         outputSampleSize;
-}
-PaWinWdmStream;
-
-#include <setupapi.h>
-
-HMODULE      DllKsUser = NULL;
-KSCREATEPIN* FunctionKsCreatePin = NULL;
-
-/* prototypes for functions declared in this file */
-
-#ifdef __cplusplus
-extern "C"
-{
-#endif /* __cplusplus */
-
-PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-/* Low level I/O functions */
-static PaError WdmSyncIoctl(HANDLE handle,
-    unsigned long ioctlNumber,
-    void* inBuffer,
-    unsigned long inBufferCount,
-    void* outBuffer,
-    unsigned long outBufferCount,
-    unsigned long* bytesReturned);
-static PaError WdmGetPropertySimple(HANDLE handle,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    void* value,
-    unsigned long valueCount,
-    void* instance,
-    unsigned long instanceCount);
-static PaError WdmSetPropertySimple(HANDLE handle,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    void* value,
-    unsigned long valueCount,
-    void* instance,
-    unsigned long instanceCount);
-static PaError WdmGetPinPropertySimple(HANDLE  handle,
-    unsigned long pinId,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    void* value,
-    unsigned long valueCount);
-static PaError WdmGetPinPropertyMulti(HANDLE  handle,
-    unsigned long pinId,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    KSMULTIPLE_ITEM** ksMultipleItem);
-
-/** Pin management functions */
-static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error);
-static void PinFree(PaWinWdmPin* pin);
-static void PinClose(PaWinWdmPin* pin);
-static PaError PinInstantiate(PaWinWdmPin* pin);
-/*static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state); NOT USED */
-static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state);
-static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format);
-static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format);
-
-/* Filter management functions */
-static PaWinWdmFilter* FilterNew(
-    TCHAR* filterName,
-    TCHAR* friendlyName,
-    PaError* error);
-static void FilterFree(PaWinWdmFilter* filter);
-static PaWinWdmPin* FilterCreateRenderPin(
-    PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error);
-static PaWinWdmPin* FilterFindViableRenderPin(
-    PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error);
-static PaError FilterCanCreateRenderPin(
-    PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex);
-static PaWinWdmPin* FilterCreateCapturePin(
-    PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error);
-static PaWinWdmPin* FilterFindViableCapturePin(
-    PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error);
-static PaError FilterCanCreateCapturePin(
-    PaWinWdmFilter* filter,
-    const WAVEFORMATEX* pwfx);
-static PaError FilterUse(
-    PaWinWdmFilter* filter);
-static void FilterRelease(
-    PaWinWdmFilter* filter);
-
-/* Interface functions */
-static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
-static PaError IsFormatSupported(
-    struct PaUtilHostApiRepresentation *hostApi,
-    const PaStreamParameters *inputParameters,
-    const PaStreamParameters *outputParameters,
-    double sampleRate );
-static PaError OpenStream(
-    struct PaUtilHostApiRepresentation *hostApi,
-    PaStream** s,
-    const PaStreamParameters *inputParameters,
-    const PaStreamParameters *outputParameters,
-    double sampleRate,
-    unsigned long framesPerBuffer,
-    PaStreamFlags streamFlags,
-    PaStreamCallback *streamCallback,
-    void *userData );
-static PaError CloseStream( PaStream* stream );
-static PaError StartStream( PaStream *stream );
-static PaError StopStream( PaStream *stream );
-static PaError AbortStream( PaStream *stream );
-static PaError IsStreamStopped( PaStream *s );
-static PaError IsStreamActive( PaStream *stream );
-static PaTime GetStreamTime( PaStream *stream );
-static double GetStreamCpuLoad( PaStream* stream );
-static PaError ReadStream(
-    PaStream* stream,
-    void *buffer,
-    unsigned long frames );
-static PaError WriteStream(
-    PaStream* stream,
-    const void *buffer,
-    unsigned long frames );
-static signed long GetStreamReadAvailable( PaStream* stream );
-static signed long GetStreamWriteAvailable( PaStream* stream );
-
-/* Utility functions */
-static unsigned long GetWfexSize(const WAVEFORMATEX* wfex);
-static PaError BuildFilterList(PaWinWdmHostApiRepresentation* wdmHostApi);
-static BOOL PinWrite(HANDLE h, DATAPACKET* p);
-static BOOL PinRead(HANDLE h, DATAPACKET* p);
-static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples);
-static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples);
-static DWORD WINAPI ProcessingThread(LPVOID pParam);
-
-/* Function bodies */
-
-static unsigned long GetWfexSize(const WAVEFORMATEX* wfex)
-{
-    if( wfex->wFormatTag == WAVE_FORMAT_PCM )
-    {
-        return sizeof( WAVEFORMATEX );
-    }
-    else
-    {
-        return (sizeof( WAVEFORMATEX ) + wfex->cbSize);
-    }
-}
-
-/*
-Low level pin/filter access functions
-*/
-static PaError WdmSyncIoctl(
-    HANDLE handle,
-    unsigned long ioctlNumber,
-    void* inBuffer,
-    unsigned long inBufferCount,
-    void* outBuffer,
-    unsigned long outBufferCount,
-    unsigned long* bytesReturned)
-{
-    PaError result = paNoError;
-    OVERLAPPED overlapped;
-    int boolResult;
-    unsigned long dummyBytesReturned;
-    unsigned long error;
-
-    if( !bytesReturned )
-    {
-        /* User a dummy as the caller hasn't supplied one */
-        bytesReturned = &dummyBytesReturned;
-    }
-
-    FillMemory((void *)&overlapped,sizeof(overlapped),0);
-    overlapped.hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
-    if( !overlapped.hEvent )
-    {
-          result = paInsufficientMemory;
-        goto error;
-    }
-    overlapped.hEvent = (HANDLE)((DWORD_PTR)overlapped.hEvent | 0x1);
-
-    boolResult = DeviceIoControl(handle, ioctlNumber, inBuffer, inBufferCount,
-        outBuffer, outBufferCount, bytesReturned, &overlapped);
-    if( !boolResult )
-    {
-        error = GetLastError();
-        if( error == ERROR_IO_PENDING )
-        {
-            error = WaitForSingleObject(overlapped.hEvent,INFINITE);
-            if( error != WAIT_OBJECT_0 )
-            {
-                result = paUnanticipatedHostError;
-                goto error;
-            }
-        }
-        else if((( error == ERROR_INSUFFICIENT_BUFFER ) ||
-                  ( error == ERROR_MORE_DATA )) &&
-                  ( ioctlNumber == IOCTL_KS_PROPERTY ) &&
-                  ( outBufferCount == 0 ))
-        {
-            boolResult = TRUE;
-        }
-        else
-        {
-            result = paUnanticipatedHostError;
-        }
-    }
-    if( !boolResult )
-        *bytesReturned = 0;
-
-error:
-    if( overlapped.hEvent )
-    {
-            CloseHandle( overlapped.hEvent );
-    }
-    return result;
-}
-
-static PaError WdmGetPropertySimple(HANDLE handle,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    void* value,
-    unsigned long valueCount,
-    void* instance,
-    unsigned long instanceCount)
-{
-    PaError result;
-    KSPROPERTY* ksProperty;
-    unsigned long propertyCount;
-
-    propertyCount = sizeof(KSPROPERTY) + instanceCount;
-    ksProperty = (KSPROPERTY*)PaUtil_AllocateMemory( propertyCount );
-    if( !ksProperty )
-    {
-        return paInsufficientMemory;
-    }
-
-    FillMemory((void*)ksProperty,sizeof(ksProperty),0);
-    ksProperty->Set = *guidPropertySet;
-    ksProperty->Id = property;
-    ksProperty->Flags = KSPROPERTY_TYPE_GET;
-
-    if( instance )
-    {
-        memcpy( (void*)(((char*)ksProperty)+sizeof(KSPROPERTY)), instance, instanceCount );
-    }
-
-    result = WdmSyncIoctl(
-                handle,
-                IOCTL_KS_PROPERTY,
-                ksProperty,
-                propertyCount,
-                value,
-                valueCount,
-                NULL);
-
-    PaUtil_FreeMemory( ksProperty );
-    return result;
-}
-
-static PaError WdmSetPropertySimple(
-    HANDLE handle,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    void* value,
-    unsigned long valueCount,
-    void* instance,
-    unsigned long instanceCount)
-{
-    PaError result;
-    KSPROPERTY* ksProperty;
-    unsigned long propertyCount  = 0;
-
-    propertyCount = sizeof(KSPROPERTY) + instanceCount;
-    ksProperty = (KSPROPERTY*)PaUtil_AllocateMemory( propertyCount );
-    if( !ksProperty )
-    {
-        return paInsufficientMemory;
-    }
-
-    ksProperty->Set = *guidPropertySet;
-    ksProperty->Id = property;
-    ksProperty->Flags = KSPROPERTY_TYPE_SET;
-
-    if( instance )
-    {
-        memcpy((void*)((char*)ksProperty + sizeof(KSPROPERTY)), instance, instanceCount);
-    }
-
-    result = WdmSyncIoctl(
-                handle,
-                IOCTL_KS_PROPERTY,
-                ksProperty,
-                propertyCount,
-                value,
-                valueCount,
-                NULL);
-
-    PaUtil_FreeMemory( ksProperty );
-    return result;
-}
-
-static PaError WdmGetPinPropertySimple(
-    HANDLE  handle,
-    unsigned long pinId,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    void* value,
-    unsigned long valueCount)
-{
-    PaError result;
-
-    KSP_PIN ksPProp;
-    ksPProp.Property.Set = *guidPropertySet;
-    ksPProp.Property.Id = property;
-    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
-    ksPProp.PinId = pinId;
-    ksPProp.Reserved = 0;
-
-    result = WdmSyncIoctl(
-                handle,
-                IOCTL_KS_PROPERTY,
-                &ksPProp,
-                sizeof(KSP_PIN),
-                value,
-                valueCount,
-                NULL);
-
-    return result;
-}
-
-static PaError WdmGetPinPropertyMulti(
-    HANDLE handle,
-    unsigned long pinId,
-    const GUID* const guidPropertySet,
-    unsigned long property,
-    KSMULTIPLE_ITEM** ksMultipleItem)
-{
-    PaError result;
-    unsigned long multipleItemSize = 0;
-    KSP_PIN ksPProp;
-
-    ksPProp.Property.Set = *guidPropertySet;
-    ksPProp.Property.Id = property;
-    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
-    ksPProp.PinId = pinId;
-    ksPProp.Reserved = 0;
-
-    result = WdmSyncIoctl(
-                handle,
-                IOCTL_KS_PROPERTY,
-                &ksPProp.Property,
-                sizeof(KSP_PIN),
-                NULL,
-                0,
-                &multipleItemSize);
-    if( result != paNoError )
-    {
-        return result;
-    }
-
-    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
-    if( !*ksMultipleItem )
-    {
-        return paInsufficientMemory;
-    }
-
-    result = WdmSyncIoctl(
-                handle,
-                IOCTL_KS_PROPERTY,
-                &ksPProp,
-                sizeof(KSP_PIN),
-                (void*)*ksMultipleItem,
-                multipleItemSize,
-                NULL);
-
-    if( result != paNoError )
-    {
-        PaUtil_FreeMemory( ksMultipleItem );
-    }
-
-    return result;
-}
-
-
-/*
-Create a new pin object belonging to a filter
-The pin object holds all the configuration information about the pin
-before it is opened, and then the handle of the pin after is opened
-*/
-static PaWinWdmPin* PinNew(PaWinWdmFilter* parentFilter, unsigned long pinId, PaError* error)
-{
-    PaWinWdmPin* pin;
-    PaError result;
-    unsigned long i;
-    KSMULTIPLE_ITEM* item = NULL;
-    KSIDENTIFIER* identifier;
-    KSDATARANGE* dataRange;
-
-    PA_LOGE_;
-    PA_DEBUG(("Creating pin %d:\n",pinId));
-
-    /* Allocate the new PIN object */
-    pin = (PaWinWdmPin*)PaUtil_AllocateMemory( sizeof(PaWinWdmPin) );
-    if( !pin )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    /* Zero the pin object */
-    /* memset( (void*)pin, 0, sizeof(PaWinWdmPin) ); */
-
-    pin->parentFilter = parentFilter;
-    pin->pinId = pinId;
-
-    /* Allocate a connect structure */
-    pin->pinConnectSize = sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX);
-    pin->pinConnect = (KSPIN_CONNECT*)PaUtil_AllocateMemory( pin->pinConnectSize );
-    if( !pin->pinConnect )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    /* Configure the connect structure with default values */
-    pin->pinConnect->Interface.Set               = KSINTERFACESETID_Standard;
-    pin->pinConnect->Interface.Id                = KSINTERFACE_STANDARD_STREAMING;
-    pin->pinConnect->Interface.Flags             = 0;
-    pin->pinConnect->Medium.Set                  = KSMEDIUMSETID_Standard;
-    pin->pinConnect->Medium.Id                   = KSMEDIUM_TYPE_ANYINSTANCE;
-    pin->pinConnect->Medium.Flags                = 0;
-    pin->pinConnect->PinId                       = pinId;
-    pin->pinConnect->PinToHandle                 = NULL;
-    pin->pinConnect->Priority.PriorityClass      = KSPRIORITY_NORMAL;
-    pin->pinConnect->Priority.PrioritySubClass   = 1;
-    pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)(pin->pinConnect + 1);
-    pin->ksDataFormatWfx->DataFormat.FormatSize  = sizeof(KSDATAFORMAT_WAVEFORMATEX);
-    pin->ksDataFormatWfx->DataFormat.Flags       = 0;
-    pin->ksDataFormatWfx->DataFormat.Reserved    = 0;
-    pin->ksDataFormatWfx->DataFormat.MajorFormat = KSDATAFORMAT_TYPE_AUDIO;
-    pin->ksDataFormatWfx->DataFormat.SubFormat   = KSDATAFORMAT_SUBTYPE_PCM;
-    pin->ksDataFormatWfx->DataFormat.Specifier   = KSDATAFORMAT_SPECIFIER_WAVEFORMATEX;
-
-    pin->frameSize = 0; /* Unknown until we instantiate pin */
-
-    /* Get the COMMUNICATION property */
-    result = WdmGetPinPropertySimple(
-        parentFilter->handle,
-        pinId,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_COMMUNICATION,
-        &pin->communication,
-        sizeof(KSPIN_COMMUNICATION));
-    if( result != paNoError )
-        goto error;
-
-    if( /*(pin->communication != KSPIN_COMMUNICATION_SOURCE) &&*/
-         (pin->communication != KSPIN_COMMUNICATION_SINK) &&
-         (pin->communication != KSPIN_COMMUNICATION_BOTH) )
-    {
-        PA_DEBUG(("Not source/sink\n"));
-        result = paInvalidDevice;
-        goto error;
-    }
-
-    /* Get dataflow information */
-    result = WdmGetPinPropertySimple(
-        parentFilter->handle,
-        pinId,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_DATAFLOW,
-        &pin->dataFlow,
-        sizeof(KSPIN_DATAFLOW));
-
-    if( result != paNoError )
-        goto error;
-
-    /* Get the INTERFACE property list */
-    result = WdmGetPinPropertyMulti(
-        parentFilter->handle,
-        pinId,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_INTERFACES,
-        &item);
-
-    if( result != paNoError )
-        goto error;
-
-    identifier = (KSIDENTIFIER*)(item+1);
-
-    /* Check that at least one interface is STANDARD_STREAMING */
-    result = paUnanticipatedHostError;
-    for( i = 0; i < item->Count; i++ )
-    {
-        if( !memcmp( (void*)&identifier[i].Set, (void*)&KSINTERFACESETID_Standard, sizeof( GUID ) ) &&
-            ( identifier[i].Id == KSINTERFACE_STANDARD_STREAMING ) )
-        {
-            result = paNoError;
-            break;
-        }
-    }
-
-    if( result != paNoError )
-    {
-        PA_DEBUG(("No standard streaming\n"));
-        goto error;
-    }
-
-    /* Don't need interfaces any more */
-    PaUtil_FreeMemory( item );
-    item = NULL;
-
-    /* Get the MEDIUM properties list */
-    result = WdmGetPinPropertyMulti(
-        parentFilter->handle,
-        pinId,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_MEDIUMS,
-        &item);
-
-    if( result != paNoError )
-        goto error;
-
-    identifier = (KSIDENTIFIER*)(item+1); /* Not actually necessary... */
-
-    /* Check that at least one medium is STANDARD_DEVIO */
-    result = paUnanticipatedHostError;
-    for( i = 0; i < item->Count; i++ )
-    {
-        if( !memcmp( (void*)&identifier[i].Set, (void*)&KSMEDIUMSETID_Standard, sizeof( GUID ) ) &&
-           ( identifier[i].Id == KSMEDIUM_STANDARD_DEVIO ) )
-        {
-            result = paNoError;
-            break;
-        }
-    }
-
-    if( result != paNoError )
-    {
-        PA_DEBUG(("No standard devio\n"));
-        goto error;
-    }
-    /* Don't need mediums any more */
-    PaUtil_FreeMemory( item );
-    item = NULL;
-
-    /* Get DATARANGES */
-    result = WdmGetPinPropertyMulti(
-        parentFilter->handle,
-        pinId,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_DATARANGES,
-        &pin->dataRangesItem);
-
-    if( result != paNoError )
-        goto error;
-
-    pin->dataRanges = (KSDATARANGE*)(pin->dataRangesItem +1);
-
-    /* Check that at least one datarange supports audio */
-    result = paUnanticipatedHostError;
-    dataRange = pin->dataRanges;
-    pin->maxChannels = 0;
-    pin->bestSampleRate = 0;
-    pin->formats = 0;
-    for( i = 0; i <pin->dataRangesItem->Count; i++)
-    {
-        PA_DEBUG(("DR major format %x\n",*(unsigned long*)(&(dataRange->MajorFormat))));
-        /* Check that subformat is WAVEFORMATEX, PCM or WILDCARD */
-        if( IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat) ||
-            !memcmp((void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_PCM, sizeof ( GUID ) ) ||
-            ( !memcmp((void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_WILDCARD, sizeof ( GUID ) ) &&
-            ( !memcmp((void*)&dataRange->MajorFormat, (void*)&KSDATAFORMAT_TYPE_AUDIO, sizeof ( GUID ) ) ) ) )
-        {
-            result = paNoError;
-            /* Record the maximum possible channels with this pin */
-            PA_DEBUG(("MaxChannel: %d\n",pin->maxChannels));
-            if( (int)((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels > pin->maxChannels )
-            {
-                pin->maxChannels = ((KSDATARANGE_AUDIO*)dataRange)->MaximumChannels;
-                /*PA_DEBUG(("MaxChannel: %d\n",pin->maxChannels));*/
-            }
-            /* Record the formats (bit depths) that are supported */
-            if( ((KSDATARANGE_AUDIO*)dataRange)->MinimumBitsPerSample <= 16 )
-            {
-                pin->formats |= paInt16;
-                PA_DEBUG(("Format 16 bit supported\n"));
-            }
-            if( ((KSDATARANGE_AUDIO*)dataRange)->MaximumBitsPerSample >= 24 )
-            {
-                pin->formats |= paInt24;
-                PA_DEBUG(("Format 24 bit supported\n"));
-            }
-            if( ( pin->bestSampleRate != 48000) &&
-                (((KSDATARANGE_AUDIO*)dataRange)->MaximumSampleFrequency >= 48000) &&
-                (((KSDATARANGE_AUDIO*)dataRange)->MinimumSampleFrequency <= 48000) )
-            {
-                pin->bestSampleRate = 48000;
-                PA_DEBUG(("48kHz supported\n"));
-            }
-            else if(( pin->bestSampleRate != 48000) && ( pin->bestSampleRate != 44100 ) &&
-                (((KSDATARANGE_AUDIO*)dataRange)->MaximumSampleFrequency >= 44100) &&
-                (((KSDATARANGE_AUDIO*)dataRange)->MinimumSampleFrequency <= 44100) )
-            {
-                pin->bestSampleRate = 44100;
-                PA_DEBUG(("44.1kHz supported\n"));
-            }
-            else
-            {
-                pin->bestSampleRate = ((KSDATARANGE_AUDIO*)dataRange)->MaximumSampleFrequency;
-            }
-        }
-        dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);
-    }
-
-    if( result != paNoError )
-        goto error;
-
-    /* Get instance information */
-    result = WdmGetPinPropertySimple(
-        parentFilter->handle,
-        pinId,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_CINSTANCES,
-        &pin->instances,
-        sizeof(KSPIN_CINSTANCES));
-
-    if( result != paNoError )
-        goto error;
-
-    /* Success */
-    *error = paNoError;
-    PA_DEBUG(("Pin created successfully\n"));
-    PA_LOGL_;
-    return pin;
-
-error:
-    /*
-    Error cleanup
-    */
-    PaUtil_FreeMemory( item );
-    if( pin )
-    {
-        PaUtil_FreeMemory( pin->pinConnect );
-        PaUtil_FreeMemory( pin->dataRangesItem );
-        PaUtil_FreeMemory( pin );
-    }
-    *error = result;
-    PA_LOGL_;
-    return NULL;
-}
-
-/*
-Safely free all resources associated with the pin
-*/
-static void PinFree(PaWinWdmPin* pin)
-{
-    PA_LOGE_;
-    if( pin )
-    {
-        PinClose(pin);
-        if( pin->pinConnect )
-        {
-            PaUtil_FreeMemory( pin->pinConnect );
-        }
-        if( pin->dataRangesItem )
-        {
-            PaUtil_FreeMemory( pin->dataRangesItem );
-        }
-        PaUtil_FreeMemory( pin );
-    }
-    PA_LOGL_;
-}
-
-/*
-If the pin handle is open, close it
-*/
-static void PinClose(PaWinWdmPin* pin)
-{
-    PA_LOGE_;
-    if( pin == NULL )
-    {
-        PA_DEBUG(("Closing NULL pin!"));
-        PA_LOGL_;
-        return;
-    }
-    if( pin->handle != NULL )
-    {
-        PinSetState( pin, KSSTATE_PAUSE );
-        PinSetState( pin, KSSTATE_STOP );
-        CloseHandle( pin->handle );
-        pin->handle = NULL;
-        FilterRelease(pin->parentFilter);
-    }
-    PA_LOGL_;
-}
-
-/*
-Set the state of this (instantiated) pin
-*/
-static PaError PinSetState(PaWinWdmPin* pin, KSSTATE state)
-{
-    PaError result;
-
-    PA_LOGE_;
-    if( pin == NULL )
-        return paInternalError;
-    if( pin->handle == NULL )
-        return paInternalError;
-
-    result = WdmSetPropertySimple(
-        pin->handle,
-        &KSPROPSETID_Connection,
-        KSPROPERTY_CONNECTION_STATE,
-        &state,
-        sizeof(state),
-        NULL,
-        0);
-    PA_LOGL_;
-    return result;
-}
-
-static PaError PinInstantiate(PaWinWdmPin* pin)
-{
-    PaError result;
-    unsigned long createResult;
-    KSALLOCATOR_FRAMING ksaf;
-    KSALLOCATOR_FRAMING_EX ksafex;
-
-    PA_LOGE_;
-
-    if( pin == NULL )
-        return paInternalError;
-    if(!pin->pinConnect)
-        return paInternalError;
-
-    FilterUse(pin->parentFilter);
-
-    createResult = FunctionKsCreatePin(
-        pin->parentFilter->handle,
-        pin->pinConnect,
-        GENERIC_WRITE | GENERIC_READ,
-        &pin->handle
-        );
-
-    PA_DEBUG(("Pin create result = %x\n",createResult));
-    if( createResult != ERROR_SUCCESS )
-    {
-        FilterRelease(pin->parentFilter);
-        pin->handle = NULL;
-        return paInvalidDevice;
-    }
-
-    result = WdmGetPropertySimple(
-        pin->handle,
-        &KSPROPSETID_Connection,
-        KSPROPERTY_CONNECTION_ALLOCATORFRAMING,
-        &ksaf,
-        sizeof(ksaf),
-        NULL,
-        0);
-
-    if( result != paNoError )
-    {
-        result = WdmGetPropertySimple(
-            pin->handle,
-            &KSPROPSETID_Connection,
-            KSPROPERTY_CONNECTION_ALLOCATORFRAMING_EX,
-            &ksafex,
-            sizeof(ksafex),
-            NULL,
-            0);
-        if( result == paNoError )
-        {
-            pin->frameSize = ksafex.FramingItem[0].FramingRange.Range.MinFrameSize;
-        }
-    }
-    else
-    {
-        pin->frameSize = ksaf.FrameSize;
-    }
-
-    PA_LOGL_;
-
-    return paNoError;
-}
-
-/* NOT USED
-static PaError PinGetState(PaWinWdmPin* pin, KSSTATE* state)
-{
-    PaError result;
-
-    if( state == NULL )
-        return paInternalError;
-    if( pin == NULL )
-        return paInternalError;
-    if( pin->handle == NULL )
-        return paInternalError;
-
-    result = WdmGetPropertySimple(
-        pin->handle,
-        KSPROPSETID_Connection,
-        KSPROPERTY_CONNECTION_STATE,
-        state,
-        sizeof(KSSTATE),
-        NULL,
-        0);
-
-    return result;
-}
-*/
-static PaError PinSetFormat(PaWinWdmPin* pin, const WAVEFORMATEX* format)
-{
-    unsigned long size;
-    void* newConnect;
-
-    PA_LOGE_;
-
-    if( pin == NULL )
-        return paInternalError;
-    if( format == NULL )
-        return paInternalError;
-
-    size = GetWfexSize(format) + sizeof(KSPIN_CONNECT) + sizeof(KSDATAFORMAT_WAVEFORMATEX) - sizeof(WAVEFORMATEX);
-
-    if( pin->pinConnectSize != size )
-    {
-        newConnect = PaUtil_AllocateMemory( size );
-        if( newConnect == NULL )
-            return paInsufficientMemory;
-        memcpy( newConnect, (void*)pin->pinConnect, min(pin->pinConnectSize,size) );
-        PaUtil_FreeMemory( pin->pinConnect );
-        pin->pinConnect = (KSPIN_CONNECT*)newConnect;
-        pin->pinConnectSize = size;
-        pin->ksDataFormatWfx = (KSDATAFORMAT_WAVEFORMATEX*)((KSPIN_CONNECT*)newConnect + 1);
-        pin->ksDataFormatWfx->DataFormat.FormatSize = size - sizeof(KSPIN_CONNECT);
-    }
-
-    memcpy( (void*)&(pin->ksDataFormatWfx->WaveFormatEx), format, GetWfexSize(format) );
-    pin->ksDataFormatWfx->DataFormat.SampleSize = (unsigned short)(format->nChannels * (format->wBitsPerSample / 8));
-
-    PA_LOGL_;
-
-    return paNoError;
-}
-
-static PaError PinIsFormatSupported(PaWinWdmPin* pin, const WAVEFORMATEX* format)
-{
-    KSDATARANGE_AUDIO* dataRange;
-    unsigned long count;
-    GUID guid = DYNAMIC_GUID( DEFINE_WAVEFORMATEX_GUID(format->wFormatTag) );
-    PaError result = paInvalidDevice;
-
-    PA_LOGE_;
-
-    if( format->wFormatTag == WAVE_FORMAT_EXTENSIBLE )
-    {
-        guid = ((WAVEFORMATEXTENSIBLE*)format)->SubFormat;
-    }
-    dataRange = (KSDATARANGE_AUDIO*)pin->dataRanges;
-    for(count = 0; count<pin->dataRangesItem->Count; count++)
-    {
-        if(( !memcmp(&(dataRange->DataRange.MajorFormat),&KSDATAFORMAT_TYPE_AUDIO,sizeof(GUID)) ) ||
-           ( !memcmp(&(dataRange->DataRange.MajorFormat),&KSDATAFORMAT_TYPE_WILDCARD,sizeof(GUID)) ))
-        {
-            /* This is an audio or wildcard datarange... */
-            if(( !memcmp(&(dataRange->DataRange.SubFormat),&KSDATAFORMAT_SUBTYPE_WILDCARD,sizeof(GUID)) ) ||
-                ( !memcmp(&(dataRange->DataRange.SubFormat),&guid,sizeof(GUID)) ))
-            {
-                if(( !memcmp(&(dataRange->DataRange.Specifier),&KSDATAFORMAT_SPECIFIER_WILDCARD,sizeof(GUID)) ) ||
-                  ( !memcmp(&(dataRange->DataRange.Specifier),&KSDATAFORMAT_SPECIFIER_WAVEFORMATEX,sizeof(GUID) )))
-                {
-
-                    PA_DEBUG(("Pin:%x, DataRange:%d\n",(void*)pin,count));
-                    PA_DEBUG(("\tFormatSize:%d, SampleSize:%d\n",dataRange->DataRange.FormatSize,dataRange->DataRange.SampleSize));
-                    PA_DEBUG(("\tMaxChannels:%d\n",dataRange->MaximumChannels));
-                    PA_DEBUG(("\tBits:%d-%d\n",dataRange->MinimumBitsPerSample,dataRange->MaximumBitsPerSample));
-                    PA_DEBUG(("\tSampleRate:%d-%d\n",dataRange->MinimumSampleFrequency,dataRange->MaximumSampleFrequency));
-
-                    if( dataRange->MaximumChannels < format->nChannels )
-                    {
-                        result = paInvalidChannelCount;
-                        continue;
-                    }
-                    if( dataRange->MinimumBitsPerSample > format->wBitsPerSample )
-                    {
-                        result = paSampleFormatNotSupported;
-                        continue;
-                    }
-                    if( dataRange->MaximumBitsPerSample < format->wBitsPerSample )
-                    {
-                        result = paSampleFormatNotSupported;
-                        continue;
-                    }
-                    if( dataRange->MinimumSampleFrequency > format->nSamplesPerSec )
-                    {
-                        result = paInvalidSampleRate;
-                        continue;
-                    }
-                    if( dataRange->MaximumSampleFrequency < format->nSamplesPerSec )
-                    {
-                        result = paInvalidSampleRate;
-                        continue;
-                    }
-                    /* Success! */
-                    PA_LOGL_;
-                    return paNoError;
-                }
-            }
-        }
-        dataRange = (KSDATARANGE_AUDIO*)( ((char*)dataRange) + dataRange->DataRange.FormatSize);
-    }
-
-    PA_LOGL_;
-
-    return result;
-}
-
-/**
- * Create a new filter object
- */
-static PaWinWdmFilter* FilterNew(TCHAR* filterName, TCHAR* friendlyName, PaError* error)
-{
-    PaWinWdmFilter* filter;
-    PaError result;
-    int pinId;
-    int valid;
-
-
-    /* Allocate the new filter object */
-    filter = (PaWinWdmFilter*)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter) );
-    if( !filter )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    /* Zero the filter object - done by AllocateMemory */
-    /* memset( (void*)filter, 0, sizeof(PaWinWdmFilter) ); */
-
-    /* Copy the filter name */
-    _tcsncpy(filter->filterName, filterName, MAX_PATH);
-
-    /* Copy the friendly name */
-    _tcsncpy(filter->friendlyName, friendlyName, MAX_PATH);
-
-    /* Open the filter handle */
-    result = FilterUse(filter);
-    if( result != paNoError )
-    {
-        goto error;
-    }
-
-    /* Get pin count */
-    result = WdmGetPinPropertySimple
-        (
-        filter->handle,
-        0,
-        &KSPROPSETID_Pin,
-        KSPROPERTY_PIN_CTYPES,
-        &filter->pinCount,
-        sizeof(filter->pinCount)
-        );
-
-    if( result != paNoError)
-    {
-        goto error;
-    }
-
-    /* Allocate pointer array to hold the pins */
-    filter->pins = (PaWinWdmPin**)PaUtil_AllocateMemory( sizeof(PaWinWdmPin*) * filter->pinCount );
-    if( !filter->pins )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    /* Create all the pins we can */
-    filter->maxInputChannels = 0;
-    filter->maxOutputChannels = 0;
-    filter->bestSampleRate = 0;
-
-    valid = 0;
-    for(pinId = 0; pinId < filter->pinCount; pinId++)
-    {
-        /* Create the pin with this Id */
-        PaWinWdmPin* newPin;
-        newPin = PinNew(filter, pinId, &result);
-        if( result == paInsufficientMemory )
-            goto error;
-        if( newPin != NULL )
-        {
-            filter->pins[pinId] = newPin;
-            valid = 1;
-
-            /* Get the max output channel count */
-            if(( newPin->dataFlow == KSPIN_DATAFLOW_IN ) &&
-                (( newPin->communication == KSPIN_COMMUNICATION_SINK) ||
-                 ( newPin->communication == KSPIN_COMMUNICATION_BOTH)))
-            {
-                if(newPin->maxChannels > filter->maxOutputChannels)
-                    filter->maxOutputChannels = newPin->maxChannels;
-                filter->formats |= newPin->formats;
-            }
-            /* Get the max input channel count */
-            if(( newPin->dataFlow == KSPIN_DATAFLOW_OUT ) &&
-                (( newPin->communication == KSPIN_COMMUNICATION_SINK) ||
-                 ( newPin->communication == KSPIN_COMMUNICATION_BOTH)))
-            {
-                if(newPin->maxChannels > filter->maxInputChannels)
-                    filter->maxInputChannels = newPin->maxChannels;
-                filter->formats |= newPin->formats;
-            }
-
-            if(newPin->bestSampleRate > filter->bestSampleRate)
-            {
-                filter->bestSampleRate = newPin->bestSampleRate;
-            }
-        }
-    }
-
-    if(( filter->maxInputChannels == 0) && ( filter->maxOutputChannels == 0))
-    {
-        /* No input or output... not valid */
-        valid = 0;
-    }
-
-    if( !valid )
-    {
-        /* No valid pin was found on this filter so we destroy it */
-        result = paDeviceUnavailable;
-        goto error;
-    }
-
-    /* Close the filter handle for now
-     * It will be opened later when needed */
-    FilterRelease(filter);
-
-    *error = paNoError;
-    return filter;
-
-error:
-    /*
-    Error cleanup
-    */
-    if( filter )
-    {
-        for( pinId = 0; pinId < filter->pinCount; pinId++ )
-            PinFree(filter->pins[pinId]);
-        PaUtil_FreeMemory( filter->pins );
-        if( filter->handle )
-            CloseHandle( filter->handle );
-        PaUtil_FreeMemory( filter );
-    }
-    *error = result;
-    return NULL;
-}
-
-/**
- * Free a previously created filter
- */
-static void FilterFree(PaWinWdmFilter* filter)
-{
-    int pinId;
-    PA_LOGL_;
-    if( filter )
-    {
-        for( pinId = 0; pinId < filter->pinCount; pinId++ )
-            PinFree(filter->pins[pinId]);
-        PaUtil_FreeMemory( filter->pins );
-        if( filter->handle )
-            CloseHandle( filter->handle );
-        PaUtil_FreeMemory( filter );
-    }
-    PA_LOGE_;
-}
-
-/**
- * Reopen the filter handle if necessary so it can be used
- **/
-static PaError FilterUse(PaWinWdmFilter* filter)
-{
-    assert( filter );
-
-    PA_LOGE_;
-    if( filter->handle == NULL )
-    {
-        /* Open the filter */
-        filter->handle = CreateFile(
-            filter->filterName,
-            GENERIC_READ | GENERIC_WRITE,
-            0,
-            NULL,
-            OPEN_EXISTING,
-            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
-            NULL);
-
-        if( filter->handle == NULL )
-        {
-            return paDeviceUnavailable;
-        }
-    }
-    filter->usageCount++;
-    PA_LOGL_;
-    return paNoError;
-}
-
-/**
- * Release the filter handle if nobody is using it
- **/
-static void FilterRelease(PaWinWdmFilter* filter)
-{
-    assert( filter );
-    assert( filter->usageCount > 0 );
-
-    PA_LOGE_;
-    filter->usageCount--;
-    if( filter->usageCount == 0 )
-    {
-        if( filter->handle != NULL )
-        {
-            CloseHandle( filter->handle );
-            filter->handle = NULL;
-        }
-    }
-    PA_LOGL_;
-}
-
-/**
- * Create a render (playback) Pin using the supplied format
- **/
-static PaWinWdmPin* FilterCreateRenderPin(PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error)
-{
-    PaError result;
-    PaWinWdmPin* pin;
-
-    assert( filter );
-
-    pin = FilterFindViableRenderPin(filter,wfex,&result);
-    if(!pin)
-    {
-        goto error;
-    }
-    result = PinSetFormat(pin,wfex);
-    if( result != paNoError )
-    {
-        goto error;
-    }
-    result = PinInstantiate(pin);
-    if( result != paNoError )
-    {
-        goto error;
-    }
-
-    *error = paNoError;
-    return pin;
-
-error:
-    *error = result;
-    return NULL;
-}
-
-/**
- * Find a pin that supports the given format
- **/
-static PaWinWdmPin* FilterFindViableRenderPin(PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error)
-{
-    int pinId;
-    PaWinWdmPin*  pin;
-    PaError result = paDeviceUnavailable;
-    *error = paNoError;
-
-    assert( filter );
-
-    for( pinId = 0; pinId<filter->pinCount; pinId++ )
-    {
-        pin = filter->pins[pinId];
-        if( pin != NULL )
-        {
-            if(( pin->dataFlow == KSPIN_DATAFLOW_IN ) &&
-                (( pin->communication == KSPIN_COMMUNICATION_SINK) ||
-                 ( pin->communication == KSPIN_COMMUNICATION_BOTH)))
-            {
-                result = PinIsFormatSupported( pin, wfex );
-                if( result == paNoError )
-                {
-                    return pin;
-                }
-            }
-        }
-    }
-
-    *error = result;
-    return NULL;
-}
-
-/**
- * Check if there is a pin that should playback
- * with the supplied format
- **/
-static PaError FilterCanCreateRenderPin(PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex)
-{
-    PaWinWdmPin* pin;
-    PaError result;
-
-    assert ( filter );
-
-    pin = FilterFindViableRenderPin(filter,wfex,&result);
-    /* result will be paNoError if pin found
-     * or else an error code indicating what is wrong with the format
-     **/
-    return result;
-}
-
-/**
- * Create a capture (record) Pin using the supplied format
- **/
-static PaWinWdmPin* FilterCreateCapturePin(PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error)
-{
-    PaError result;
-    PaWinWdmPin* pin;
-
-    assert( filter );
-
-    pin = FilterFindViableCapturePin(filter,wfex,&result);
-    if(!pin)
-    {
-        goto error;
-    }
-
-    result = PinSetFormat(pin,wfex);
-    if( result != paNoError )
-    {
-        goto error;
-    }
-
-    result = PinInstantiate(pin);
-    if( result != paNoError )
-    {
-        goto error;
-    }
-
-    *error = paNoError;
-    return pin;
-
-error:
-    *error = result;
-    return NULL;
-}
-
-/**
- * Find a capture pin that supports the given format
- **/
-static PaWinWdmPin* FilterFindViableCapturePin(PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex,
-    PaError* error)
-{
-    int pinId;
-    PaWinWdmPin*  pin;
-    PaError result = paDeviceUnavailable;
-    *error = paNoError;
-
-    assert( filter );
-
-    for( pinId = 0; pinId<filter->pinCount; pinId++ )
-    {
-        pin = filter->pins[pinId];
-        if( pin != NULL )
-        {
-            if(( pin->dataFlow == KSPIN_DATAFLOW_OUT ) &&
-                (( pin->communication == KSPIN_COMMUNICATION_SINK) ||
-                 ( pin->communication == KSPIN_COMMUNICATION_BOTH)))
-            {
-                result = PinIsFormatSupported( pin, wfex );
-                if( result == paNoError )
-                {
-                    return pin;
-                }
-            }
-        }
-    }
-
-    *error = result;
-    return NULL;
-}
-
-/**
- * Check if there is a pin that should playback
- * with the supplied format
- **/
-static PaError FilterCanCreateCapturePin(PaWinWdmFilter* filter,
-    const WAVEFORMATEX* wfex)
-{
-    PaWinWdmPin* pin;
-    PaError result;
-
-    assert ( filter );
-
-    pin = FilterFindViableCapturePin(filter,wfex,&result);
-    /* result will be paNoError if pin found
-     * or else an error code indicating what is wrong with the format
-     **/
-    return result;
-}
-
-/**
- * Build the list of available filters
- * Use the SetupDi API to enumerate all devices in the KSCATEGORY_AUDIO which 
- * have a KSCATEGORY_RENDER or KSCATEGORY_CAPTURE alias. For each of these 
- * devices initialise a PaWinWdmFilter structure by calling our NewFilter() 
- * function. We enumerate devices twice, once to count how many there are, 
- * and once to initialize the PaWinWdmFilter structures.
- */
-static PaError BuildFilterList(PaWinWdmHostApiRepresentation* wdmHostApi)
-{
-    PaError result = paNoError;
-    HDEVINFO handle = NULL;
-    int device;
-    int invalidDevices;
-    int slot;
-    SP_DEVICE_INTERFACE_DATA interfaceData;
-    SP_DEVICE_INTERFACE_DATA aliasData;
-    SP_DEVINFO_DATA devInfoData;
-    int noError;
-    const int sizeInterface = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR));
-    unsigned char interfaceDetailsArray[sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) + (MAX_PATH * sizeof(WCHAR))];
-    SP_DEVICE_INTERFACE_DETAIL_DATA* devInterfaceDetails = (SP_DEVICE_INTERFACE_DETAIL_DATA*)interfaceDetailsArray;
-    TCHAR friendlyName[MAX_PATH];
-    HKEY hkey;
-    DWORD sizeFriendlyName;
-    DWORD type;
-    PaWinWdmFilter* newFilter;
-    GUID* category = (GUID*)&KSCATEGORY_AUDIO;
-    GUID* alias_render = (GUID*)&KSCATEGORY_RENDER;
-    GUID* alias_capture = (GUID*)&KSCATEGORY_CAPTURE;
-    DWORD hasAlias;
-
-    PA_LOGE_;
-
-    devInterfaceDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
-
-    /* Open a handle to search for devices (filters) */
-    handle = SetupDiGetClassDevs(category,NULL,NULL,DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
-    if( handle == NULL )
-    {
-        return paUnanticipatedHostError;
-    }
-    PA_DEBUG(("Setup called\n"));
-
-    /* First let's count the number of devices so we can allocate a list */
-    invalidDevices = 0;
-    for( device = 0;;device++ )
-    {
-        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
-        interfaceData.Reserved = 0;
-        aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
-        aliasData.Reserved = 0;
-        noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);
-        PA_DEBUG(("Enum called\n"));
-        if( !noError )
-            break; /* No more devices */
-
-        /* Check this one has the render or capture alias */
-        hasAlias = 0;
-        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);
-        PA_DEBUG(("noError = %d\n",noError));
-        if(noError)
-        {
-            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
-            {
-                PA_DEBUG(("Device %d has render alias\n",device));
-                hasAlias |= 1; /* Has render alias */
-            }
-            else
-            {
-                PA_DEBUG(("Device %d has no render alias\n",device));
-            }
-        }
-        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);
-        if(noError)
-        {
-            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
-            {
-                PA_DEBUG(("Device %d has capture alias\n",device));
-                hasAlias |= 2; /* Has capture alias */
-            }
-            else
-            {
-                PA_DEBUG(("Device %d has no capture alias\n",device));
-            }
-        }
-        if(!hasAlias)
-            invalidDevices++; /* This was not a valid capture or render audio device */
-
-    }
-    /* Remember how many there are */
-    wdmHostApi->filterCount = device-invalidDevices;
-
-    PA_DEBUG(("Interfaces found: %d\n",device-invalidDevices));
-
-    /* Now allocate the list of pointers to devices */
-    wdmHostApi->filters  = (PaWinWdmFilter**)PaUtil_AllocateMemory( sizeof(PaWinWdmFilter*) * device );
-    if( !wdmHostApi->filters )
-    {
-        if(handle != NULL)
-            SetupDiDestroyDeviceInfoList(handle);
-        return paInsufficientMemory;
-    }
-
-    /* Now create filter objects for each interface found */
-    slot = 0;
-    for( device = 0;;device++ )
-    {
-        interfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
-        interfaceData.Reserved = 0;
-        aliasData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
-        aliasData.Reserved = 0;
-        devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
-        devInfoData.Reserved = 0;
-
-        noError = SetupDiEnumDeviceInterfaces(handle,NULL,category,device,&interfaceData);
-        if( !noError )
-            break; /* No more devices */
-
-        /* Check this one has the render or capture alias */
-        hasAlias = 0;
-        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_render,&aliasData);
-        if(noError)
-        {
-            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
-            {
-                PA_DEBUG(("Device %d has render alias\n",device));
-                hasAlias |= 1; /* Has render alias */
-            }
-        }
-        noError = SetupDiGetDeviceInterfaceAlias(handle,&interfaceData,alias_capture,&aliasData);
-        if(noError)
-        {
-            if(aliasData.Flags && (!(aliasData.Flags & SPINT_REMOVED)))
-            {
-                PA_DEBUG(("Device %d has capture alias\n",device));
-                hasAlias |= 2; /* Has capture alias */
-            }
-        }
-        if(!hasAlias)
-            continue; /* This was not a valid capture or render audio device */
-
-        noError = SetupDiGetDeviceInterfaceDetail(handle,&interfaceData,devInterfaceDetails,sizeInterface,NULL,&devInfoData);
-        if( noError )
-        {
-            /* Try to get the "friendly name" for this interface */
-            sizeFriendlyName = sizeof(friendlyName);
-            /* Fix contributed by Ben Allison
-             * Removed KEY_SET_VALUE from flags on following call
-             * as its causes failure when running without admin rights
-             * and it was not required */
-            hkey=SetupDiOpenDeviceInterfaceRegKey(handle,&interfaceData,0,KEY_QUERY_VALUE);
-            if(hkey!=INVALID_HANDLE_VALUE)
-            {
-                noError = RegQueryValueEx(hkey,TEXT("FriendlyName"),0,&type,(BYTE*)friendlyName,&sizeFriendlyName);
-                if( noError == ERROR_SUCCESS )
-                {
-                    PA_DEBUG(("Interface %d, Name: %s\n",device,friendlyName));
-                    RegCloseKey(hkey);
-                }
-                else
-                {
-                    friendlyName[0] = 0;
-                }
-            }
-            newFilter = FilterNew(devInterfaceDetails->DevicePath,friendlyName,&result);
-            if( result == paNoError )
-            {
-                PA_DEBUG(("Filter created\n"));
-                wdmHostApi->filters[slot] = newFilter;
-                slot++;
-            }
-            else
-            {
-                PA_DEBUG(("Filter NOT created\n"));
-                /* As there are now less filters than we initially thought
-                 * we must reduce the count by one */
-                wdmHostApi->filterCount--;
-            }
-        }
-    }
-
-    /* Clean up */
-    if(handle != NULL)
-        SetupDiDestroyDeviceInfoList(handle);
-
-    return paNoError;
-}
-
-PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
-{
-    PaError result = paNoError;
-    int i, deviceCount;
-    PaWinWdmHostApiRepresentation *wdmHostApi;
-    PaWinWdmDeviceInfo *deviceInfoArray;
-    PaWinWdmFilter* pFilter;
-    PaWinWdmDeviceInfo *wdmDeviceInfo;
-    PaDeviceInfo *deviceInfo;
-
-    PA_LOGE_;
-
-    /*
-    Attempt to load the KSUSER.DLL without which we cannot create pins
-    We will unload this on termination
-    */
-    if(DllKsUser == NULL)
-    {
-        DllKsUser = LoadLibrary(TEXT("ksuser.dll"));
-        if(DllKsUser == NULL)
-            goto error;
-    }
-
-    FunctionKsCreatePin = (KSCREATEPIN*)GetProcAddress(DllKsUser, "KsCreatePin");
-    if(FunctionKsCreatePin == NULL)
-        goto error;
-
-    wdmHostApi = (PaWinWdmHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinWdmHostApiRepresentation) );
-    if( !wdmHostApi )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    wdmHostApi->allocations = PaUtil_CreateAllocationGroup();
-    if( !wdmHostApi->allocations )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-
-    result = BuildFilterList( wdmHostApi );
-    if( result != paNoError )
-    {
-        goto error;
-    }
-    deviceCount = wdmHostApi->filterCount;
-
-    *hostApi = &wdmHostApi->inheritedHostApiRep;
-    (*hostApi)->info.structVersion = 1;
-    (*hostApi)->info.type = paWDMKS;
-    (*hostApi)->info.name = "Windows WDM-KS";
-    (*hostApi)->info.defaultInputDevice = paNoDevice;
-    (*hostApi)->info.defaultOutputDevice = paNoDevice;
-
-    if( deviceCount > 0 )
-    {
-        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
-               wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo*) * deviceCount );
-        if( !(*hostApi)->deviceInfos )
-        {
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-        /* allocate all device info structs in a contiguous block */
-        deviceInfoArray = (PaWinWdmDeviceInfo*)PaUtil_GroupAllocateMemory(
-                wdmHostApi->allocations, sizeof(PaWinWdmDeviceInfo) * deviceCount );
-        if( !deviceInfoArray )
-        {
-            result = paInsufficientMemory;
-            goto error;
-        }
-
-        for( i=0; i < deviceCount; ++i )
-        {
-            wdmDeviceInfo = &deviceInfoArray[i];
-            deviceInfo = &wdmDeviceInfo->inheritedDeviceInfo;
-            pFilter = wdmHostApi->filters[i];
-            if( pFilter == NULL )
-                continue;
-            wdmDeviceInfo->filter = pFilter;
-            deviceInfo->structVersion = 2;
-            deviceInfo->hostApi = hostApiIndex;
-            deviceInfo->name = (char*)pFilter->friendlyName;
-            PA_DEBUG(("Device found name: %s\n",(char*)pFilter->friendlyName));
-            deviceInfo->maxInputChannels = pFilter->maxInputChannels;
-            if(deviceInfo->maxInputChannels > 0)
-            {
-                /* Set the default input device to the first device we find with
-                 * more than zero input channels
-                 **/
-                if((*hostApi)->info.defaultInputDevice == paNoDevice)
-                {
-                    (*hostApi)->info.defaultInputDevice = i;
-                }
-            }
-
-            deviceInfo->maxOutputChannels = pFilter->maxOutputChannels;
-            if(deviceInfo->maxOutputChannels > 0)
-            {
-                /* Set the default output device to the first device we find with
-                 * more than zero output channels
-                 **/
-                if((*hostApi)->info.defaultOutputDevice == paNoDevice)
-                {
-                    (*hostApi)->info.defaultOutputDevice = i;
-                }
-            }
-
-            /* These low values are not very useful because
-             * a) The lowest latency we end up with can depend on many factors such
-             *    as the device buffer sizes/granularities, sample rate, channels and format
-             * b) We cannot know the device buffer sizes until we try to open/use it at
-             *    a particular setting
-             * So: we give 512x48000Hz frames as the default low input latency
-             **/
-            deviceInfo->defaultLowInputLatency = (512.0/48000.0);
-            deviceInfo->defaultLowOutputLatency = (512.0/48000.0);
-            deviceInfo->defaultHighInputLatency = (4096.0/48000.0);
-            deviceInfo->defaultHighOutputLatency = (4096.0/48000.0);
-            deviceInfo->defaultSampleRate = (double)(pFilter->bestSampleRate);
-
-            (*hostApi)->deviceInfos[i] = deviceInfo;
-        }
-    }
-
-    (*hostApi)->info.deviceCount = deviceCount;
-
-    (*hostApi)->Terminate = Terminate;
-    (*hostApi)->OpenStream = OpenStream;
-    (*hostApi)->IsFormatSupported = IsFormatSupported;
-
-    PaUtil_InitializeStreamInterface( &wdmHostApi->callbackStreamInterface, CloseStream, StartStream,
-                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
-                                      GetStreamTime, GetStreamCpuLoad,
-                                      PaUtil_DummyRead, PaUtil_DummyWrite,
-                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
-
-    PaUtil_InitializeStreamInterface( &wdmHostApi->blockingStreamInterface, CloseStream, StartStream,
-                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,
-                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
-                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
-
-    PA_LOGL_;
-    return result;
-
-error:
-    if( DllKsUser != NULL )
-    {
-        FreeLibrary( DllKsUser );
-        DllKsUser = NULL;
-    }
-
-    if( wdmHostApi )
-    {
-        PaUtil_FreeMemory( wdmHostApi->filters );
-        if( wdmHostApi->allocations )
-        {
-            PaUtil_FreeAllAllocations( wdmHostApi->allocations );
-            PaUtil_DestroyAllocationGroup( wdmHostApi->allocations );
-        }
-        PaUtil_FreeMemory( wdmHostApi );
-    }
-    PA_LOGL_;
-    return result;
-}
-
-
-static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
-{
-    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
-    int i;
-    PA_LOGE_;
-
-    if( wdmHostApi->filters )
-    {
-        for( i=0; i<wdmHostApi->filterCount; i++)
-        {
-            if( wdmHostApi->filters[i] != NULL )
-            {
-                FilterFree( wdmHostApi->filters[i] );
-                wdmHostApi->filters[i] = NULL;
-            }
-        }
-    }
-    PaUtil_FreeMemory( wdmHostApi->filters );
-    if( wdmHostApi->allocations )
-    {
-        PaUtil_FreeAllAllocations( wdmHostApi->allocations );
-        PaUtil_DestroyAllocationGroup( wdmHostApi->allocations );
-    }
-    PaUtil_FreeMemory( wdmHostApi );
-    PA_LOGL_;
-}
-
-static void FillWFEXT( WAVEFORMATEXTENSIBLE* pwfext, PaSampleFormat sampleFormat, double sampleRate, int channelCount)
-{
-    PA_LOGE_;
-    PA_DEBUG(( "sampleFormat = %lx\n" , sampleFormat ));
-    PA_DEBUG(( "sampleRate = %f\n" , sampleRate ));
-    PA_DEBUG(( "chanelCount = %d\n", channelCount ));
-
-    pwfext->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
-    pwfext->Format.nChannels = channelCount;
-    pwfext->Format.nSamplesPerSec = (int)sampleRate;
-    if(channelCount == 1)
-        pwfext->dwChannelMask = KSAUDIO_SPEAKER_DIRECTOUT;
-    else
-        pwfext->dwChannelMask = KSAUDIO_SPEAKER_STEREO;
-    if(sampleFormat == paFloat32)
-    {
-        pwfext->Format.nBlockAlign = channelCount * 4;
-        pwfext->Format.wBitsPerSample = 32;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 32;
-        pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
-    }
-    else if(sampleFormat == paInt32)
-    {
-        pwfext->Format.nBlockAlign = channelCount * 4;
-        pwfext->Format.wBitsPerSample = 32;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 32;
-        pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
-    }
-    else if(sampleFormat == paInt24)
-    {
-        pwfext->Format.nBlockAlign = channelCount * 3;
-        pwfext->Format.wBitsPerSample = 24;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 24;
-        pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
-    }
-    else if(sampleFormat == paInt16)
-    {
-        pwfext->Format.nBlockAlign = channelCount * 2;
-        pwfext->Format.wBitsPerSample = 16;
-        pwfext->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
-        pwfext->Samples.wValidBitsPerSample = 16;
-        pwfext->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
-    }
-    pwfext->Format.nAvgBytesPerSec = pwfext->Format.nSamplesPerSec * pwfext->Format.nBlockAlign;
-
-    PA_LOGL_;
-}
-
-static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
-                                  const PaStreamParameters *inputParameters,
-                                  const PaStreamParameters *outputParameters,
-                                  double sampleRate )
-{
-    int inputChannelCount, outputChannelCount;
-    PaSampleFormat inputSampleFormat, outputSampleFormat;
-    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
-    PaWinWdmFilter* pFilter;
-    int result = paFormatIsSupported;
-    WAVEFORMATEXTENSIBLE wfx;
-
-    PA_LOGE_;
-
-    if( inputParameters )
-    {
-        inputChannelCount = inputParameters->channelCount;
-        inputSampleFormat = inputParameters->sampleFormat;
-
-        /* all standard sample formats are supported by the buffer adapter,
-            this implementation doesn't support any custom sample formats */
-        if( inputSampleFormat & paCustomFormat )
-            return paSampleFormatNotSupported;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-
-        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that input device can support inputChannelCount */
-        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
-            return paInvalidChannelCount;
-
-        /* validate inputStreamInfo */
-        if( inputParameters->hostApiSpecificStreamInfo )
-            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
-
-        /* Check that the input format is supported */
-        FillWFEXT(&wfx,paInt16,sampleRate,inputChannelCount);
-
-        pFilter = wdmHostApi->filters[inputParameters->device];
-        result = FilterCanCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx);
-        if( result != paNoError )
-        {
-            /* Try a WAVE_FORMAT_PCM instead */
-            wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
-            wfx.Format.cbSize = 0;
-            wfx.Samples.wValidBitsPerSample = 0;
-            wfx.dwChannelMask = 0;
-            wfx.SubFormat = GUID_NULL;
-            result = FilterCanCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx);
-            if( result != paNoError )
-                 return result;
-        }
-    }
-    else
-    {
-        inputChannelCount = 0;
-    }
-
-    if( outputParameters )
-    {
-        outputChannelCount = outputParameters->channelCount;
-        outputSampleFormat = outputParameters->sampleFormat;
-
-        /* all standard sample formats are supported by the buffer adapter,
-            this implementation doesn't support any custom sample formats */
-        if( outputSampleFormat & paCustomFormat )
-            return paSampleFormatNotSupported;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-
-        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that output device can support outputChannelCount */
-        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
-            return paInvalidChannelCount;
-
-        /* validate outputStreamInfo */
-        if( outputParameters->hostApiSpecificStreamInfo )
-            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
-
-        /* Check that the output format is supported */
-        FillWFEXT(&wfx,paInt16,sampleRate,outputChannelCount);
-
-        pFilter = wdmHostApi->filters[outputParameters->device];
-        result = FilterCanCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx);
-        if( result != paNoError )
-        {
-            /* Try a WAVE_FORMAT_PCM instead */
-            wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
-            wfx.Format.cbSize = 0;
-            wfx.Samples.wValidBitsPerSample = 0;
-            wfx.dwChannelMask = 0;
-            wfx.SubFormat = GUID_NULL;
-            result = FilterCanCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx);
-            if( result != paNoError )
-                 return result;
-        }
-
-    }
-    else
-    {
-        outputChannelCount = 0;
-    }
-
-    /*
-        IMPLEMENT ME:
-
-            - if a full duplex stream is requested, check that the combination
-                of input and output parameters is supported if necessary
-
-            - check that the device supports sampleRate
-
-        Because the buffer adapter handles conversion between all standard
-        sample formats, the following checks are only required if paCustomFormat
-        is implemented, or under some other unusual conditions.
-
-            - check that input device can support inputSampleFormat, or that
-                we have the capability to convert from inputSampleFormat to
-                a native format
-
-            - check that output device can support outputSampleFormat, or that
-                we have the capability to convert from outputSampleFormat to
-                a native format
-    */
-    if((inputChannelCount == 0)&&(outputChannelCount == 0))
-            result = paSampleFormatNotSupported; /* Not right error */
-
-    PA_LOGL_;
-    return result;
-}
-
-/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
-
-static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
-                           PaStream** s,
-                           const PaStreamParameters *inputParameters,
-                           const PaStreamParameters *outputParameters,
-                           double sampleRate,
-                           unsigned long framesPerBuffer,
-                           PaStreamFlags streamFlags,
-                           PaStreamCallback *streamCallback,
-                           void *userData )
-{
-    PaError result = paNoError;
-    PaWinWdmHostApiRepresentation *wdmHostApi = (PaWinWdmHostApiRepresentation*)hostApi;
-    PaWinWdmStream *stream = 0;
-    /* unsigned long framesPerHostBuffer; these may not be equivalent for all implementations */
-    PaSampleFormat inputSampleFormat, outputSampleFormat;
-    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
-    int userInputChannels,userOutputChannels;
-    int size;
-    PaWinWdmFilter* pFilter;
-    WAVEFORMATEXTENSIBLE wfx;
-
-    PA_LOGE_;
-    PA_DEBUG(("OpenStream:sampleRate = %f\n",sampleRate));
-    PA_DEBUG(("OpenStream:framesPerBuffer = %lu\n",framesPerBuffer));
-
-    if( inputParameters )
-    {
-        userInputChannels = inputParameters->channelCount;
-        inputSampleFormat = inputParameters->sampleFormat;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-
-        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that input device can support stream->userInputChannels */
-        if( userInputChannels > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
-            return paInvalidChannelCount;
-
-        /* validate inputStreamInfo */
-        if( inputParameters->hostApiSpecificStreamInfo )
-            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
-
-    }
-    else
-    {
-        userInputChannels = 0;
-        inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */
-    }
-
-    if( outputParameters )
-    {
-        userOutputChannels = outputParameters->channelCount;
-        outputSampleFormat = outputParameters->sampleFormat;
-
-        /* unless alternate device specification is supported, reject the use of
-            paUseHostApiSpecificDeviceSpecification */
-
-        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
-            return paInvalidDevice;
-
-        /* check that output device can support stream->userInputChannels */
-        if( userOutputChannels > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
-            return paInvalidChannelCount;
-
-        /* validate outputStreamInfo */
-        if( outputParameters->hostApiSpecificStreamInfo )
-            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
-
-    }
-    else
-    {
-        userOutputChannels = 0;
-        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */
-    }
-
-    /* validate platform specific flags */
-    if( (streamFlags & paPlatformSpecificFlags) != 0 )
-        return paInvalidFlag; /* unexpected platform specific flag */
-
-    stream = (PaWinWdmStream*)PaUtil_AllocateMemory( sizeof(PaWinWdmStream) );
-    if( !stream )
-    {
-        result = paInsufficientMemory;
-        goto error;
-    }
-    /* Zero the stream object */
-    /* memset((void*)stream,0,sizeof(PaWinWdmStream)); */
-
-    if( streamCallback )
-    {
-        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
-                                               &wdmHostApi->callbackStreamInterface, streamCallback, userData );
-    }
-    else
-    {
-        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
-                                               &wdmHostApi->blockingStreamInterface, streamCallback, userData );
-    }
-
-    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
-
-    /* Instantiate the input pin if necessary */
-    if(userInputChannels > 0)
-    {
-        result = paSampleFormatNotSupported;
-        pFilter = wdmHostApi->filters[inputParameters->device];
-        stream->userInputChannels = userInputChannels;
-
-        if(((inputSampleFormat & ~paNonInterleaved) & pFilter->formats) != 0)
-        {   /* inputSampleFormat is supported, so try to use it */
-            hostInputSampleFormat = inputSampleFormat;
-            FillWFEXT(&wfx, hostInputSampleFormat, sampleRate, stream->userInputChannels);
-            stream->bytesPerInputFrame = wfx.Format.nBlockAlign;
-            stream->recordingPin = FilterCreateCapturePin(pFilter, (const WAVEFORMATEX*)&wfx, &result);
-            stream->deviceInputChannels = stream->userInputChannels;
-        }
-        
-        if(result != paNoError)
-        {   /* Search through all PaSampleFormats to find one that works */
-            hostInputSampleFormat = paFloat32;
-
-            do {
-                FillWFEXT(&wfx, hostInputSampleFormat, sampleRate, stream->userInputChannels);
-                stream->bytesPerInputFrame = wfx.Format.nBlockAlign;
-                stream->recordingPin = FilterCreateCapturePin(pFilter, (const WAVEFORMATEX*)&wfx, &result);
-                stream->deviceInputChannels = stream->userInputChannels;
-                
-                if(stream->recordingPin == NULL) result = paSampleFormatNotSupported;
-                if(result != paNoError)    hostInputSampleFormat <<= 1;
-            }
-            while(result != paNoError && hostInputSampleFormat <= paUInt8);
-        }
-
-        if(result != paNoError)
-        {    /* None of the PaSampleFormats worked.  Set the hostInputSampleFormat to the best fit
-             * and try a PCM format.
-             **/
-            hostInputSampleFormat =
-                PaUtil_SelectClosestAvailableFormat( pFilter->formats, inputSampleFormat );
-
-            /* Try a WAVE_FORMAT_PCM instead */
-            wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
-            wfx.Format.cbSize = 0;
-            wfx.Samples.wValidBitsPerSample = 0;
-            wfx.dwChannelMask = 0;
-            wfx.SubFormat = GUID_NULL;
-            stream->recordingPin = FilterCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx,&result);
-            if(stream->recordingPin == NULL) result = paSampleFormatNotSupported;
-        }
-
-        if( result != paNoError )
-        {
-            /* Some or all KS devices can only handle the exact number of channels
-             * they specify. But PortAudio clients expect to be able to
-             * at least specify mono I/O on a multi-channel device
-             * If this is the case, then we will do the channel mapping internally
-             **/
-            if( stream->userInputChannels < pFilter->maxInputChannels )
-            {
-                FillWFEXT(&wfx,hostInputSampleFormat,sampleRate,pFilter->maxInputChannels);
-                stream->bytesPerInputFrame = wfx.Format.nBlockAlign;
-                stream->recordingPin = FilterCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx,&result);
-                stream->deviceInputChannels = pFilter->maxInputChannels;
-
-                if( result != paNoError )
-                {
-                    /* Try a WAVE_FORMAT_PCM instead */
-                    wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
-                    wfx.Format.cbSize = 0;
-                    wfx.Samples.wValidBitsPerSample = 0;
-                    wfx.dwChannelMask = 0;
-                    wfx.SubFormat = GUID_NULL;
-                    stream->recordingPin = FilterCreateCapturePin(pFilter,(const WAVEFORMATEX*)&wfx,&result);
-                }
-            }
-        }
-
-        if(stream->recordingPin == NULL)
-        {
-            goto error;
-        }
-
-        switch(hostInputSampleFormat)
-        {
-            case paInt16: stream->inputSampleSize = 2; break;
-            case paInt24: stream->inputSampleSize = 3; break;
-            case paInt32:
-            case paFloat32:    stream->inputSampleSize = 4; break;
-        }
-
-        stream->recordingPin->frameSize /= stream->bytesPerInputFrame;
-        PA_DEBUG(("Pin output frames: %d\n",stream->recordingPin->frameSize));
-    }
-    else
-    {
-        stream->recordingPin = NULL;
-        stream->bytesPerInputFrame = 0;
-    }
-
-    /* Instantiate the output pin if necessary */
-    if(userOutputChannels > 0)
-    {
-        result = paSampleFormatNotSupported;
-        pFilter = wdmHostApi->filters[outputParameters->device];
-        stream->userOutputChannels = userOutputChannels;
-
-        if(((outputSampleFormat & ~paNonInterleaved) & pFilter->formats) != 0)
-        {
-            hostOutputSampleFormat = outputSampleFormat;
-            FillWFEXT(&wfx,hostOutputSampleFormat,sampleRate,stream->userOutputChannels);
-            stream->bytesPerOutputFrame = wfx.Format.nBlockAlign;
-            stream->playbackPin = FilterCreateRenderPin(pFilter,(WAVEFORMATEX*)&wfx,&result);
-            stream->deviceOutputChannels = stream->userOutputChannels;
-        }
-
-        if(result != paNoError)
-        {
-            hostOutputSampleFormat = paFloat32;
-
-            do {
-                FillWFEXT(&wfx,hostOutputSampleFormat,sampleRate,stream->userOutputChannels);
-                stream->bytesPerOutputFrame = wfx.Format.nBlockAlign;
-                stream->playbackPin = FilterCreateRenderPin(pFilter,(WAVEFORMATEX*)&wfx,&result);
-                stream->deviceOutputChannels = stream->userOutputChannels;
-
-                if(stream->playbackPin == NULL) result = paSampleFormatNotSupported;
-                if(result != paNoError)    hostOutputSampleFormat <<= 1;
-            }
-            while(result != paNoError && hostOutputSampleFormat <= paUInt8);
-        }
-
-        if(result != paNoError)
-        {
-            hostOutputSampleFormat =
-                PaUtil_SelectClosestAvailableFormat( pFilter->formats, outputSampleFormat );
-       
-            /* Try a WAVE_FORMAT_PCM instead */
-            wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
-            wfx.Format.cbSize = 0;
-            wfx.Samples.wValidBitsPerSample = 0;
-            wfx.dwChannelMask = 0;
-            wfx.SubFormat = GUID_NULL;
-            stream->playbackPin = FilterCreateRenderPin(pFilter,(WAVEFORMATEX*)&wfx,&result);
-            if(stream->playbackPin == NULL) result = paSampleFormatNotSupported;
-        }
-            
-        if( result != paNoError )
-        {
-            /* Some or all KS devices can only handle the exact number of channels
-             * they specify. But PortAudio clients expect to be able to
-             * at least specify mono I/O on a multi-channel device
-             * If this is the case, then we will do the channel mapping internally
-             **/
-            if( stream->userOutputChannels < pFilter->maxOutputChannels )
-            {
-                FillWFEXT(&wfx,hostOutputSampleFormat,sampleRate,pFilter->maxOutputChannels);
-                stream->bytesPerOutputFrame = wfx.Format.nBlockAlign;
-                stream->playbackPin = FilterCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx,&result);
-                stream->deviceOutputChannels = pFilter->maxOutputChannels;
-                if( result != paNoError )
-                {
-                    /* Try a WAVE_FORMAT_PCM instead */
-                    wfx.Format.wFormatTag = WAVE_FORMAT_PCM;
-                    wfx.Format.cbSize = 0;
-                    wfx.Samples.wValidBitsPerSample = 0;
-                    wfx.dwChannelMask = 0;
-                    wfx.SubFormat = GUID_NULL;
-                    stream->playbackPin = FilterCreateRenderPin(pFilter,(const WAVEFORMATEX*)&wfx,&result);
-                }
-            }
-        }
-
-        if(stream->playbackPin == NULL)
-        {
-            goto error;
-        }
-
-        switch(hostOutputSampleFormat)
-        {
-            case paInt16: stream->outputSampleSize = 2; break;
-            case paInt24: stream->outputSampleSize = 3; break;
-            case paInt32:
-            case paFloat32: stream->outputSampleSize = 4; break;
-        }
-
-        stream->playbackPin->frameSize /= stream->bytesPerOutputFrame;
-        PA_DEBUG(("Pin output frames: %d\n",stream->playbackPin->frameSize));
-    }
-    else
-    {
-        stream->playbackPin = NULL;
-        stream->bytesPerOutputFrame = 0;
-    }
-
-    /* Calculate the framesPerHostXxxxBuffer size based upon the suggested latency values */
-
-    /* Record the buffer length */
-    if(inputParameters)
-    {
-        /* Calculate the frames from the user's value - add a bit to round up */
-            stream->framesPerHostIBuffer = (unsigned long)((inputParameters->suggestedLatency*sampleRate)+0.0001);
-        if(stream->framesPerHostIBuffer > (unsigned long)sampleRate)
-        { /* Upper limit is 1 second */
-              stream->framesPerHostIBuffer = (unsigned long)sampleRate;
-        }
-        else if(stream->framesPerHostIBuffer < stream->recordingPin->frameSize)
-        {
-              stream->framesPerHostIBuffer = stream->recordingPin->frameSize;
-        }
-        PA_DEBUG(("Input frames chosen:%ld\n",stream->framesPerHostIBuffer));
-    }
-
-    if(outputParameters)
-    {
-        /* Calculate the frames from the user's value - add a bit to round up */
-        stream->framesPerHostOBuffer = (unsigned long)((outputParameters->suggestedLatency*sampleRate)+0.0001);
-        if(stream->framesPerHostOBuffer > (unsigned long)sampleRate)
-        { /* Upper limit is 1 second */
-                  stream->framesPerHostOBuffer = (unsigned long)sampleRate;
-        }
-        else if(stream->framesPerHostOBuffer < stream->playbackPin->frameSize)
-        {
-              stream->framesPerHostOBuffer = stream->playbackPin->frameSize;
-        }
-        PA_DEBUG(("Output frames chosen:%ld\n",stream->framesPerHostOBuffer));
-    }
-
-    /* Host buffer size is bounded to the largest of the input and output
-    frame sizes */
-
-    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
-              stream->userInputChannels, inputSampleFormat, hostInputSampleFormat,
-              stream->userOutputChannels, outputSampleFormat, hostOutputSampleFormat,
-              sampleRate, streamFlags, framesPerBuffer,
-              max(stream->framesPerHostOBuffer,stream->framesPerHostIBuffer),
-              paUtilBoundedHostBufferSize,
-              streamCallback, userData );
-    if( result != paNoError )
-        goto error;
-
-    stream->streamRepresentation.streamInfo.inputLatency =
-            ((double)stream->framesPerHostIBuffer) / sampleRate;
-    stream->streamRepresentation.streamInfo.outputLatency =
-            ((double)stream->framesPerHostOBuffer) / sampleRate;
-    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
-
-      PA_DEBUG(("BytesPerInputFrame = %d\n",stream->bytesPerInputFrame));
-      PA_DEBUG(("BytesPerOutputFrame = %d\n",stream->bytesPerOutputFrame));
-
-    /* Allocate all the buffers for host I/O */
-    size = 2 * (stream->framesPerHostIBuffer*stream->bytesPerInputFrame +  stream->framesPerHostOBuffer*stream->bytesPerOutputFrame);
-    PA_DEBUG(("Buffer size = %d\n",size));
-    stream->hostBuffer = (char*)PaUtil_AllocateMemory(size);
-    PA_DEBUG(("Buffer allocated\n"));
-    if( !stream->hostBuffer )
-    {
-        PA_DEBUG(("Cannot allocate host buffer!\n"));
-        result = paInsufficientMemory;
-        goto error;
-    }
-    PA_DEBUG(("Buffer start = %p\n",stream->hostBuffer));
-    /* memset(stream->hostBuffer,0,size); */
-
-    /* Set up the packets */
-    stream->events[0] = CreateEvent(NULL, FALSE, FALSE, NULL);
-    ResetEvent(stream->events[0]); /* Record buffer 1 */
-    stream->events[1] = CreateEvent(NULL, FALSE, FALSE, NULL);
-    ResetEvent(stream->events[1]); /* Record buffer 2 */
-    stream->events[2] = CreateEvent(NULL, FALSE, FALSE, NULL);
-    ResetEvent(stream->events[2]); /* Play buffer 1 */
-    stream->events[3] = CreateEvent(NULL, FALSE, FALSE, NULL);
-    ResetEvent(stream->events[3]); /* Play buffer 2 */
-    stream->events[4] = CreateEvent(NULL, FALSE, FALSE, NULL);
-    ResetEvent(stream->events[4]); /* Abort event */
-    if(stream->userInputChannels > 0)
-    {
-        DATAPACKET *p = &(stream->packets[0]);
-        p->Signal.hEvent = stream->events[0];
-        p->Header.Data = stream->hostBuffer;
-        p->Header.FrameExtent = stream->framesPerHostIBuffer*stream->bytesPerInputFrame;
-        p->Header.DataUsed = 0;
-        p->Header.Size = sizeof(p->Header);
-        p->Header.PresentationTime.Numerator = 1;
-        p->Header.PresentationTime.Denominator = 1;
-
-        p = &(stream->packets[1]);
-        p->Signal.hEvent = stream->events[1];
-        p->Header.Data = stream->hostBuffer + stream->framesPerHostIBuffer*stream->bytesPerInputFrame;
-        p->Header.FrameExtent = stream->framesPerHostIBuffer*stream->bytesPerInputFrame;
-        p->Header.DataUsed = 0;
-        p->Header.Size = sizeof(p->Header);
-        p->Header.PresentationTime.Numerator = 1;
-        p->Header.PresentationTime.Denominator = 1;
-    }
-    if(stream->userOutputChannels > 0)
-    {
-        DATAPACKET *p = &(stream->packets[2]);
-        p->Signal.hEvent = stream->events[2];
-        p->Header.Data = stream->hostBuffer + 2*stream->framesPerHostIBuffer*stream->bytesPerInputFrame;
-        p->Header.FrameExtent = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame;
-        p->Header.DataUsed = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame;
-        p->Header.Size = sizeof(p->Header);
-        p->Header.PresentationTime.Numerator = 1;
-        p->Header.PresentationTime.Denominator = 1;
-    
-        p = &(stream->packets[3]);
-        p->Signal.hEvent = stream->events[3];
-        p->Header.Data = stream->hostBuffer + 2*stream->framesPerHostIBuffer*stream->bytesPerInputFrame + stream->framesPerHostOBuffer*stream->bytesPerOutputFrame;
-        p->Header.FrameExtent = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame;
-        p->Header.DataUsed = stream->framesPerHostOBuffer*stream->bytesPerOutputFrame;
-        p->Header.Size = sizeof(p->Header);
-        p->Header.PresentationTime.Numerator = 1;
-        p->Header.PresentationTime.Denominator = 1;
-    }
-
-    stream->streamStarted = 0;
-    stream->streamActive = 0;
-    stream->streamStop = 0;
-    stream->streamAbort = 0;
-    stream->streamFlags = streamFlags;
-    stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;
-
-    *s = (PaStream*)stream;
-
-    PA_LOGL_;
-    return result;
-
-error:
-    size = 5;
-    while(size--)
-    {
-        if(stream->events[size] != NULL)
-        {
-            CloseHandle(stream->events[size]);
-            stream->events[size] = NULL;
-        }
-    }
-    if(stream->hostBuffer)
-        PaUtil_FreeMemory( stream->hostBuffer );
-
-    if(stream->playbackPin)
-        PinClose(stream->playbackPin);
-    if(stream->recordingPin)
-        PinClose(stream->recordingPin);
-
-    if( stream )
-        PaUtil_FreeMemory( stream );
-
-    PA_LOGL_;
-    return result;
-}
-
-/*
-    When CloseStream() is called, the multi-api layer ensures that
-    the stream has already been stopped or aborted.
-*/
-static PaError CloseStream( PaStream* s )
-{
-    PaError result = paNoError;
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    int size;
-
-    PA_LOGE_;
-
-    assert(!stream->streamStarted);
-    assert(!stream->streamActive);
-
-    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
-    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
-    size = 5;
-    while(size--)
-    {
-        if(stream->events[size] != NULL)
-        {
-            CloseHandle(stream->events[size]);
-            stream->events[size] = NULL;
-        }
-    }
-    if(stream->hostBuffer)
-        PaUtil_FreeMemory( stream->hostBuffer );
-
-    if(stream->playbackPin)
-        PinClose(stream->playbackPin);
-    if(stream->recordingPin)
-        PinClose(stream->recordingPin);
-
-    PaUtil_FreeMemory( stream );
-
-    PA_LOGL_;
-    return result;
-}
-
-/*
-Write the supplied packet to the pin
-Asynchronous
-Should return false on success
-*/
-static BOOL PinWrite(HANDLE h, DATAPACKET* p)
-{
-    unsigned long cbReturned = 0;
-    return DeviceIoControl(h,IOCTL_KS_WRITE_STREAM,NULL,0,
-                            &p->Header,p->Header.Size,&cbReturned,&p->Signal);
-}
-
-/*
-Read to the supplied packet from the pin
-Asynchronous
-Should return false on success
-*/
-static BOOL PinRead(HANDLE h, DATAPACKET* p)
-{
-    unsigned long cbReturned = 0;
-    return DeviceIoControl(h,IOCTL_KS_READ_STREAM,NULL,0,
-                            &p->Header,p->Header.Size,&cbReturned,&p->Signal);
-}
-
-/*
-Copy the first interleaved channel of 16 bit data to the other channels
-*/
-static void DuplicateFirstChannelInt16(void* buffer, int channels, int samples)
-{
-    unsigned short* data = (unsigned short*)buffer;
-    int channel;
-    unsigned short sourceSample;
-    while( samples-- )
-    {
-        sourceSample = *data++;
-        channel = channels-1;
-        while( channel-- )
-        {
-            *data++ = sourceSample;
-        }
-    }
-}
-
-/*
-Copy the first interleaved channel of 24 bit data to the other channels
-*/
-static void DuplicateFirstChannelInt24(void* buffer, int channels, int samples)
-{
-    unsigned char* data = (unsigned char*)buffer;
-    int channel;
-    unsigned char sourceSample[3];
-    while( samples-- )
-    {
-        sourceSample[0] = data[0];
-        sourceSample[1] = data[1];
-        sourceSample[2] = data[2];
-        data += 3;
-        channel = channels-1;
-        while( channel-- )
-        {
-            data[0] = sourceSample[0];
-            data[1] = sourceSample[1];
-            data[2] = sourceSample[2];
-            data += 3;
-        }
-    }
-}
-
-/*
-Copy the first interleaved channel of 32 bit data to the other channels
-*/
-static void DuplicateFirstChannelInt32(void* buffer, int channels, int samples)
-{
-    unsigned long* data = (unsigned long*)buffer;
-    int channel;
-    unsigned long sourceSample;
-    while( samples-- )
-    {
-        sourceSample = *data++;
-        channel = channels-1;
-        while( channel-- )
-        {
-            *data++ = sourceSample;
-        }
-    }
-}
-
-static DWORD WINAPI ProcessingThread(LPVOID pParam)
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)pParam;
-    PaStreamCallbackTimeInfo ti;
-    int cbResult = paContinue;
-    int inbuf = 0;
-    int outbuf = 0;
-    int pending = 0;
-    PaError result;
-    unsigned long wait;
-    unsigned long eventSignaled;
-    int fillPlaybuf = 0;
-    int emptyRecordbuf = 0;
-    int framesProcessed;
-    unsigned long timeout;
-    int i;
-    int doChannelCopy;
-    int priming = 0;
-    PaStreamCallbackFlags underover = 0;
-
-    PA_LOGE_;
-
-    ti.inputBufferAdcTime = 0.0;
-    ti.currentTime = 0.0;
-    ti.outputBufferDacTime = 0.0;
-
-    /* Get double buffering going */
-
-    /* Submit buffers */
-    if(stream->playbackPin)
-    {
-        result = PinSetState(stream->playbackPin, KSSTATE_RUN);
-
-        PA_DEBUG(("play state run = %d;",(int)result));
-        SetEvent(stream->events[outbuf+2]);
-        outbuf = (outbuf+1)&1;
-        SetEvent(stream->events[outbuf+2]);
-        outbuf = (outbuf+1)&1;
-        pending += 2;
-        priming += 4;
-    }
-    if(stream->recordingPin)
-    {
-        result = PinSetState(stream->recordingPin, KSSTATE_RUN);
-
-        PA_DEBUG(("recording state run = %d;",(int)result));
-        PinRead(stream->recordingPin->handle,&stream->packets[inbuf]);
-        inbuf = (inbuf+1)&1; /* Increment and wrap */
-        PinRead(stream->recordingPin->handle,&stream->packets[inbuf]);
-        inbuf = (inbuf+1)&1; /* Increment and wrap */
-        /* FIXME - do error checking */
-        pending += 2;
-    }
-    PA_DEBUG(("Out buffer len:%f\n",(2000*stream->framesPerHostOBuffer) / stream->streamRepresentation.streamInfo.sampleRate));
-    PA_DEBUG(("In buffer len:%f\n",(2000*stream->framesPerHostIBuffer) / stream->streamRepresentation.streamInfo.sampleRate));
-    timeout = max(
-       ((2000*(DWORD)stream->framesPerHostOBuffer) / (DWORD)stream->streamRepresentation.streamInfo.sampleRate),
-       ((2000*(DWORD)stream->framesPerHostIBuffer) / (DWORD)stream->streamRepresentation.streamInfo.sampleRate));
-    timeout = max(timeout,1);
-    PA_DEBUG(("Timeout = %ld\n",timeout));
-
-    while(!stream->streamAbort)
-    {
-        fillPlaybuf = 0;
-        emptyRecordbuf = 0;
-
-        /* Wait for next input or output buffer to be finished with*/
-        assert(pending>0);
-
-        if(stream->streamStop)
-        {
-            PA_DEBUG(("ss1:pending=%d ",pending));
-        }
-        wait = WaitForMultipleObjects(5, stream->events, FALSE, 0);
-        if( wait == WAIT_TIMEOUT )
-        {
-            /* No (under|over)flow has ocurred */
-            wait = WaitForMultipleObjects(5, stream->events, FALSE, timeout);
-            eventSignaled = wait - WAIT_OBJECT_0;
-        }
-        else
-        {
-            eventSignaled = wait - WAIT_OBJECT_0;
-            if( eventSignaled < 2 )
-            {
-                underover |= paInputOverflow;
-                PA_DEBUG(("Input overflow\n"));
-            }
-            else if(( eventSignaled < 4 )&&(!priming))
-            {
-                underover |= paOutputUnderflow;
-                PA_DEBUG(("Output underflow\n"));
-            }
-        }
-
-        if(stream->streamStop)
-        {
-            PA_DEBUG(("ss2:wait=%ld",wait));
-        }
-        if(wait == WAIT_FAILED)
-        {
-            PA_DEBUG(("Wait fail = %ld! ",wait));
-            break;
-        }
-        if(wait == WAIT_TIMEOUT)
-        {
-            continue;
-        }
-
-        if(eventSignaled < 2)
-        { /* Recording input buffer has been filled */
-            if(stream->playbackPin)
-            {
-                /* First check if also the next playback buffer has been signaled */
-                wait = WaitForSingleObject(stream->events[outbuf+2],0);
-                if(wait == WAIT_OBJECT_0)
-                {
-                    /* Yes, so do both buffers at same time */
-                    fillPlaybuf = 1;
-                    pending--;
-                    /* Was this an underflow situation? */
-                    if( underover )
-                        underover |= paOutputUnderflow; /* Yes! */
-                }
-            }
-            emptyRecordbuf = 1;
-            pending--;
-        }
-        else if(eventSignaled < 4)
-        { /* Playback output buffer has been emptied */
-            if(stream->recordingPin)
-            {
-                /* First check if also the next recording buffer has been signaled */
-                wait = WaitForSingleObject(stream->events[inbuf],0);
-                if(wait == WAIT_OBJECT_0)
-                { /* Yes, so do both buffers at same time */
-                    emptyRecordbuf = 1;
-                    pending--;
-                    /* Was this an overflow situation? */
-                    if( underover )
-                        underover |= paInputOverflow; /* Yes! */
-                }
-            }
-            fillPlaybuf = 1;
-            pending--;
-        }
-        else
-        {
-            /* Abort event! */
-            assert(stream->streamAbort); /* Should have been set */
-            PA_DEBUG(("ABORTING "));
-            break;
-        }
-        ResetEvent(stream->events[eventSignaled]);
-
-        if(stream->streamStop)
-        {
-            PA_DEBUG(("Stream stop! pending=%d",pending));
-            cbResult = paComplete; /* Stop, but play remaining buffers */
-        }
-
-        /* Do necessary buffer processing (which will invoke user callback if necessary */
-        doChannelCopy = 0;
-        if(cbResult==paContinue)
-        {
-            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
-            if((stream->bufferProcessor.hostInputFrameCount[0] + stream->bufferProcessor.hostInputFrameCount[1]) ==
-                (stream->bufferProcessor.hostOutputFrameCount[0] + stream->bufferProcessor.hostOutputFrameCount[1]) )
-                PaUtil_BeginBufferProcessing(&stream->bufferProcessor,&ti,underover);
-            underover = 0; /* Reset the (under|over)flow status */
-            if(fillPlaybuf)
-            {
-                PaUtil_SetOutputFrameCount(&stream->bufferProcessor,0);
-                if( stream->userOutputChannels == 1 )
-                {
-                    /* Write the single user channel to the first interleaved block */
-                    PaUtil_SetOutputChannel(&stream->bufferProcessor,0,stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels);
-                    /* We will do a copy to the other channels after the data has been written */
-                    doChannelCopy = 1;
-                }
-                else
-                {
-                    for(i=0;i<stream->userOutputChannels;i++)
-                    {
-                        /* Only write the user output channels. Leave the rest blank */
-                        PaUtil_SetOutputChannel(&stream->bufferProcessor,i,((unsigned char*)(stream->packets[outbuf+2].Header.Data))+(i*stream->outputSampleSize),stream->deviceOutputChannels);
-                    }
-                }
-            }
-            if(emptyRecordbuf)
-            {
-                PaUtil_SetInputFrameCount(&stream->bufferProcessor,stream->packets[inbuf].Header.DataUsed/stream->bytesPerInputFrame);
-                for(i=0;i<stream->userInputChannels;i++)
-                {
-                    /* Only read as many channels as the user wants */
-                    PaUtil_SetInputChannel(&stream->bufferProcessor,i,((unsigned char*)(stream->packets[inbuf].Header.Data))+(i*stream->inputSampleSize),stream->deviceInputChannels);
-                }
-            }
-            
-            if (stream->recordingPin && stream->playbackPin) /* full duplex */
-            {
-                /* Only call the EndBufferProcessing function when the total input frames == total output frames */
-
-                if((stream->bufferProcessor.hostInputFrameCount[0] + stream->bufferProcessor.hostInputFrameCount[1]) ==
-                        (stream->bufferProcessor.hostOutputFrameCount[0] + stream->bufferProcessor.hostOutputFrameCount[1]) )
-                {
-                    framesProcessed = PaUtil_EndBufferProcessing(&stream->bufferProcessor,&cbResult);
-                }
-                else
-                {
-                    framesProcessed = 0;
-                }
-            }
-            else 
-            {
-                framesProcessed = PaUtil_EndBufferProcessing(&stream->bufferProcessor,&cbResult);
-            }
-
-            if( doChannelCopy )
-            {
-                /* Copy the first output channel to the other channels */
-                switch(stream->outputSampleSize)
-                {
-                    case 2:
-                        DuplicateFirstChannelInt16(stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels,stream->framesPerHostOBuffer);
-                        break;
-                    case 3:
-                        DuplicateFirstChannelInt24(stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels,stream->framesPerHostOBuffer);
-                        break;
-                    case 4:
-                        DuplicateFirstChannelInt32(stream->packets[outbuf+2].Header.Data,stream->deviceOutputChannels,stream->framesPerHostOBuffer);
-                        break;
-                    default:
-                        assert(0); /* Unsupported format! */
-                        break;
-                }
-            }
-            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
-        }
-        else
-        {
-            fillPlaybuf = 0;
-            emptyRecordbuf = 0;
-        }
-            
-        /*
-        if(cbResult != paContinue)
-        {
-            PA_DEBUG(("cbResult=%d, pending=%d:",cbResult,pending));
-        }
-        */
-        /* Submit buffers */
-        if((fillPlaybuf)&&(cbResult!=paAbort))
-        {
-            if(!PinWrite(stream->playbackPin->handle,&stream->packets[outbuf+2]))
-                outbuf = (outbuf+1)&1; /* Increment and wrap */
-            pending++;
-            if( priming )
-                priming--; /* Have to prime twice */
-        }
-        if((emptyRecordbuf)&&(cbResult==paContinue))
-        {
-            stream->packets[inbuf].Header.DataUsed = 0; /* Reset for reuse */
-            PinRead(stream->recordingPin->handle,&stream->packets[inbuf]);
-            inbuf = (inbuf+1)&1; /* Increment and wrap */
-            pending++;
-        }
-        if(pending==0)
-        {
-            PA_DEBUG(("pending==0 finished...;"));
-            break;
-        }
-        if((!stream->playbackPin)&&(cbResult!=paContinue))
-        {
-            PA_DEBUG(("record only cbResult=%d...;",cbResult));
-            break;
-        }
-    }
-
-    PA_DEBUG(("Finished thread"));
-
-    /* Finished, either normally or aborted */
-    if(stream->playbackPin)
-    {
-        result = PinSetState(stream->playbackPin, KSSTATE_PAUSE);
-        result = PinSetState(stream->playbackPin, KSSTATE_STOP);
-    }
-    if(stream->recordingPin)
-    {
-        result = PinSetState(stream->recordingPin, KSSTATE_PAUSE);
-        result = PinSetState(stream->recordingPin, KSSTATE_STOP);
-    }
-
-    stream->streamActive = 0;
-
-    if((!stream->streamStop)&&(!stream->streamAbort))
-    {
-          /* Invoke the user stream finished callback */
-          /* Only do it from here if not being stopped/aborted by user */
-          if( stream->streamRepresentation.streamFinishedCallback != 0 )
-              stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
-    }
-    stream->streamStop = 0;
-    stream->streamAbort = 0;
-
-    /* Reset process priority if necessary */
-    if(stream->oldProcessPriority != REALTIME_PRIORITY_CLASS)
-    {
-        SetPriorityClass(GetCurrentProcess(),stream->oldProcessPriority);
-        stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;
-    }
-
-    PA_LOGL_;
-    EXIT_THREAD;
-    return 0;
-}
-
-static PaError StartStream( PaStream *s )
-{
-    PaError result = paNoError;
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    DWORD dwID;
-    BOOL ret;
-    int size;
-
-    PA_LOGE_;
-
-    stream->streamStop = 0;
-    stream->streamAbort = 0;
-    size = 5;
-    while(size--)
-    {
-        if(stream->events[size] != NULL)
-        {
-            ResetEvent(stream->events[size]);
-        }
-    }
-
-    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
-
-    stream->oldProcessPriority = GetPriorityClass(GetCurrentProcess());
-    /* Uncomment the following line to enable dynamic boosting of the process
-     * priority to real time for best low latency support
-     * Disabled by default because RT processes can easily block the OS */
-    /*ret = SetPriorityClass(GetCurrentProcess(),REALTIME_PRIORITY_CLASS);
-      PA_DEBUG(("Class ret = %d;",ret));*/
-
-    stream->streamStarted = 1;
-    stream->streamThread = (HANDLE)_beginthreadex(NULL, 0, ProcessingThread, stream, 0, &dwID);
-    if(stream->streamThread == NULL)
-    {
-        stream->streamStarted = 0;
-        result = paInsufficientMemory;
-        goto end;
-    }
-    ret = SetThreadPriority(stream->streamThread,THREAD_PRIORITY_TIME_CRITICAL);
-    PA_DEBUG(("Priority ret = %d;",ret));
-    /* Make the stream active */
-    stream->streamActive = 1;
-
-end:
-    PA_LOGL_;
-    return result;
-}
-
-
-static PaError StopStream( PaStream *s )
-{
-    PaError result = paNoError;
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    int doCb = 0;
-
-    PA_LOGE_;
-
-    if(stream->streamActive)
-    {
-        doCb = 1;
-        stream->streamStop = 1;
-        while(stream->streamActive)
-        {
-            PA_DEBUG(("W."));
-            Sleep(10); /* Let thread sleep for 10 msec */
-        }
-    }
-
-    PA_DEBUG(("Terminating thread"));
-    if(stream->streamStarted && stream->streamThread)
-    {
-        TerminateThread(stream->streamThread,0);
-        stream->streamThread = NULL;
-    }
-
-    stream->streamStarted = 0;
-
-    if(stream->oldProcessPriority != REALTIME_PRIORITY_CLASS)
-    {
-        SetPriorityClass(GetCurrentProcess(),stream->oldProcessPriority);
-        stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;
-    }
-
-    if(doCb)
-    {
-        /* Do user callback now after all state has been reset */
-        /* This means it should be safe for the called function */
-        /* to invoke e.g. StartStream */
-        if( stream->streamRepresentation.streamFinishedCallback != 0 )
-             stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
-    }
-
-    PA_LOGL_;
-    return result;
-}
-
-static PaError AbortStream( PaStream *s )
-{
-    PaError result = paNoError;
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    int doCb = 0;
-
-    PA_LOGE_;
-
-    if(stream->streamActive)
-    {
-        doCb = 1;
-        stream->streamAbort = 1;
-        SetEvent(stream->events[4]); /* Signal immediately */
-        while(stream->streamActive)
-        {
-            Sleep(10);
-        }
-    }
-
-    if(stream->streamStarted && stream->streamThread)
-    {
-        TerminateThread(stream->streamThread,0);
-        stream->streamThread = NULL;
-    }
-
-    stream->streamStarted = 0;
-
-    if(stream->oldProcessPriority != REALTIME_PRIORITY_CLASS)
-    {
-        SetPriorityClass(GetCurrentProcess(),stream->oldProcessPriority);
-        stream->oldProcessPriority = REALTIME_PRIORITY_CLASS;
-    }
-
-    if(doCb)
-    {
-        /* Do user callback now after all state has been reset */
-        /* This means it should be safe for the called function */
-        /* to invoke e.g. StartStream */
-        if( stream->streamRepresentation.streamFinishedCallback != 0 )
-            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
-    }
-
-    stream->streamActive = 0;
-    stream->streamStarted = 0;
-
-    PA_LOGL_;
-    return result;
-}
-
-
-static PaError IsStreamStopped( PaStream *s )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    int result = 0;
-
-    PA_LOGE_;
-
-    if(!stream->streamStarted)
-        result = 1;
-
-    PA_LOGL_;
-    return result;
-}
-
-
-static PaError IsStreamActive( PaStream *s )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    int result = 0;
-
-    PA_LOGE_;
-
-    if(stream->streamActive)
-        result = 1;
-
-    PA_LOGL_;
-    return result;
-}
-
-
-static PaTime GetStreamTime( PaStream* s )
-{
-    PA_LOGE_;
-    PA_LOGL_;
-    (void)s;
-    return PaUtil_GetTime();
-}
-
-
-static double GetStreamCpuLoad( PaStream* s )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-    double result;
-    PA_LOGE_;
-    result = PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
-    PA_LOGL_;
-    return result;
-}
-
-
-/*
-    As separate stream interfaces are used for blocking and callback
-    streams, the following functions can be guaranteed to only be called
-    for blocking streams.
-*/
-
-static PaError ReadStream( PaStream* s,
-                           void *buffer,
-                           unsigned long frames )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-
-    PA_LOGE_;
-
-    /* suppress unused variable warnings */
-    (void) buffer;
-    (void) frames;
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-    PA_LOGL_;
-    return paNoError;
-}
-
-
-static PaError WriteStream( PaStream* s,
-                            const void *buffer,
-                            unsigned long frames )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-
-    PA_LOGE_;
-
-    /* suppress unused variable warnings */
-    (void) buffer;
-    (void) frames;
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-    PA_LOGL_;
-    return paNoError;
-}
-
-
-static signed long GetStreamReadAvailable( PaStream* s )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-
-    PA_LOGE_;
-
-    /* suppress unused variable warnings */
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-    PA_LOGL_;
-    return 0;
-}
-
-
-static signed long GetStreamWriteAvailable( PaStream* s )
-{
-    PaWinWdmStream *stream = (PaWinWdmStream*)s;
-
-    PA_LOGE_;
-    /* suppress unused variable warnings */
-    (void) stream;
-
-    /* IMPLEMENT ME, see portaudio.h for required behavior*/
-    PA_LOGL_;
-    return 0;
-}
\ No newline at end of file
diff --git a/portaudio/src/hostapi/wdmks/readme.txt b/portaudio/src/hostapi/wdmks/readme.txt
deleted file mode 100644
index 1a381fe79..000000000
--- a/portaudio/src/hostapi/wdmks/readme.txt
+++ /dev/null
@@ -1,82 +0,0 @@
-Notes about WDM-KS host API
----------------------------
-
-Status history
---------------
-10th November 2005:
-Made following changes:
- * OpenStream: Try all PaSampleFormats internally if the the chosen
-     format is not supported natively.  This fixed several problems
-     with soundcards that soundcards that did not take kindly to
-     using 24-bit 3-byte formats.
- * OpenStream: Make the minimum framesPerHostIBuffer (and framesPerHostOBuffer)
-     the default frameSize for the playback/recording pin.
- * ProcessingThread: Added a switch to only call PaUtil_EndBufferProcessing
-     if the total input frames equals the total output frames
-
-5th September 2004:
-This is the first public version of the code. It should be considered
-an alpha release with zero guarantee not to crash on any particular 
-system. So far it has only been tested in the author's development
-environment, which means a Win2k/SP2 PIII laptop with integrated 
-SoundMAX driver and USB Tascam US-428 compiled with both MinGW
-(GCC 3.3) and MSVC++6 using the MS DirectX 9 SDK.
-It has been most widely tested with the MinGW build, with most of the
-test programs (particularly paqa_devs and paqa_errs) passing.
-There are some notable failures: patest_out_underflow and both of the
-blocking I/O tests (as blocking I/O is not implemented).
-At this point the code needs to be tested with a much wider variety 
-of configurations and feedback provided from testers regarding
-both working and failing cases.
-
-What is the WDM-KS host API?
-----------------------------
-PortAudio for Windows currently has 3 functional host implementations.
-MME uses the oldest Windows audio API which does not offer good
-play/record latency. 
-DirectX improves this, but still imposes a penalty
-of 10s of milliseconds due to the system mixing of streams from
-multiple applications. 
-ASIO offers very good latency, but requires special drivers which are
-not always available for cheaper audio hardware. Also, when ASIO 
-drivers are available, they are not always so robust because they 
-bypass all of the standardised Windows device driver architecture 
-and hit the hardware their own way.
-Alternatively there are a couple of free (but closed source) ASIO 
-implementations which connect to the lower level Windows 
-"Kernel Streaming" API, but again these require special installation 
-by the user, and can be limited in functionality or difficult to use. 
-
-This is where the PortAudio "WDM-KS" host implementation comes in.
-It directly connects PortAudio to the same Kernel Streaming API which
-those ASIO bridges use. This avoids the mixing penatly of DirectX, 
-giving at least as good latency as any ASIO driver, but it has the
-advantage of working with ANY Windows audio hardware which is available
-through the normal MME/DirectX routes without the user requiring 
-any additional device drivers to be installed, and allowing all 
-device selection to be done through the normal PortAudio API.
-
-Note that in general you should only be using this host API if your 
-application has a real requirement for very low latency audio (<20ms), 
-either because you are generating sounds in real-time based upon 
-user input, or you a processing recorded audio in real time.
-
-The only thing to be aware of is that using the KS interface will
-block that device from being used by the rest of system through
-the higher level APIs, or conversely, if the system is using
-a device, the KS API will not be able to use it. MS recommend that
-you should keep the device open only when your application has focus.
-In PortAudio terms, this means having a stream Open on a WDMKS device.
-
-Usage
------
-To add the WDMKS backend to your program which is already using 
-PortAudio, you must undefine PA_NO_WDMKS from your build file,
-and include the pa_win_wdmks\pa_win_wdmks.c into your build.
-The file should compile in both C and C++.
-You will need a DirectX SDK installed on your system for the
-ks.h and ksmedia.h header files.
-You will need to link to the system "setupapi" library.
-Note that if you use MinGW, you will get more warnings from 
-the DX header files when using GCC(C), and still a few warnings
-with G++(CPP).
\ No newline at end of file
diff --git a/portaudio/src/hostapi/wmme/pa_win_wmme.c b/portaudio/src/hostapi/wmme/pa_win_wmme.c
index 2436d8de1..3264ebf89 100644
--- a/portaudio/src/hostapi/wmme/pa_win_wmme.c
+++ b/portaudio/src/hostapi/wmme/pa_win_wmme.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_win_wmme.c 1432 2009-12-09 01:31:44Z rossb $
+ * $Id: pa_win_wmme.c 1229 2007-06-15 16:11:11Z rossb $
  * pa_win_wmme.c
  * Implementation of PortAudio for Windows MultiMedia Extensions (WMME)       
  *                                                                                         
@@ -62,9 +62,7 @@
 */
 
 /** @file
-	@ingroup hostapi_src
-
-    @brief Win32 host API implementation for the Windows MultiMedia Extensions (WMME) audio API.
+	@ingroup hostaip_src
 
 	@todo Fix buffer catch up code, can sometimes get stuck (perhaps fixed now,
             needs to be reviewed and tested.)
@@ -90,10 +88,6 @@ Non-critical stuff for the future:
     
     @todo define UNICODE and _UNICODE in the project settings and see what breaks
 
-    @todo refactor conversion of MMSYSTEM errors into PA arrors into a single function.
-
-    @todo cleanup WAVEFORMATEXTENSIBLE retry in InitializeWaveHandles to not use a for loop
-
 */
 
 /*
@@ -139,29 +133,8 @@ Non-critical stuff for the future:
 #include "pa_debugprint.h"
 
 #include "pa_win_wmme.h"
-#include "pa_win_waveformat.h"
-
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-#include "pa_win_wdmks_utils.h"
-#ifndef DRV_QUERYDEVICEINTERFACE
-#define DRV_QUERYDEVICEINTERFACE     (DRV_RESERVED + 12)
-#endif
-#ifndef DRV_QUERYDEVICEINTERFACESIZE
-#define DRV_QUERYDEVICEINTERFACESIZE (DRV_RESERVED + 13)
-#endif
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
 
-/* use CreateThread for CYGWIN, _beginthreadex for all others */
-#if !defined(__CYGWIN__) && !defined(_WIN32_WCE)
-#define CREATE_THREAD (HANDLE)_beginthreadex( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
-#define PA_THREAD_FUNC static unsigned WINAPI
-#define PA_THREAD_ID unsigned
-#else
-#define CREATE_THREAD CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId )
-#define PA_THREAD_FUNC static DWORD WINAPI
-#define PA_THREAD_ID DWORD
-#endif
-#if (defined(_WIN32_WCE))
+#if (defined(UNDER_CE))
 #pragma comment(lib, "Coredll.lib")
 #elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
 #pragma comment(lib, "winmm.lib")
@@ -171,11 +144,7 @@ Non-critical stuff for the future:
  provided in newer platform sdks
  */
 #ifndef DWORD_PTR
-    #if defined(_WIN64)
-        #define DWORD_PTR unsigned __int64
-    #else
-        #define DWORD_PTR unsigned long
-    #endif
+#define DWORD_PTR DWORD
 #endif
 
 /************************************************* Constants ********/
@@ -212,34 +181,6 @@ Non-critical stuff for the future:
 static const char constInputMapperSuffix_[] = " - Input";
 static const char constOutputMapperSuffix_[] = " - Output";
 
-/*
-copies TCHAR string to explicit char string
-*/
-char *StrTCpyToC(char *to, const TCHAR *from)
-{
-#if !defined(_UNICODE) && !defined(UNICODE)
-	return strcpy(to, from);
-#else
-	int count = wcslen(from);
-	if (count != 0)
-		if (WideCharToMultiByte(CP_ACP, 0, from, count, to, count, NULL, NULL) == 0)
-			return NULL;
-	return to;
-#endif
-}
-
-/*
-returns length of TCHAR string
-*/
-size_t StrTLen(const TCHAR *str)
-{
-#if !defined(_UNICODE) && !defined(UNICODE)
-	return strlen(str);
-#else
-	return wcslen(str);	
-#endif
-}
-
 /********************************************************************/
 
 typedef struct PaWinMmeStream PaWinMmeStream;     /* forward declaration */
@@ -433,8 +374,6 @@ typedef struct
 {
     PaDeviceInfo inheritedDeviceInfo;
     DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */
-    char deviceInputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
-    char deviceOutputChannelCountIsKnown; /**<< if the system returns 0xFFFF then we don't really know the number of supported channels (1=>known, 0=>unknown)*/
 }
 PaWinMmeDeviceInfo;
 
@@ -506,21 +445,6 @@ static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hos
 }
 
 
-static int SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( PaSampleFormat sampleFormat, unsigned long winMmeSpecificFlags )
-{
-    int waveFormatTag = 0;
-
-    if( winMmeSpecificFlags & paWinMmeWaveFormatDolbyAc3Spdif )
-        waveFormatTag = PAWIN_WAVE_FORMAT_DOLBY_AC3_SPDIF;
-    else if( winMmeSpecificFlags & paWinMmeWaveFormatWmaSpdif )
-        waveFormatTag = PAWIN_WAVE_FORMAT_WMA_SPDIF;
-    else
-        waveFormatTag = PaWin_SampleFormatToLinearWaveFormatTag( sampleFormat );
-
-    return waveFormatTag;
-}
-
-
 static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
 {
     MMRESULT mmresult;
@@ -575,57 +499,41 @@ static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx
 
 static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo,
         PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*),
-        int winMmeDeviceId, int channels, double sampleRate, unsigned long winMmeSpecificFlags )
+        int winMmeDeviceId, int channels, double sampleRate )
 {
     PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo;
-    PaWinWaveFormat waveFormat;
-    PaSampleFormat sampleFormat;
-    int waveFormatTag;
-    
-    /* @todo at the moment we only query with 16 bit sample format and directout speaker config*/
-
-    sampleFormat = paInt16;
-    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );
-
-    if( waveFormatTag == PaWin_SampleFormatToLinearWaveFormatTag( paInt16 ) ){
+    WAVEFORMATEX waveFormatEx;
     
-        /* attempt bypass querying the device for linear formats */
-
-        if( sampleRate == 11025.0
-            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))
-                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){
-
-            return paNoError;
-        }
+    if( sampleRate == 11025.0
+        && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))
+            || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){
 
-        if( sampleRate == 22050.0
-            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))
-                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){
-
-            return paNoError;
-        }
-
-        if( sampleRate == 44100.0
-            && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))
-                || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){
-
-            return paNoError;
-        }
+        return paNoError;
     }
 
+    if( sampleRate == 22050.0
+        && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))
+            || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){
 
-    /* first, attempt to query the device using WAVEFORMATEXTENSIBLE, 
-       if this fails we fall back to WAVEFORMATEX */
+        return paNoError;
+    }
 
-    PaWin_InitializeWaveFormatExtensible( &waveFormat, channels, sampleFormat, waveFormatTag,
-            sampleRate, PAWIN_SPEAKER_DIRECTOUT );
+    if( sampleRate == 44100.0
+        && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))
+            || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){
 
-    if( waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat ) == paNoError )
         return paNoError;
+    }
 
-    PaWin_InitializeWaveFormatEx( &waveFormat, channels, sampleFormat, waveFormatTag, sampleRate );
+    waveFormatEx.wFormatTag = WAVE_FORMAT_PCM;
+    waveFormatEx.nChannels = (WORD)channels;
+    waveFormatEx.nSamplesPerSec = (DWORD)sampleRate;
+    waveFormatEx.nAvgBytesPerSec = waveFormatEx.nSamplesPerSec * channels * sizeof(short);
+    waveFormatEx.nBlockAlign = (WORD)(channels * sizeof(short));
+    waveFormatEx.wBitsPerSample = 16;
+    waveFormatEx.cbSize = 0;
 
-    return waveFormatExQueryFunction( winMmeDeviceId, (WAVEFORMATEX*)&waveFormat );
+    return waveFormatExQueryFunction( winMmeDeviceId, &waveFormatEx );
 }
 
 
@@ -645,7 +553,7 @@ static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int w
     for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
     {
         double sampleRate = defaultSampleRateSearchOrder_[ i ]; 
-        PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate, 0 );
+        PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate );
         if( paerror == paNoError )
         {
             deviceInfo->defaultSampleRate = sampleRate;
@@ -655,40 +563,6 @@ static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int w
 }
 
 
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-static int QueryWaveInKSFilterMaxChannels( int waveInDeviceId, int *maxChannels )
-{
-    void *devicePath;
-    DWORD devicePathSize;
-    int result = 0;
-
-    if( waveInMessage((HWAVEIN)waveInDeviceId, DRV_QUERYDEVICEINTERFACESIZE,
-            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )
-        return 0;
-
-    devicePath = PaUtil_AllocateMemory( devicePathSize );
-    if( !devicePath )
-        return 0;
-
-    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */
-    if( waveInMessage((HWAVEIN)waveInDeviceId, DRV_QUERYDEVICEINTERFACE,
-            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )
-    {
-        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 1  );
-        if( count > 0 )
-        {
-            *maxChannels = count;
-            result = 1;
-        }
-    }
-
-    PaUtil_FreeMemory( devicePath );
-
-    return result;
-}
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-
 static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
         PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success )
 {
@@ -720,52 +594,39 @@ static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeH
     {
         /* Append I/O suffix to WAVE_MAPPER device. */
         deviceName = (char *)PaUtil_GroupAllocateMemory(
-                    winMmeHostApi->allocations, StrTLen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_) );
+                    winMmeHostApi->allocations, strlen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_) );
         if( !deviceName )
         {
             result = paInsufficientMemory;
             goto error;
         }
-        StrTCpyToC( deviceName, wic.szPname );
+        strcpy( deviceName, wic.szPname );
         strcat( deviceName, constInputMapperSuffix_ );
     }
     else
     {
         deviceName = (char*)PaUtil_GroupAllocateMemory(
-                    winMmeHostApi->allocations, StrTLen( wic.szPname ) + 1 );
+                    winMmeHostApi->allocations, strlen( wic.szPname ) + 1 );
         if( !deviceName )
         {
             result = paInsufficientMemory;
             goto error;
         }
-        StrTCpyToC( deviceName, wic.szPname  );
+        strcpy( deviceName, wic.szPname  );
     }
     deviceInfo->name = deviceName;
 
-    if( wic.wChannels == 0xFFFF || wic.wChannels < 1 || wic.wChannels > 255 ){
-        /* For Windows versions using WDM (possibly Windows 98 ME and later)
-         * the kernel mixer sits between the application and the driver. As a result,
-         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.
-         * When this happens we assume the device is stereo and set a flag
-         * so that other channel counts can be tried with OpenStream -- i.e. when
-         * device*ChannelCountIsKnown is false, OpenStream will try whatever
-         * channel count you supply.
-         * see also InitializeOutputDeviceInfo() below.
+    deviceInfo->maxInputChannels = wic.wChannels;
+    /* Sometimes a device can return a rediculously large number of channels.
+     * This happened with an SBLive card on a Windows ME box.
+     * If that happens, then force it to 2 channels.  PLB20010413
      */
-
-        PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", wic.wChannels ));
+    if( (deviceInfo->maxInputChannels < 1) || (deviceInfo->maxInputChannels > 256) )
+    {
+        PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", deviceInfo->maxInputChannels ));
         deviceInfo->maxInputChannels = 2;
-        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 0;
-    }else{
-        deviceInfo->maxInputChannels = wic.wChannels;
-        winMmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
     }
 
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-    winMmeDeviceInfo->deviceInputChannelCountIsKnown = 
-            QueryWaveInKSFilterMaxChannels( winMmeInputDeviceId, &deviceInfo->maxInputChannels );
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
     winMmeDeviceInfo->dwFormats = wic.dwFormats;
 
     DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId,
@@ -778,40 +639,6 @@ error:
 }
 
 
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-static int QueryWaveOutKSFilterMaxChannels( int waveOutDeviceId, int *maxChannels )
-{
-    void *devicePath;
-    DWORD devicePathSize;
-    int result = 0;
-
-    if( waveOutMessage((HWAVEOUT)waveOutDeviceId, DRV_QUERYDEVICEINTERFACESIZE,
-            (DWORD_PTR)&devicePathSize, 0 ) != MMSYSERR_NOERROR )
-        return 0;
-
-    devicePath = PaUtil_AllocateMemory( devicePathSize );
-    if( !devicePath )
-        return 0;
-
-    /* apparently DRV_QUERYDEVICEINTERFACE returns a unicode interface path, although this is undocumented */
-    if( waveOutMessage((HWAVEOUT)waveOutDeviceId, DRV_QUERYDEVICEINTERFACE,
-            (DWORD_PTR)devicePath, devicePathSize ) == MMSYSERR_NOERROR )
-    {
-        int count = PaWin_WDMKS_QueryFilterMaximumChannelCount( devicePath, /* isInput= */ 0  );
-        if( count > 0 )
-        {
-            *maxChannels = count;
-            result = 1;
-        }
-    }
-
-    PaUtil_FreeMemory( devicePath );
-
-    return result;
-}
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
-
 static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
         PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success )
 {
@@ -820,8 +647,7 @@ static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMme
     MMRESULT mmresult;
     WAVEOUTCAPS woc;
     PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
-    int wdmksDeviceOutputChannelCountIsKnown;
-
+    
     *success = 0;
 
     mmresult = waveOutGetDevCaps( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPS ) );
@@ -844,54 +670,39 @@ static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMme
     {
         /* Append I/O suffix to WAVE_MAPPER device. */
         deviceName = (char *)PaUtil_GroupAllocateMemory(
-                    winMmeHostApi->allocations, StrTLen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_) );
+                    winMmeHostApi->allocations, strlen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_) );
         if( !deviceName )
         {
             result = paInsufficientMemory;
             goto error;
         }
-        StrTCpyToC( deviceName, woc.szPname );
+        strcpy( deviceName, woc.szPname );
         strcat( deviceName, constOutputMapperSuffix_ );
     }
     else
     {
         deviceName = (char*)PaUtil_GroupAllocateMemory(
-                    winMmeHostApi->allocations, StrTLen( woc.szPname ) + 1 );
+                    winMmeHostApi->allocations, strlen( woc.szPname ) + 1 );
         if( !deviceName )
         {
             result = paInsufficientMemory;
             goto error;
         }
-        StrTCpyToC( deviceName, woc.szPname  );
+        strcpy( deviceName, woc.szPname  );
     }
     deviceInfo->name = deviceName;
 
-    if( woc.wChannels == 0xFFFF || woc.wChannels < 1 || woc.wChannels > 255 ){
-        /* For Windows versions using WDM (possibly Windows 98 ME and later)
-         * the kernel mixer sits between the application and the driver. As a result,
-         * wave*GetDevCaps often kernel mixer channel counts, which are unlimited.
-         * When this happens we assume the device is stereo and set a flag
-         * so that other channel counts can be tried with OpenStream -- i.e. when
-         * device*ChannelCountIsKnown is false, OpenStream will try whatever
-         * channel count you supply.
-         * see also InitializeInputDeviceInfo() above.
+    deviceInfo->maxOutputChannels = woc.wChannels;
+    /* Sometimes a device can return a rediculously large number of channels.
+     * This happened with an SBLive card on a Windows ME box.
+     * It also happens on Win XP!
      */
-
-        PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", woc.wChannels ));
+    if( (deviceInfo->maxOutputChannels < 1) || (deviceInfo->maxOutputChannels > 256) )
+    {
+        PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", deviceInfo->maxOutputChannels ));
         deviceInfo->maxOutputChannels = 2;
-        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 0;
-    }else{
-        deviceInfo->maxOutputChannels = woc.wChannels;
-        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
     }
 
-#ifdef PAWIN_USE_WDMKS_DEVICE_INFO
-    wdmksDeviceOutputChannelCountIsKnown = QueryWaveOutKSFilterMaxChannels( 
-			winMmeOutputDeviceId, &deviceInfo->maxOutputChannels );
-    if( wdmksDeviceOutputChannelCountIsKnown && !winMmeDeviceInfo->deviceOutputChannelCountIsKnown )
-        winMmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
-#endif /* PAWIN_USE_WDMKS_DEVICE_INFO */
-
     winMmeDeviceInfo->dwFormats = woc.dwFormats;
 
     DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId,
@@ -937,8 +748,6 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
     PaWinMmeDeviceInfo *deviceInfoArray;
     int deviceInfoInitializationSucceeded;
     PaTime defaultLowLatency, defaultHighLatency;
-    DWORD waveInPreferredDevice, waveOutPreferredDevice;
-    DWORD preferredDeviceStatusFlags;
 
     winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) );
     if( !winMmeHostApi )
@@ -970,19 +779,6 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
     winMmeHostApi->inputDeviceCount = 0;
     winMmeHostApi->outputDeviceCount = 0;
 
-#if !defined(DRVM_MAPPER_PREFERRED_GET)
-/* DRVM_MAPPER_PREFERRED_GET is defined in mmddk.h but we avoid a dependency on the DDK by defining it here */
-#define DRVM_MAPPER_PREFERRED_GET    (0x2000+21)
-#endif
-
-    /* the following calls assume that if wave*Message fails the preferred device parameter won't be modified */
-    preferredDeviceStatusFlags = 0;
-    waveInPreferredDevice = -1;
-    waveInMessage( (HWAVEIN)WAVE_MAPPER, DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveInPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );
-
-    preferredDeviceStatusFlags = 0;
-    waveOutPreferredDevice = -1;
-    waveOutMessage( (HWAVEOUT)WAVE_MAPPER, DRVM_MAPPER_PREFERRED_GET, (DWORD_PTR)&waveOutPreferredDevice, (DWORD_PTR)&preferredDeviceStatusFlags );
 
     maximumPossibleDeviceCount = 0;
 
@@ -1034,9 +830,7 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
                 deviceInfo->hostApi = hostApiIndex;
 
                 deviceInfo->maxInputChannels = 0;
-                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
                 deviceInfo->maxOutputChannels = 0;
-                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
 
                 deviceInfo->defaultLowInputLatency = defaultLowLatency;
                 deviceInfo->defaultLowOutputLatency = defaultLowLatency;
@@ -1049,14 +843,8 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
                     goto error;
 
                 if( deviceInfoInitializationSucceeded ){
-                    if( (*hostApi)->info.defaultInputDevice == paNoDevice ){
-                        /* if there is currently no default device, use the first one available */
+                    if( (*hostApi)->info.defaultInputDevice == paNoDevice )
                         (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
-                    
-                    }else if( winMmeDeviceId == waveInPreferredDevice ){
-                        /* set the default device to the system preferred device */
-                        (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
-                    }
 
                     winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
                     (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
@@ -1077,9 +865,7 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
                 deviceInfo->hostApi = hostApiIndex;
 
                 deviceInfo->maxInputChannels = 0;
-                wmmeDeviceInfo->deviceInputChannelCountIsKnown = 1;
                 deviceInfo->maxOutputChannels = 0;
-                wmmeDeviceInfo->deviceOutputChannelCountIsKnown = 1;
 
                 deviceInfo->defaultLowInputLatency = defaultLowLatency;
                 deviceInfo->defaultLowOutputLatency = defaultLowLatency;
@@ -1092,15 +878,9 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
                     goto error;
 
                 if( deviceInfoInitializationSucceeded ){
-                    if( (*hostApi)->info.defaultOutputDevice == paNoDevice ){
-                        /* if there is currently no default device, use the first one available */
+                    if( (*hostApi)->info.defaultOutputDevice == paNoDevice )
                         (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
 
-                    }else if( winMmeDeviceId == waveOutPreferredDevice ){
-                        /* set the default device to the system preferred device */
-                        (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
-                    }
-
                     winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
                     (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
 
@@ -1111,6 +891,7 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
         }
     }
     
+
     InitializeDefaultDeviceIdsFromEnv( winMmeHostApi );
 
     (*hostApi)->Terminate = Terminate;
@@ -1160,34 +941,6 @@ static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
 }
 
 
-static PaError IsInputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )
-{
-    PaError result = paNoError;
-
-    if( channelCount > 0
-            && deviceInfo->deviceInputChannelCountIsKnown
-            && channelCount > deviceInfo->inheritedDeviceInfo.maxInputChannels ){
-
-        result = paInvalidChannelCount; 
-    }
-
-    return result;
-}
-
-static PaError IsOutputChannelCountSupported( PaWinMmeDeviceInfo* deviceInfo, int channelCount )
-{
-    PaError result = paNoError;
-
-    if( channelCount > 0
-            && deviceInfo->deviceOutputChannelCountIsKnown
-            && channelCount > deviceInfo->inheritedDeviceInfo.maxOutputChannels ){
-
-        result = paInvalidChannelCount; 
-    }
-
-    return result;
-}
-
 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                                   const PaStreamParameters *inputParameters,
                                   const PaStreamParameters *outputParameters,
@@ -1232,19 +985,13 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                 inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ];
 
                 /* check that input device can support inputChannelCount */
-                if( inputStreamInfo->devices[i].channelCount < 1 )
+                if( inputStreamInfo->devices[i].channelCount <= 0
+                        || inputStreamInfo->devices[i].channelCount > inputDeviceInfo->maxInputChannels )
                     return paInvalidChannelCount;
 
-                paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, 
-                        inputStreamInfo->devices[i].channelCount );
-                if( paerror != paNoError )
-                    return paerror;
-
                 /* test for valid sample rate, see comment above */
                 winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device );
-                paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, 
-                        winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate, 
-                        ((inputStreamInfo) ? inputStreamInfo->flags : 0) );
+                paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate );
                 if( paerror != paNoError )
                     return paInvalidSampleRate;
             }
@@ -1260,15 +1007,12 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
             inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ];
 
             /* check that input device can support inputChannelCount */
-            paerror = IsInputChannelCountSupported( (PaWinMmeDeviceInfo*)inputDeviceInfo, inputChannelCount );
-            if( paerror != paNoError )
-                return paerror;
+            if( inputChannelCount > inputDeviceInfo->maxInputChannels )
+                return paInvalidChannelCount;
 
             /* test for valid sample rate, see comment above */
             winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device );
-            paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, 
-                    winMmeInputDeviceId, inputChannelCount, sampleRate,
-                    ((inputStreamInfo) ? inputStreamInfo->flags : 0) );
+            paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputChannelCount, sampleRate );
             if( paerror != paNoError )
                 return paInvalidSampleRate;
         }
@@ -1296,19 +1040,13 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
                 outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ];
 
                 /* check that output device can support outputChannelCount */
-                if( outputStreamInfo->devices[i].channelCount < 1 )
+                if( outputStreamInfo->devices[i].channelCount <= 0
+                        || outputStreamInfo->devices[i].channelCount > outputDeviceInfo->maxOutputChannels )
                     return paInvalidChannelCount;
 
-                paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, 
-                        outputStreamInfo->devices[i].channelCount );
-                if( paerror != paNoError )
-                    return paerror;
-
                 /* test for valid sample rate, see comment above */
                 winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device );
-                paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, 
-                        winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate,
-                        ((outputStreamInfo) ? outputStreamInfo->flags : 0) );
+                paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate );
                 if( paerror != paNoError )
                     return paInvalidSampleRate;
             }
@@ -1324,15 +1062,12 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
             outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ];
 
             /* check that output device can support outputChannelCount */
-            paerror = IsOutputChannelCountSupported( (PaWinMmeDeviceInfo*)outputDeviceInfo, outputChannelCount );
-            if( paerror != paNoError )
-                return paerror;
+            if( outputChannelCount > outputDeviceInfo->maxOutputChannels )
+                return paInvalidChannelCount;
 
             /* test for valid sample rate, see comment above */
             winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device );
-            paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, 
-                    winMmeOutputDeviceId, outputChannelCount, sampleRate,
-                    ((outputStreamInfo) ? outputStreamInfo->flags : 0) );
+            paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputChannelCount, sampleRate );
             if( paerror != paNoError )
                 return paInvalidSampleRate;
         }
@@ -1756,10 +1491,9 @@ typedef struct
 static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers );
 static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
         PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
-        unsigned long winMmeSpecificFlags,
         unsigned long bytesPerHostSample,
         double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
-        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput );
+        unsigned int deviceCount, int isInput );
 static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError );
 static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
         unsigned long hostBufferCount,
@@ -1781,16 +1515,15 @@ static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionH
 
 static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
         PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
-        unsigned long winMmeSpecificFlags,
         unsigned long bytesPerHostSample,
         double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
-        unsigned int deviceCount, PaWinWaveFormatChannelMask channelMask, int isInput )
+        unsigned int deviceCount, int isInput )
 {
     PaError result;
     MMRESULT mmresult;
-    signed int i, j;
-    PaSampleFormat sampleFormat;
-    int waveFormatTag;
+    unsigned long bytesPerFrame;
+    WAVEFORMATEX wfx;
+    signed int i;
 
     /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
         has already been called to zero some fields */       
@@ -1818,98 +1551,64 @@ static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostA
             ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0;
     }
 
-    /* @todo at the moment we only use 16 bit sample format */
-    sampleFormat = paInt16;
-    waveFormatTag = SampleFormatAndWinWmmeSpecificFlagsToLinearWaveFormatTag( sampleFormat, winMmeSpecificFlags );
-
+    wfx.wFormatTag = WAVE_FORMAT_PCM;
+    wfx.nSamplesPerSec = (DWORD) sampleRate;
+    wfx.cbSize = 0;
+    
     for( i = 0; i < (signed int)deviceCount; ++i )
     {
-        PaWinWaveFormat waveFormat;
-        UINT winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );
-    
-        /* @todo: consider providing a flag or #define to not try waveformat extensible 
-           this could just initialize j to 1 the first time round. */
+        UINT winMmeDeviceId;
 
-        for( j = 0; j < 2; ++j )
-        {
-            if( j == 0 )
-            { 
-                /* first, attempt to open the device using WAVEFORMATEXTENSIBLE, 
-                    if this fails we fall back to WAVEFORMATEX */
-
-                PaWin_InitializeWaveFormatExtensible( &waveFormat, devices[i].channelCount, 
-                        sampleFormat, waveFormatTag, sampleRate, channelMask );
+        winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );
+        wfx.nChannels = (WORD)devices[i].channelCount;
 
-            }
-            else
-            {
-                /* retry with WAVEFORMATEX */
+        bytesPerFrame = wfx.nChannels * bytesPerHostSample;
 
-                PaWin_InitializeWaveFormatEx( &waveFormat, devices[i].channelCount, 
-                        sampleFormat, waveFormatTag, sampleRate );
-            }
+        wfx.nAvgBytesPerSec = (DWORD)(bytesPerFrame * sampleRate);
+        wfx.nBlockAlign = (WORD)bytesPerFrame;
+        wfx.wBitsPerSample = (WORD)((bytesPerFrame/wfx.nChannels) * 8);
 
-            /* REVIEW: consider not firing an event for input when a full duplex
-                stream is being used. this would probably depend on the
-                neverDropInput flag. */
+        /* REVIEW: consider not firing an event for input when a full duplex
+            stream is being used. this would probably depend on the
+            neverDropInput flag. */
 
-            if( isInput )
-            {
-                mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, 
-                                    (WAVEFORMATEX*)&waveFormat,
+        if( isInput )
+            mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx,
                                (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
-            }
-            else
-            {
-                mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, 
-                                    (WAVEFORMATEX*)&waveFormat,
+        else
+            mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx,
                                 (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
-            }
 
-            if( mmresult == MMSYSERR_NOERROR )
-            {
-                break; /* success */
-            }
-            else if( j == 0 )
-            {
-                continue; /* try again with WAVEFORMATEX */
-            }
-            else
+        if( mmresult != MMSYSERR_NOERROR )
+        {
+            switch( mmresult )
             {
-                switch( mmresult )
-                {
-                    case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
-                        result = paDeviceUnavailable;
-                        break;
-                    case MMSYSERR_NODRIVER:	    /* No device driver is present. */
-                        result = paDeviceUnavailable;
-                        break;
-                    case MMSYSERR_NOMEM:	    /* Unable to allocate or lock memory. */
-                        result = paInsufficientMemory;
-                        break;
+                case MMSYSERR_ALLOCATED:    /* Specified resource is already allocated. */
+                    result = paDeviceUnavailable;
+                    break;
+                case MMSYSERR_NODRIVER:	    /* No device driver is present. */
+                    result = paDeviceUnavailable;
+                    break;
+                case MMSYSERR_NOMEM:	    /* Unable to allocate or lock memory. */
+                    result = paInsufficientMemory;
+                    break;
 
-                    case MMSYSERR_BADDEVICEID:	/* Specified device identifier is out of range. */
-                        /* falls through */
-
-                    case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
-                                                    /* This can also occur if we try to open the device with an unsupported
-                                                     * number of channels. This is attempted when device*ChannelCountIsKnown is
-                                                     * set to 0. 
-                                                     */
-                        /* falls through */
-                    default:
-                        result = paUnanticipatedHostError;
-                        if( isInput )
-                        {
-                            PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
-                        }
-                        else
-                        {
-                            PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
-                        }
-                }
-                goto error;
+                case MMSYSERR_BADDEVICEID:	/* Specified device identifier is out of range. */
+                    /* falls through */
+                case WAVERR_BADFORMAT:      /* Attempted to open with an unsupported waveform-audio format. */
+                    /* falls through */
+                default:
+                    result = paUnanticipatedHostError;
+                    if( isInput )
+                    {
+                        PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+                    }
+                    else
+                    {
+                        PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+                    }
             }
+            goto error;
         }
     }
 
@@ -2130,7 +1829,7 @@ struct PaWinMmeStream
     /* Processing thread management -------------- */
     HANDLE abortEvent;
     HANDLE processingThread;
-    PA_THREAD_ID processingThreadId;
+    DWORD processingThreadId;
 
     char throttleProcessingThreadOnOverload; /* 0 -> don't throtte, non-0 -> throttle */
     int processingThreadPriority;
@@ -2151,7 +1850,6 @@ struct PaWinMmeStream
 static PaError ValidateWinMmeSpecificStreamInfo(
         const PaStreamParameters *streamParameters,
         const PaWinMmeStreamInfo *streamInfo,
-        unsigned long *winMmeSpecificFlags,
         char *throttleProcessingThreadOnOverload,
         unsigned long *deviceCount )
 {
@@ -2163,8 +1861,6 @@ static PaError ValidateWinMmeSpecificStreamInfo(
 	        return paIncompatibleHostApiSpecificStreamInfo;
 	    }
 
-        *winMmeSpecificFlags = streamInfo->flags;
-
 	    if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread )
 	        *throttleProcessingThreadOnOverload = 0;
             
@@ -2230,20 +1926,12 @@ static PaError ValidateInputChannelCounts(
         unsigned long deviceCount )
 {
     unsigned int i;
-    PaWinMmeDeviceInfo *inputDeviceInfo;
-    PaError paerror;
 
 	for( i=0; i < deviceCount; ++i )
 	{
-        if( devices[i].channelCount < 1 )
+		if( devices[i].channelCount < 1 || devices[i].channelCount
+					> hostApi->deviceInfos[ devices[i].device ]->maxInputChannels )
         	return paInvalidChannelCount;
-
-        inputDeviceInfo = 
-                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];
-
-        paerror = IsInputChannelCountSupported( inputDeviceInfo, devices[i].channelCount );
-        if( paerror != paNoError )
-            return paerror;
 	}
 
     return paNoError;
@@ -2255,20 +1943,12 @@ static PaError ValidateOutputChannelCounts(
         unsigned long deviceCount )
 {
     unsigned int i;
-    PaWinMmeDeviceInfo *outputDeviceInfo;
-    PaError paerror;
 
 	for( i=0; i < deviceCount; ++i )
 	{
-        if( devices[i].channelCount < 1 )
+		if( devices[i].channelCount < 1 || devices[i].channelCount
+					> hostApi->deviceInfos[ devices[i].device ]->maxOutputChannels )
         	return paInvalidChannelCount;
-
-        outputDeviceInfo = 
-                (PaWinMmeDeviceInfo*)hostApi->deviceInfos[ devices[i].device ];
-
-        paerror = IsOutputChannelCountSupported( outputDeviceInfo, devices[i].channelCount );
-        if( paerror != paNoError )
-            return paerror;
 	}
 
     return paNoError;
@@ -2301,17 +1981,14 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     PaSampleFormat inputSampleFormat, outputSampleFormat;
     double suggestedInputLatency, suggestedOutputLatency;
     PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
-    PaWinWaveFormatChannelMask inputChannelMask, outputChannelMask;
     unsigned long framesPerHostInputBuffer;
     unsigned long hostInputBufferCount;
     unsigned long framesPerHostOutputBuffer;
     unsigned long hostOutputBufferCount;
     unsigned long framesPerBufferProcessorCall;
     PaWinMmeDeviceAndChannelCount *inputDevices = 0;  /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
-    unsigned long winMmeSpecificInputFlags = 0;
     unsigned long inputDeviceCount = 0;            
     PaWinMmeDeviceAndChannelCount *outputDevices = 0;
-    unsigned long winMmeSpecificOutputFlags = 0;
     unsigned long outputDeviceCount = 0;                /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
     char throttleProcessingThreadOnOverload = 1;
 
@@ -2327,7 +2004,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
 		/* validate input hostApiSpecificStreamInfo */
         inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
 		result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo,
-                &winMmeSpecificInputFlags,
 				&throttleProcessingThreadOnOverload,
 				&inputDeviceCount );
 		if( result != paNoError ) return result;
@@ -2343,18 +2019,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
 
         hostInputSampleFormat =
             PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );
-
-        if( inputDeviceCount != 1 ){
-            /* always use direct speakers when using multi-device multichannel mode */
-            inputChannelMask = PAWIN_SPEAKER_DIRECTOUT;           
-        }
-        else
-        {
-            if( inputStreamInfo && inputStreamInfo->flags & paWinMmeUseChannelMask )
-                inputChannelMask = inputStreamInfo->channelMask;
-            else
-                inputChannelMask = PaWin_DefaultChannelMask( inputDevices[0].channelCount );
-        }
 	}
     else
     {
@@ -2377,7 +2041,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
 		/* validate output hostApiSpecificStreamInfo */
         outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
 		result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo,
-                &winMmeSpecificOutputFlags,
 				&throttleProcessingThreadOnOverload,
 				&outputDeviceCount );
 		if( result != paNoError ) return result;
@@ -2393,18 +2056,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
 
         hostOutputSampleFormat =
             PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );
-
-        if( outputDeviceCount != 1 ){
-            /* always use direct speakers when using multi-device multichannel mode */
-            outputChannelMask = PAWIN_SPEAKER_DIRECTOUT;           
-        }
-        else
-        {
-            if( outputStreamInfo && outputStreamInfo->flags & paWinMmeUseChannelMask )
-                outputChannelMask = outputStreamInfo->channelMask;
-            else
-                outputChannelMask = PaWin_DefaultChannelMask( outputDevices[0].channelCount );
-        }
     }
     else
     {
@@ -2427,14 +2078,6 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
         return paInvalidFlag; /* unexpected platform specific flag */
 
 
-    /* always disable clipping and dithering if we are outputting a raw spdif stream */
-    if( (winMmeSpecificOutputFlags & paWinMmeWaveFormatDolbyAc3Spdif)
-            || (winMmeSpecificOutputFlags & paWinMmeWaveFormatWmaSpdif) ){
-
-        streamFlags = streamFlags | paClipOff | paDitherOff;
-    }
-
-
     result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount,
                 &framesPerHostOutputBuffer, &hostOutputBufferCount,
                 inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo,
@@ -2533,18 +2176,16 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
     if( inputParameters )
     {
         result = InitializeWaveHandles( winMmeHostApi, &stream->input,
-                winMmeSpecificInputFlags,
                 stream->bufferProcessor.bytesPerHostInputSample, sampleRate,
-                inputDevices, inputDeviceCount, inputChannelMask, 1 /* isInput */ );
+                inputDevices, inputDeviceCount, 1 /* isInput */ );
         if( result != paNoError ) goto error;
     }
     
     if( outputParameters )
     {
         result = InitializeWaveHandles( winMmeHostApi, &stream->output,
-                winMmeSpecificOutputFlags,
                 stream->bufferProcessor.bytesPerHostOutputSample, sampleRate,
-                outputDevices, outputDeviceCount, outputChannelMask, 0 /* isInput */ );
+                outputDevices, outputDeviceCount, 0 /* isInput */ );
         if( result != paNoError ) goto error;
     }
 
@@ -2699,7 +2340,6 @@ static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream )
 
     for( i=0; i < stream->input.deviceCount; ++i )
     {
-        stream->input.waveHeaders[i][ stream->input.currentBufferIndex ].dwFlags &= ~WHDR_DONE;
         mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i],
                                     &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ],
                                     sizeof(WAVEHDR) );
@@ -2796,7 +2436,7 @@ static PaError CatchUpOutputBuffers( PaWinMmeStream *stream )
 }
 
 
-PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
+static DWORD WINAPI ProcessingThreadProc( void *pArg )
 {
     PaWinMmeStream *stream = (PaWinMmeStream *)pArg;
     HANDLE events[3];
@@ -3002,7 +2642,7 @@ PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
                         for( i=0; i<stream->input.deviceCount; ++i )
                         {
                              /* we have stored the number of channels in the buffer in dwUser */
-                            int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
+                            int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
                             
                             PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
                                     stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
@@ -3023,7 +2663,7 @@ PA_THREAD_FUNC ProcessingThreadProc( void *pArg )
                         for( i=0; i<stream->output.deviceCount; ++i )
                         {
                             /* we have stored the number of channels in the buffer in dwUser */
-                            int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+                            int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
 
                             PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                                     stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
@@ -3226,7 +2866,6 @@ static PaError StartStream( PaStream *s )
         {
             for( j=0; j<stream->input.deviceCount; ++j )
             {
-                stream->input.waveHeaders[j][i].dwFlags &= ~WHDR_DONE;
                 mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) );
                 if( mmresult != MMSYSERR_NOERROR )
                 {
@@ -3273,7 +2912,7 @@ static PaError StartStream( PaStream *s )
                     for( j=0; j<stream->output.deviceCount; ++j )
                     {
                         /* we have stored the number of channels in the buffer in dwUser */
-                        int channelCount = (int)stream->output.waveHeaders[j][i].dwUser;
+                        int channelCount = stream->output.waveHeaders[j][i].dwUser;
 
                         PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                                 stream->output.waveHeaders[j][i].lpData +
@@ -3349,7 +2988,7 @@ static PaError StartStream( PaStream *s )
         if( result != paNoError ) goto error;
 
         /* Create thread that waits for audio buffers to be ready for processing. */
-        stream->processingThread = CREATE_THREAD;
+        stream->processingThread = CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId );
         if( !stream->processingThread )
         {
             result = paUnanticipatedHostError;
@@ -3481,7 +3120,7 @@ static PaError StopStream( PaStream *s )
                 for( i=0; i<stream->output.deviceCount; ++i )
                 {
                     /* we have stored the number of channels in the buffer in dwUser */
-                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+                    int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
 
                     PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                             stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
@@ -3705,7 +3344,7 @@ static PaError ReadStream( PaStream* s,
         }
         else
         {
-            userBuffer = (void*)alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );
+            userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );
             if( !userBuffer )
                 return paInsufficientMemory;
             for( i = 0; i<stream->bufferProcessor.inputChannelCount; ++i )
@@ -3733,7 +3372,7 @@ static PaError ReadStream( PaStream* s,
                 for( i=0; i<stream->input.deviceCount; ++i )
                 {
                     /* we have stored the number of channels in the buffer in dwUser */
-                    int channelCount = (int)stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
+                    int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
 
                     PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
                             stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
@@ -3809,7 +3448,7 @@ static PaError WriteStream( PaStream* s,
         }
         else
         {
-            userBuffer = (const void*)alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );
+            userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );
             if( !userBuffer )
                 return paInsufficientMemory;
             for( i = 0; i<stream->bufferProcessor.outputChannelCount; ++i )
@@ -3838,7 +3477,7 @@ static PaError WriteStream( PaStream* s,
                 for( i=0; i<stream->output.deviceCount; ++i )
                 {
                     /* we have stored the number of channels in the buffer in dwUser */
-                    int channelCount = (int)stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+                    int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
 
                     PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
                             stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
diff --git a/portaudio/src/os/unix/pa_unix_hostapis.c b/portaudio/src/os/unix/pa_unix_hostapis.c
index 339e1b148..d695e1b19 100644
--- a/portaudio/src/os/unix/pa_unix_hostapis.c
+++ b/portaudio/src/os/unix/pa_unix_hostapis.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_unix_hostapis.c 1413 2009-05-24 17:00:36Z aknudsen $
+ * $Id: pa_unix_hostapis.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library UNIX initialization table
  *
  * Based on the Open Source API proposed by Ross Bencina
@@ -49,26 +49,10 @@ PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex
 PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
 /* Linux AudioScience HPI */
 PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
-PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
-PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
 
-/** Note that on Linux, ALSA is placed before OSS so that the former is preferred over the latter.
- */
 
 PaUtilHostApiInitializer *paHostApiInitializers[] =
     {
-#ifdef __linux__
-
-#ifdef PA_USE_ALSA
-        PaAlsa_Initialize,
-#endif
-
-#ifdef PA_USE_OSS
-        PaOSS_Initialize,
-#endif
-
-#else   /* __linux__ */
-
 #ifdef PA_USE_OSS
         PaOSS_Initialize,
 #endif
@@ -77,8 +61,6 @@ PaUtilHostApiInitializer *paHostApiInitializers[] =
         PaAlsa_Initialize,
 #endif
 
-#endif  /* __linux__ */
-
 #ifdef PA_USE_JACK
         PaJack_Initialize,
 #endif
@@ -90,15 +72,6 @@ PaUtilHostApiInitializer *paHostApiInitializers[] =
 #ifdef PA_USE_ASIHPI
         PaAsiHpi_Initialize,
 #endif
-
-#ifdef PA_USE_COREAUDIO
-        PaMacCore_Initialize,
-#endif
-
-#ifdef PA_USE_SKELETON
-        PaSkeleton_Initialize,
-#endif
-
         0   /* NULL terminated array */
     };
 
diff --git a/portaudio/src/os/unix/pa_unix_util.c b/portaudio/src/os/unix/pa_unix_util.c
index 18f806c50..1cb838752 100644
--- a/portaudio/src/os/unix/pa_unix_util.c
+++ b/portaudio/src/os/unix/pa_unix_util.c
@@ -1,5 +1,5 @@
 /*
- * $Id: pa_unix_util.c 1510 2010-06-10 08:05:29Z dmitrykos $
+ * $Id: pa_unix_util.c 1232 2007-06-16 14:49:43Z rossb $
  * Portable Audio I/O Library
  * UNIX platform-specific support functions
  *
@@ -51,13 +51,6 @@
 #include <math.h>
 #include <errno.h>
 
-#if defined(__APPLE__) && !defined(HAVE_MACH_ABSOLUTE_TIME)
-#define HAVE_MACH_ABSOLUTE_TIME
-#endif
-#ifdef HAVE_MACH_ABSOLUTE_TIME
-#include <mach/mach_time.h>
-#endif
-
 #include "pa_util.h"
 #include "pa_unix_util.h"
 #include "pa_debugprint.h"
@@ -125,47 +118,27 @@ void Pa_Sleep( long msec )
 #endif
 }
 
-#ifdef HAVE_MACH_ABSOLUTE_TIME
-/*
-    Discussion on the CoreAudio mailing list suggests that calling
-    gettimeofday (or anything else in the BSD layer) is not real-time
-    safe, so we use mach_absolute_time on OSX. This implementation is 
-    based on these two links:
-
-    Technical Q&A QA1398 - Mach Absolute Time Units
-    http://developer.apple.com/mac/library/qa/qa2004/qa1398.html
-
-    Tutorial: Performance and Time.
-    http://www.macresearch.org/tutorial_performance_and_time
+/*            *** NOT USED YET: ***
+static int usePerformanceCounter_;
+static double microsecondsPerTick_;
 */
 
-/* Scaler to convert the result of mach_absolute_time to seconds */
-static double machSecondsConversionScaler_ = 0.0; 
-#endif
-
 void PaUtil_InitializeClock( void )
 {
-#ifdef HAVE_MACH_ABSOLUTE_TIME
-    mach_timebase_info_data_t info;
-    kern_return_t err = mach_timebase_info( &info );
-    if( err == 0  )
-        machSecondsConversionScaler_ = 1e-9 * (double) info.numer / (double) info.denom;
-#endif
+    /* TODO */
 }
 
 
 PaTime PaUtil_GetTime( void )
 {
-#ifdef HAVE_MACH_ABSOLUTE_TIME
-    return mach_absolute_time() * machSecondsConversionScaler_;
-#elif defined(HAVE_CLOCK_GETTIME)
+#ifdef HAVE_CLOCK_GETTIME
     struct timespec tp;
     clock_gettime(CLOCK_REALTIME, &tp);
-    return (PaTime)(tp.tv_sec + tp.tv_nsec * 1e-9);
+    return (PaTime)(tp.tv_sec + tp.tv_nsec / 1.e9);
 #else
     struct timeval tv;
     gettimeofday( &tv, NULL );
-    return (PaTime) tv.tv_usec * 1e-6 + tv.tv_sec;
+    return (PaTime) tv.tv_usec / 1000000. + tv.tv_sec;
 #endif
 }
 
@@ -193,15 +166,9 @@ PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *e
     if( exitResult )
         *exitResult = paNoError;
 
-    /* If pthread_cancel is not supported (Android platform) whole this function can lead to indefinite waiting if 
-       working thread (callbackThread) has'n received any stop signals from outside, please keep 
-       this in mind when considering using PaUtil_CancelThreading
-    */
-#ifdef PTHREAD_CANCELED
     /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
     if( !wait )
         pthread_cancel( threading->callbackThread );   /* XXX: Safe to call this if the thread has exited on its own? */
-#endif
     pthread_join( threading->callbackThread, &pret );
 
 #ifdef PTHREAD_CANCELED
@@ -223,7 +190,7 @@ PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *e
 /* paUnixMainThread 
  * We have to be a bit careful with defining this global variable,
  * as explained below. */
-#ifdef __APPLE__
+#ifdef __apple__
 /* apple/gcc has a "problem" with global vars and dynamic libs.
    Initializing it seems to fix the problem.
    Described a bit in this thread:
@@ -433,19 +400,12 @@ PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResul
     {
         PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread ));
         /* XXX: Safe to call this if the thread has exited on its own? */
-#ifdef PTHREAD_CANCELED
         pthread_cancel( self->thread );
-#endif
     }
     PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread ));
     PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 );
 
-#ifdef PTHREAD_CANCELED
     if( pret && PTHREAD_CANCELED != pret )
-#else
-    /* !wait means the thread may have been canceled */
-    if( pret && wait )
-#endif
     {
         if( exitResult )
         {
@@ -519,11 +479,9 @@ PaError PaUnixMutex_Terminate( PaUnixMutex* self )
 PaError PaUnixMutex_Lock( PaUnixMutex* self )
 {
     PaError result = paNoError;
+    int oldState;
     
-#ifdef PTHREAD_CANCEL
-	int oldState;
     PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 );
-#endif
     PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 );
 
 error:
@@ -537,12 +495,10 @@ error:
 PaError PaUnixMutex_Unlock( PaUnixMutex* self )
 {
     PaError result = paNoError;
+    int oldState;
 
     PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 );
-#ifdef PTHREAD_CANCEL
-	int oldState;
     PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 );
-#endif
 
 error:
     return result;
diff --git a/portaudio/src/os/win/pa_win_hostapis.c b/portaudio/src/os/win/pa_win_hostapis.c
index df084cbfa..83f1e9141 100644
--- a/portaudio/src/os/win/pa_win_hostapis.c
+++ b/portaudio/src/os/win/pa_win_hostapis.c
@@ -1,9 +1,9 @@
 /*
- * $Id: pa_win_hostapis.c 1453 2010-02-16 09:46:08Z dmitrykos $
+ * $Id: pa_win_hostapis.c 1097 2006-08-26 08:27:53Z rossb $
  * Portable Audio I/O Library Windows initialization table
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina, Phil Burk
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -39,7 +39,7 @@
 /** @file
  @ingroup win_src
 
-    @brief Win32 host API initialization function table.
+    Win32 host API initialization function table.
 
     @todo Consider using PA_USE_WMME etc instead of PA_NO_WMME. This is what
     the Unix version does, we should consider being consistent.
@@ -58,7 +58,7 @@ PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiInd
 PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
 PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
 PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
-PaError PaWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
 
 #ifdef __cplusplus
 }
@@ -80,17 +80,17 @@ PaUtilHostApiInitializer *paHostApiInitializers[] =
         PaAsio_Initialize,
 #endif
 
+/*
 #ifndef PA_NO_WASAPI
-		PaWasapi_Initialize,
+		PaWinWasapi_Initialize,
 #endif
 
-/*
 #ifndef PA_NO_WDMKS
        PaWinWdm_Initialize,
 #endif
 */
 
-        //PaSkeleton_Initialize, /* just for testing */
+        PaSkeleton_Initialize, /* just for testing */
 
         0   /* NULL terminated array */
     };
diff --git a/portaudio/src/os/win/pa_win_util.c b/portaudio/src/os/win/pa_win_util.c
index 45eb26867..2f0cdf343 100644
--- a/portaudio/src/os/win/pa_win_util.c
+++ b/portaudio/src/os/win/pa_win_util.c
@@ -1,10 +1,10 @@
 /*
- * $Id: pa_win_util.c 1437 2009-12-10 08:10:08Z rossb $
+ * $Id: pa_win_util.c 1197 2007-05-04 13:07:10Z gordon_gidluck $
  * Portable Audio I/O Library
  * Win32 platform-specific support functions
  *
  * Based on the Open Source API proposed by Ross Bencina
- * Copyright (c) 1999-2008 Ross Bencina
+ * Copyright (c) 1999-2000 Ross Bencina
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
@@ -40,7 +40,7 @@
 /** @file
  @ingroup win_src
 
- @brief Win32 implementation of platform-specific PaUtil support functions.
+ Win32 platform-specific support functions.
 
     @todo Implement workaround for QueryPerformanceCounter() skipping forward
     bug. (see msdn kb Q274323).
@@ -51,10 +51,6 @@
 
 #include "pa_util.h"
 
-#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) && !defined(_WIN32_WCE) /* MSC version 6 and above */
-#pragma comment( lib, "winmm.lib" )
-#endif
-
 
 /*
    Track memory allocations to avoid leaks.
diff --git a/portaudio/src/os/win/pa_win_waveformat.c b/portaudio/src/os/win/pa_win_waveformat.c
deleted file mode 100644
index bbf616c34..000000000
--- a/portaudio/src/os/win/pa_win_waveformat.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * PortAudio Portable Real-Time Audio Library
- * Windows WAVEFORMAT* data structure utilities
- * portaudio.h should be included before this file.
- *
- * Copyright (c) 2007 Ross Bencina
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-#include <windows.h>
-#include <mmsystem.h>
-
-#include "portaudio.h"
-#include "pa_win_waveformat.h"
-
-
-#if !defined(WAVE_FORMAT_EXTENSIBLE)
-#define  WAVE_FORMAT_EXTENSIBLE         0xFFFE
-#endif
-
-static GUID pawin_ksDataFormatSubtypeGuidBase = 
-	{ (USHORT)(WAVE_FORMAT_PCM), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 };
-
-
-int PaWin_SampleFormatToLinearWaveFormatTag( PaSampleFormat sampleFormat )
-{
-    if( sampleFormat == paFloat32 )
-        return PAWIN_WAVE_FORMAT_IEEE_FLOAT;
-    
-    return PAWIN_WAVE_FORMAT_PCM;
-}
-
-
-void PaWin_InitializeWaveFormatEx( PaWinWaveFormat *waveFormat, 
-		int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate )
-{
-	WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat;
-    int bytesPerSample = Pa_GetSampleSize(sampleFormat);
-	unsigned long bytesPerFrame = numChannels * bytesPerSample;
-	
-    waveFormatEx->wFormatTag = waveFormatTag;
-	waveFormatEx->nChannels = (WORD)numChannels;
-	waveFormatEx->nSamplesPerSec = (DWORD)sampleRate;
-	waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame;
-	waveFormatEx->nBlockAlign = (WORD)bytesPerFrame;
-	waveFormatEx->wBitsPerSample = bytesPerSample * 8;
-	waveFormatEx->cbSize = 0;
-}
-
-
-void PaWin_InitializeWaveFormatExtensible( PaWinWaveFormat *waveFormat, 
-		int numChannels, PaSampleFormat sampleFormat, int waveFormatTag, double sampleRate,
-		PaWinWaveFormatChannelMask channelMask )
-{
-	WAVEFORMATEX *waveFormatEx = (WAVEFORMATEX*)waveFormat;
-    int bytesPerSample = Pa_GetSampleSize(sampleFormat);
-	unsigned long bytesPerFrame = numChannels * bytesPerSample;
-    GUID guid;
-
-	waveFormatEx->wFormatTag = WAVE_FORMAT_EXTENSIBLE;
-	waveFormatEx->nChannels = (WORD)numChannels;
-	waveFormatEx->nSamplesPerSec = (DWORD)sampleRate;
-	waveFormatEx->nAvgBytesPerSec = waveFormatEx->nSamplesPerSec * bytesPerFrame;
-	waveFormatEx->nBlockAlign = (WORD)bytesPerFrame;
-	waveFormatEx->wBitsPerSample = bytesPerSample * 8;
-	waveFormatEx->cbSize = 22;
-
-	*((WORD*)&waveFormat->fields[PAWIN_INDEXOF_WVALIDBITSPERSAMPLE]) =
-			waveFormatEx->wBitsPerSample;
-
-	*((DWORD*)&waveFormat->fields[PAWIN_INDEXOF_DWCHANNELMASK]) = channelMask;
-		
-    guid = pawin_ksDataFormatSubtypeGuidBase;
-    guid.Data1 = (USHORT)waveFormatTag;
-    *((GUID*)&waveFormat->fields[PAWIN_INDEXOF_SUBFORMAT]) = guid;
-}
-
-
-PaWinWaveFormatChannelMask PaWin_DefaultChannelMask( int numChannels )
-{
-	switch( numChannels ){
-		case 1:
-			return PAWIN_SPEAKER_MONO;
-		case 2:
-			return PAWIN_SPEAKER_STEREO; 
-		case 3:
-            return PAWIN_SPEAKER_FRONT_LEFT | PAWIN_SPEAKER_FRONT_CENTER | PAWIN_SPEAKER_FRONT_RIGHT;
-		case 4:
-			return PAWIN_SPEAKER_QUAD;
-		case 5:
-            return PAWIN_SPEAKER_QUAD | PAWIN_SPEAKER_FRONT_CENTER;
-		case 6:
-            /* The meaning of the PAWIN_SPEAKER_5POINT1 flag has changed over time:
-                http://msdn2.microsoft.com/en-us/library/aa474707.aspx
-               We use PAWIN_SPEAKER_5POINT1 (not PAWIN_SPEAKER_5POINT1_SURROUND)
-               because on some cards (eg Audigy) PAWIN_SPEAKER_5POINT1_SURROUND 
-               results in a virtual mixdown placing the rear output in the 
-               front _and_ rear speakers.
-            */
-			return PAWIN_SPEAKER_5POINT1; 
-        /* case 7: */
-		case 8:
-			return PAWIN_SPEAKER_7POINT1;
-	}
-
-    /* Apparently some Audigy drivers will output silence 
-       if the direct-out constant (0) is used. So this is not ideal.    
-    */
-	return  PAWIN_SPEAKER_DIRECTOUT;
-
-    /* Note that Alec Rogers proposed the following as an alternate method to 
-        generate the default channel mask, however it doesn't seem to be an improvement
-        over the above, since some drivers will matrix outputs mapping to non-present
-        speakers accross multiple physical speakers.
-
-        if(nChannels==1) {
-            pwfFormat->dwChannelMask = SPEAKER_FRONT_CENTER;
-        }
-        else {
-            pwfFormat->dwChannelMask = 0;
-            for(i=0; i<nChannels; i++)
-                pwfFormat->dwChannelMask = (pwfFormat->dwChannelMask << 1) | 0x1;
-        }
-    */
-}
diff --git a/portaudio/src/os/win/pa_win_wdmks_utils.c b/portaudio/src/os/win/pa_win_wdmks_utils.c
deleted file mode 100644
index a830f76df..000000000
--- a/portaudio/src/os/win/pa_win_wdmks_utils.c
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * PortAudio Portable Real-Time Audio Library
- * Windows WDM KS utilities
- *
- * Copyright (c) 1999 - 2007 Andrew Baldwin, Ross Bencina
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-#include <windows.h>
-#include <mmreg.h>
-#ifndef WAVE_FORMAT_IEEE_FLOAT
-    #define WAVE_FORMAT_IEEE_FLOAT 0x0003   // MinGW32 does not define this
-#endif    
-#ifndef _WAVEFORMATEXTENSIBLE_
-    #define _WAVEFORMATEXTENSIBLE_          // MinGW32 does not define this
-#endif
-#ifndef _INC_MMREG
-    #define _INC_MMREG                      // for STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
-#endif
-#include <winioctl.h>						// MinGW32 does not define this automatically
-#include <ks.h>
-#include <ksmedia.h>
-#include <stdio.h>                          // just for some development printfs
-
-#include "portaudio.h"
-#include "pa_util.h"
-#include "pa_win_wdmks_utils.h"
-
-#if !defined(PA_WDMKS_NO_KSGUID_LIB) && !defined(PAWIN_WDMKS_NO_KSGUID_LIB)
-    #if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
-        #pragma comment( lib, "ksguid.lib" )
-    #endif
-    #define pa_KSDATAFORMAT_TYPE_AUDIO            KSDATAFORMAT_TYPE_AUDIO
-    #define pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT    KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
-    #define pa_KSDATAFORMAT_SUBTYPE_PCM           KSDATAFORMAT_SUBTYPE_PCM
-    #define pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX  KSDATAFORMAT_SUBTYPE_WAVEFORMATEX
-    #define pa_KSMEDIUMSETID_Standard             KSMEDIUMSETID_Standard
-    #define pa_KSINTERFACESETID_Standard          KSINTERFACESETID_Standard
-    #define pa_KSPROPSETID_Pin                    KSPROPSETID_Pin
-#else
-    static const GUID pa_KSDATAFORMAT_TYPE_AUDIO            = { STATIC_KSDATAFORMAT_TYPE_AUDIO };
-    static const GUID pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT    = { STATIC_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT };
-    static const GUID pa_KSDATAFORMAT_SUBTYPE_PCM           = { STATIC_KSDATAFORMAT_SUBTYPE_PCM };
-    static const GUID pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX  = { STATIC_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX };
-    static const GUID pa_KSMEDIUMSETID_Standard             = { STATIC_KSMEDIUMSETID_Standard };
-    static const GUID pa_KSINTERFACESETID_Standard          = { STATIC_KSINTERFACESETID_Standard };
-    static const GUID pa_KSPROPSETID_Pin                    = { STATIC_KSPROPSETID_Pin };
-#endif
-
-
-#define pa_IS_VALID_WAVEFORMATEX_GUID(Guid)\
-    (!memcmp(((PUSHORT)&pa_KSDATAFORMAT_SUBTYPE_WAVEFORMATEX) + 1, ((PUSHORT)(Guid)) + 1, sizeof(GUID) - sizeof(USHORT)))
-
-
-
-static PaError WdmGetPinPropertySimple(
-    HANDLE  handle,
-    unsigned long pinId,
-    unsigned long property,
-    void* value,
-    unsigned long valueSize )
-{
-    DWORD bytesReturned;
-    KSP_PIN ksPProp;
-    ksPProp.Property.Set = pa_KSPROPSETID_Pin;
-    ksPProp.Property.Id = property;
-    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
-    ksPProp.PinId = pinId;
-    ksPProp.Reserved = 0;
-
-    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN),
-            value, valueSize, &bytesReturned, NULL ) == 0 || bytesReturned != valueSize )
-    {
-        return paUnanticipatedHostError;
-    }
-    else
-    {
-        return paNoError;
-    }
-}
-
-
-static PaError WdmGetPinPropertyMulti(
-    HANDLE handle,
-    unsigned long pinId,
-    unsigned long property,
-    KSMULTIPLE_ITEM** ksMultipleItem)
-{
-    unsigned long multipleItemSize = 0;
-    KSP_PIN ksPProp;
-    DWORD bytesReturned;
-
-    *ksMultipleItem = 0;
-
-    ksPProp.Property.Set = pa_KSPROPSETID_Pin;
-    ksPProp.Property.Id = property;
-    ksPProp.Property.Flags = KSPROPERTY_TYPE_GET;
-    ksPProp.PinId = pinId;
-    ksPProp.Reserved = 0;
-
-    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp.Property,
-            sizeof(KSP_PIN), NULL, 0, &multipleItemSize, NULL ) == 0 && GetLastError() != ERROR_MORE_DATA )
-    {
-        return paUnanticipatedHostError;
-    }
-
-    *ksMultipleItem = (KSMULTIPLE_ITEM*)PaUtil_AllocateMemory( multipleItemSize );
-    if( !*ksMultipleItem )
-    {
-        return paInsufficientMemory;
-    }
-
-    if( DeviceIoControl( handle, IOCTL_KS_PROPERTY, &ksPProp, sizeof(KSP_PIN),
-            (void*)*ksMultipleItem,  multipleItemSize, &bytesReturned, NULL ) == 0 || bytesReturned != multipleItemSize )
-    {
-        PaUtil_FreeMemory( ksMultipleItem );
-        return paUnanticipatedHostError;
-    }
-
-    return paNoError;
-}
-
-
-static int GetKSFilterPinCount( HANDLE deviceHandle )
-{
-    DWORD result;
-
-    if( WdmGetPinPropertySimple( deviceHandle, 0, KSPROPERTY_PIN_CTYPES, &result, sizeof(result) ) == paNoError ){
-        return result;
-    }else{
-        return 0;
-    }
-}
-
-
-static KSPIN_COMMUNICATION GetKSFilterPinPropertyCommunication( HANDLE deviceHandle, int pinId )
-{
-    KSPIN_COMMUNICATION result;
-
-    if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_COMMUNICATION, &result, sizeof(result) ) == paNoError ){
-        return result;
-    }else{
-        return KSPIN_COMMUNICATION_NONE;
-    }
-}
-
-
-static KSPIN_DATAFLOW GetKSFilterPinPropertyDataflow( HANDLE deviceHandle, int pinId )
-{
-    KSPIN_DATAFLOW result;
-
-    if( WdmGetPinPropertySimple( deviceHandle, pinId, KSPROPERTY_PIN_DATAFLOW, &result, sizeof(result) ) == paNoError ){
-        return result;
-    }else{
-        return (KSPIN_DATAFLOW)0;
-    }
-}
-
-
-static int KSFilterPinPropertyIdentifiersInclude( 
-        HANDLE deviceHandle, int pinId, unsigned long property, const GUID *identifierSet, unsigned long identifierId  )
-{
-    KSMULTIPLE_ITEM* item = NULL;
-    KSIDENTIFIER* identifier;
-    int i;
-    int result = 0;
-
-    if( WdmGetPinPropertyMulti( deviceHandle, pinId, property, &item) != paNoError )
-        return 0;
-    
-    identifier = (KSIDENTIFIER*)(item+1);
-
-    for( i = 0; i < (int)item->Count; i++ )
-    {
-        if( !memcmp( (void*)&identifier[i].Set, (void*)identifierSet, sizeof( GUID ) ) &&
-           ( identifier[i].Id == identifierId ) )
-        {
-            result = 1;
-            break;
-        }
-    }
-
-    PaUtil_FreeMemory( item );
-
-    return result;
-}
-
-
-/* return the maximum channel count supported by any pin on the device. 
-   if isInput is non-zero we query input pins, otherwise output pins.
-*/
-int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput )
-{
-    HANDLE deviceHandle;
-	ULONG i;
-    int pinCount, pinId;
-    int result = 0;
-    KSPIN_DATAFLOW requiredDataflowDirection = (isInput ? KSPIN_DATAFLOW_OUT : KSPIN_DATAFLOW_IN );
-    
-    if( !wcharDevicePath )
-        return 0;
-
-    deviceHandle = CreateFileW( (LPCWSTR)wcharDevicePath, FILE_SHARE_READ|FILE_SHARE_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL );
-    if( deviceHandle == INVALID_HANDLE_VALUE )
-        return 0;
-
-    pinCount = GetKSFilterPinCount( deviceHandle );
-    for( pinId = 0; pinId < pinCount; ++pinId )
-    {
-        KSPIN_COMMUNICATION communication = GetKSFilterPinPropertyCommunication( deviceHandle, pinId );
-        KSPIN_DATAFLOW dataflow = GetKSFilterPinPropertyDataflow( deviceHandle, pinId );
-        if( ( dataflow == requiredDataflowDirection ) &&
-                (( communication == KSPIN_COMMUNICATION_SINK) ||
-                 ( communication == KSPIN_COMMUNICATION_BOTH)) 
-             && ( KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
-                    KSPROPERTY_PIN_INTERFACES, &pa_KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_STREAMING )
-                || KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
-                    KSPROPERTY_PIN_INTERFACES, &pa_KSINTERFACESETID_Standard, KSINTERFACE_STANDARD_LOOPED_STREAMING ) )
-             && KSFilterPinPropertyIdentifiersInclude( deviceHandle, pinId, 
-                    KSPROPERTY_PIN_MEDIUMS, &pa_KSMEDIUMSETID_Standard, KSMEDIUM_STANDARD_DEVIO ) )
-         {
-            KSMULTIPLE_ITEM* item = NULL;
-            if( WdmGetPinPropertyMulti( deviceHandle, pinId, KSPROPERTY_PIN_DATARANGES, &item ) == paNoError )
-            {
-                KSDATARANGE *dataRange = (KSDATARANGE*)(item+1);
-
-                for( i=0; i < item->Count; ++i ){
-
-                    if( pa_IS_VALID_WAVEFORMATEX_GUID(&dataRange->SubFormat)
-                            || memcmp( (void*)&dataRange->SubFormat, (void*)&pa_KSDATAFORMAT_SUBTYPE_PCM, sizeof(GUID) ) == 0
-                            || memcmp( (void*)&dataRange->SubFormat, (void*)&pa_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(GUID) ) == 0
-                            || ( ( memcmp( (void*)&dataRange->MajorFormat, (void*)&pa_KSDATAFORMAT_TYPE_AUDIO, sizeof(GUID) ) == 0 )
-                                && ( memcmp( (void*)&dataRange->SubFormat, (void*)&KSDATAFORMAT_SUBTYPE_WILDCARD, sizeof(GUID) ) == 0 ) ) )
-                    {
-                        KSDATARANGE_AUDIO *dataRangeAudio = (KSDATARANGE_AUDIO*)dataRange;
-                        
-                        /*
-                        printf( ">>> %d %d %d %d %S\n", isInput, dataflow, communication, dataRangeAudio->MaximumChannels, devicePath );
-                       
-                        if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WAVEFORMATEX, sizeof(GUID) ) == 0 )
-                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WAVEFORMATEX\n" );
-                        else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_DSOUND, sizeof(GUID) ) == 0 )
-                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_DSOUND\n" );
-                        else if( memcmp((void*)&dataRange->Specifier, (void*)&KSDATAFORMAT_SPECIFIER_WILDCARD, sizeof(GUID) ) == 0 )
-                            printf( "\tspecifier: KSDATAFORMAT_SPECIFIER_WILDCARD\n" );
-                        else
-                            printf( "\tspecifier: ?\n" );
-                        */
-
-                        /*
-                            We assume that very high values for MaximumChannels are not useful and indicate
-                            that the driver isn't prepared to tell us the real number of channels which it supports.
-                        */
-                        if( dataRangeAudio->MaximumChannels  < 0xFFFFUL && (int)dataRangeAudio->MaximumChannels > result )
-                            result = (int)dataRangeAudio->MaximumChannels;
-                    }
-                    
-                    dataRange = (KSDATARANGE*)( ((char*)dataRange) + dataRange->FormatSize);
-                }
-
-                PaUtil_FreeMemory( item );
-            }
-        }
-    }
-    
-    CloseHandle( deviceHandle );
-    return result;
-}
diff --git a/portaudio/src/os/win/pa_win_wdmks_utils.h b/portaudio/src/os/win/pa_win_wdmks_utils.h
deleted file mode 100644
index f54035f45..000000000
--- a/portaudio/src/os/win/pa_win_wdmks_utils.h
+++ /dev/null
@@ -1,65 +0,0 @@
-#ifndef PA_WIN_WDMKS_UTILS_H
-#define PA_WIN_WDMKS_UTILS_H
-
-/*
- * PortAudio Portable Real-Time Audio Library
- * Windows WDM KS utilities
- *
- * Copyright (c) 1999 - 2007 Ross Bencina, Andrew Baldwin
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files
- * (the "Software"), to deal in the Software without restriction,
- * including without limitation the rights to use, copy, modify, merge,
- * publish, distribute, sublicense, and/or sell copies of the Software,
- * and to permit persons to whom the Software is furnished to do so,
- * subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
- * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/*
- * The text above constitutes the entire PortAudio license; however, 
- * the PortAudio community also makes the following non-binding requests:
- *
- * Any person wishing to distribute modifications to the Software is
- * requested to send the modifications to the original developer so that
- * they can be incorporated into the canonical version. It is also 
- * requested that these non-binding requests be included along with the 
- * license above.
- */
-
-/** @file
- @brief Utilities for working with the Windows WDM KS API
-*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
-    Query for the maximum number of channels supported by any pin of the
-    specified device. Returns 0 if the query fails for any reason.
-
-    @param wcharDevicePath A system level PnP interface path, supplied as a WCHAR unicode string.
-    Declard as void* to avoid introducing a dependency on wchar_t here.
-
-    @param isInput A flag specifying whether to query for input (non-zero) or output (zero) channels.
-*/
-int PaWin_WDMKS_QueryFilterMaximumChannelCount( void *wcharDevicePath, int isInput );
-
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* PA_WIN_WDMKS_UTILS_H */
\ No newline at end of file
diff --git a/portaudio/src/os/win/pa_x86_plain_converters.c b/portaudio/src/os/win/pa_x86_plain_converters.c
index 4fcde40cb..63b058dfa 100644
--- a/portaudio/src/os/win/pa_x86_plain_converters.c
+++ b/portaudio/src/os/win/pa_x86_plain_converters.c
@@ -124,13 +124,13 @@ static const double ditheredInt16Scaler_ = 0x7FFE;
 
 #define PA_DITHER_BITS_   (15)
 /* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */
-#define PA_FLOAT_DITHER_SCALE_  (1.0F / ((1<<PA_DITHER_BITS_)-1))
+#define PA_FLOAT_DITHER_SCALE_  (1.0 / ((1<<PA_DITHER_BITS_)-1))
 static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;
 #define PA_DITHER_SHIFT_  ((32 - PA_DITHER_BITS_) + 1)
 
 /* -------------------------------------------------------------------------- */
 
-#if defined(_WIN64) || defined(_WIN32_WCE)
+#ifdef _WIN64
 
 /*
 	-EMT64/AMD64 uses different asm
diff --git a/portmidi/CHANGELOG.txt b/portmidi/CHANGELOG.txt
index 986137ea6..fd118e814 100644
--- a/portmidi/CHANGELOG.txt
+++ b/portmidi/CHANGELOG.txt
@@ -1,14 +1,4 @@
 /* CHANGELOG FOR PORTMIDI
- *
- * 02Jan09 Roger Dannenberg
- * - Created Java interface and wrote PmDefaults application to set
- *   values for Pm_GetDefaultInputDeviceID() and 
- *   Pm_GetDefaultOutputDeviceID(). Other fixes.
- *
- * 19Jun08 Roger Dannenberg and Austin Sung
- * - Removed USE_DLL_FOR_CLEANUP -- Windows 2000 through Vista seem to be
- *   fixed now, and can recover if MIDI ports are left open
- * - Various other minor patches
  *
  * 17Jan07 Roger Dannenberg
  * - Lots more help for Common Lisp user in pm_cl
diff --git a/portmidi/README.txt b/portmidi/README.txt
index 2d2d6fb95..0ab950d03 100644
--- a/portmidi/README.txt
+++ b/portmidi/README.txt
@@ -1,8 +1,7 @@
 README for PortMidi
+Roger Dannenberg
 
-Roger B. Dannenberg
-
-VERSION: please use "svn info" to get info.
+VERSION: this is the 17-Jan-07 version of PortMidi.
 
 Documentation for PortMidi is found in pm_common/portmidi.h.
 
@@ -28,7 +27,7 @@ ERROR HANDLING
 
 Error handling turned out to be much more complicated than expected.
 PortMidi functions return error codes that the caller can check.
-In addition, errors may occur asynchronously due to MIDI input.
+In addition, errors may occur asynchronously due to MIDI input. 
 However, for Windows, there are virtually no errors that can
 occur if the code is correct and not passing bogus values. One
 exception is an error that the system is out of memory, but my
@@ -40,8 +39,8 @@ Ordinarily, the caller checks for an error code. If the error is
 system-dependent, pmHostError is returned and the caller can
 call Pm_GetHostErrorText to get a text description of the error.
 
-Host error codes are system-specific and are recorded in the
-system-specific data allocated for each open MIDI port.
+Host error codes are system-specific and are recorded in the 
+system-specific data allocated for each open MIDI port. 
 However, if an error occurs on open or close,
 we cannot store the error with the device because there will be
 no device data (assuming PortMidi cleans up after devices that
@@ -57,7 +56,7 @@ overhead even if the user does not want to look at the error data.
 
 The system-specific Read, Write, Poll, etc. implementations should
 check for asynchronous errors and return immediately if one is
-found so that these get reported. This happens in the Mac OS X
+found so that these get reported. This happens in the Mac OS X 
 code, where lots of things are happening in callbacks, but again,
 in Windows, there are no error codes recorded in callbacks.
 
@@ -65,7 +64,7 @@ DEBUGGING
 
 If you are building a console application for research, we suggest
 compiling with the option PM_CHECK_ERRORS. This will insert a
-check for error return values at the end of each PortMidi
+check for error return values at the end of each PortMidi 
 function. If an error is encountered, a text message is printed
 using printf(), the user is asked to type ENTER, and then exit(-1)
 is called to clean up and terminate the program.
diff --git a/portmidi/license.txt b/portmidi/license.txt
index c757b3713..b04523be4 100644
--- a/portmidi/license.txt
+++ b/portmidi/license.txt
@@ -3,10 +3,10 @@
  *
  * license.txt -- a copy of the PortMidi copyright notice and license information
  *
- * Latest version available at: http://sourceforge.net/projects/portmedia
+ * Latest version available at: http://www.cs.cmu.edu/~music/portmidi/
  *
  * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
- * Copyright (c) 2001-2009 Roger B. Dannenberg
+ * Copyright (c) 2001-2006 Roger B. Dannenberg
  *
  * Permission is hereby granted, free of charge, to any person obtaining
  * a copy of this software and associated documentation files
diff --git a/portmidi/pm_common/pminternal.h b/portmidi/pm_common/pminternal.h
index bd1e68ee4..b8c032325 100644
--- a/portmidi/pm_common/pminternal.h
+++ b/portmidi/pm_common/pminternal.h
@@ -21,8 +21,6 @@
 extern "C" {
 #endif
 
-extern int pm_initialized; /* see note in portmidi.c */
-
 /* these are defined in system-specific file */
 void *pm_alloc(size_t s);
 void pm_free(void *ptr);
@@ -104,8 +102,16 @@ typedef struct pm_internal_struct {
     PmTimeProcPtr time_proc; /* where to get the time */
     void *time_info; /* pass this to get_time() */
     long buffer_len; /* how big is the buffer or queue? */
+#ifdef NEWBUFFER
     PmQueue *queue;
-
+#else
+    PmEvent *buffer; /* storage for: 
+                        - midi input 
+                        - midi output w/latency != 0 */
+    long head;
+    long tail;
+    int overflow; /* set to non-zero if input is dropped */
+#endif
     long latency; /* time delay in ms between timestamps and actual output */
                   /* set to zero to get immediate, simple blocking output */
                   /* if latency is zero, timestamps will be ignored; */
@@ -137,7 +143,7 @@ typedef struct pm_internal_struct {
      * important
      */
     unsigned char *fill_base; /* addr of ptr to sysex data */
-    unsigned long *fill_offset_ptr; /* offset of next sysex byte */
+    int *fill_offset_ptr; /* offset of next sysex byte */
     int fill_length; /* how many sysex bytes to write */
 } PmInternal;
 
@@ -170,8 +176,6 @@ void pm_read_short(PmInternal *midi, PmEvent *event);
 #define is_real_time(msg) \
     ((Pm_MessageStatus(msg) & MIDI_REALTIME_MASK) == MIDI_REALTIME_MASK)
 
-int pm_find_default_device(char *pattern, int is_input);
-
 #ifdef __cplusplus
 }
 #endif
diff --git a/portmidi/pm_common/pmutil.c b/portmidi/pm_common/pmutil.c
index eb3d80a44..42f386c1d 100644
--- a/portmidi/pm_common/pmutil.c
+++ b/portmidi/pm_common/pmutil.c
@@ -1,9 +1,9 @@
 /* pmutil.c -- some helpful utilities for building midi
                applications that use PortMidi
  */
-#include <stdlib.h>
-#include <assert.h>
-#include <string.h>
+#include "stdlib.h"
+#include "assert.h"
+#include "memory.h"
 #include "portmidi.h"
 #include "pmutil.h"
 #include "pminternal.h"
@@ -38,10 +38,11 @@ typedef struct {
 
 PmQueue *Pm_QueueCreate(long num_msgs, long bytes_per_msg)
 {
+    PmQueueRep *queue = (PmQueueRep *) pm_alloc(sizeof(PmQueueRep));
     int int32s_per_msg = ((bytes_per_msg + sizeof(int32) - 1) &
                           ~(sizeof(int32) - 1)) / sizeof(int32);
-    PmQueueRep *queue = (PmQueueRep *) pm_alloc(sizeof(PmQueueRep));
-    if (!queue) /* memory allocation failed */
+    /* arg checking */
+    if (!queue) 
         return NULL;
 
     /* need extra word per message for non-zero encoding */
@@ -76,7 +77,7 @@ PmError Pm_QueueDestroy(PmQueue *q)
 {
     PmQueueRep *queue = (PmQueueRep *) q;
         
-    /* arg checking */
+        /* arg checking */
     if (!queue || !queue->buffer || !queue->peek) 
                 return pmBadPtr;
     
@@ -106,9 +107,16 @@ PmError Pm_Dequeue(PmQueue *q, void *msg)
         return pmBufferOverflow;
     }
     if (queue->peek_flag) {
+#ifdef QUEUE_DEBUG
+        printf("Pm_Dequeue returns peek msg:");
+        for (i = 0; i < queue->msg_size - 1; i++) {
+            printf(" %d", queue->peek[i]);
+        }
+        printf("\n");
+#endif
         memcpy(msg, queue->peek, (queue->msg_size - 1) * sizeof(int32));
         queue->peek_flag = FALSE;
-        return pmGotData;
+        return 1;
     }
 
     head = queue->head;
@@ -140,9 +148,16 @@ PmError Pm_Dequeue(PmQueue *q, void *msg)
      */
     for (i = queue->msg_size - 1; i >= 0; i--) {
         if (!queue->buffer[head + i]) {
-            return pmNoData;
+            return 0;
         }
     }
+#ifdef QUEUE_DEBUG
+    printf("Pm_Dequeue:");
+    for (i = 0; i < queue->msg_size; i++) {
+        printf(" %d", queue->buffer[head + i]);
+    }
+    printf("\n");
+#endif
     memcpy(msg, (char *) &queue->buffer[head + 1], 
            sizeof(int32) * (queue->msg_size - 1));
     /* fix up zeros */
@@ -161,7 +176,7 @@ PmError Pm_Dequeue(PmQueue *q, void *msg)
     head += queue->msg_size;
     if (head == queue->len) head = 0;
     queue->head = head;
-    return pmGotData; /* success */
+    return 1; /* success */
 }
 
 
@@ -170,11 +185,10 @@ PmError Pm_SetOverflow(PmQueue *q)
 {
     PmQueueRep *queue = (PmQueueRep *) q;
     long tail;
-    /* arg checking */
-    if (!queue)
-        return pmBadPtr;
     /* no more enqueue until receiver acknowledges overflow */
     if (queue->overflow) return pmBufferOverflow;
+    if (!queue)
+        return pmBadPtr;
     tail = queue->tail;
     queue->overflow = tail + 1;
     return pmBufferOverflow;
@@ -188,11 +202,12 @@ PmError Pm_Enqueue(PmQueue *q, void *msg)
     int i;
     int32 *src = (int32 *) msg;
     int32 *ptr;
+
     int32 *dest;
+
     int rslt;
-    if (!queue) 
-        return pmBadPtr;
     /* no more enqueue until receiver acknowledges overflow */
+    if (!queue) return pmBadPtr;
     if (queue->overflow) return pmBufferOverflow;
     rslt = Pm_QueueFull(q);
     /* already checked above: if (rslt == pmBadPtr) return rslt; */
@@ -216,6 +231,13 @@ PmError Pm_Enqueue(PmQueue *q, void *msg)
         dest++;
     }
     *ptr = i;
+#ifdef QUEUE_DEBUG
+    printf("Pm_Enqueue:");
+    for (i = 0; i < queue->msg_size; i++) {
+        printf(" %d", queue->buffer[tail + i]);
+    }
+    printf("\n");
+#endif
     tail += queue->msg_size;
     if (tail == queue->len) tail = 0;
     queue->tail = tail;
@@ -224,18 +246,18 @@ PmError Pm_Enqueue(PmQueue *q, void *msg)
 
 
 int Pm_QueueEmpty(PmQueue *q)
-{
+{ 
     PmQueueRep *queue = (PmQueueRep *) q;
-    return (!queue) ||  /* null pointer -> return "empty" */
-           (queue->buffer[queue->head] == 0 && !queue->peek_flag);
+    if (!queue) return TRUE;
+    return (queue->buffer[queue->head] == 0);
 }
 
 
 int Pm_QueueFull(PmQueue *q)
 {
+    PmQueueRep *queue = (PmQueueRep *) q;
     int tail;
     int i; 
-    PmQueueRep *queue = (PmQueueRep *) q;
     /* arg checking */
     if (!queue)
         return pmBadPtr;
@@ -249,12 +271,12 @@ int Pm_QueueFull(PmQueue *q)
     return FALSE;
 }
 
-
 void *Pm_QueuePeek(PmQueue *q)
 {
+    PmQueueRep *queue = (PmQueueRep *) q;
     PmError rslt;
     long temp;
-    PmQueueRep *queue = (PmQueueRep *) q;
+
     /* arg checking */
     if (!queue)
         return NULL;
diff --git a/portmidi/pm_common/pmutil.h b/portmidi/pm_common/pmutil.h
index 10a85ffba..8e4294670 100644
--- a/portmidi/pm_common/pmutil.h
+++ b/portmidi/pm_common/pmutil.h
@@ -78,9 +78,6 @@ PmError Pm_Enqueue(PmQueue *queue, void *msg);
     Pm_Dequeue() could still return 0 after Pm_QueueEmpty() returns
     false. On the other hand, Pm_QueueFull() is pessimistic: if it
     returns false, then Pm_Enqueue() is guaranteed to succeed. 
-
-    Error conditions: Pm_QueueFull() returns pmBadPtr if queue is NULL.
-    Pm_QueueEmpty() returns FALSE if queue is NULL.
  */
 int Pm_QueueFull(PmQueue *queue);
 int Pm_QueueEmpty(PmQueue *queue);
diff --git a/portmidi/pm_common/portmidi.c b/portmidi/pm_common/portmidi.c
index 79329835d..71988e471 100644
--- a/portmidi/pm_common/portmidi.c
+++ b/portmidi/pm_common/portmidi.c
@@ -1,1124 +1,1184 @@
-#ifdef _MSC_VER
- #pragma warning(disable: 4244) // stop warnings about downsize typecasts
- #pragma warning(disable: 4018) // stop warnings about signed/unsigned
-#endif
-
-#include "stdlib.h"
-#include "string.h"
-#include "portmidi.h"
-#include "porttime.h"
-#include "pmutil.h"
-#include "pminternal.h"
-#include <assert.h>
-
-#define MIDI_CLOCK      0xf8
-#define MIDI_ACTIVE     0xfe
-#define MIDI_STATUS_MASK 0x80
-#define MIDI_SYSEX      0xf0
-#define MIDI_EOX        0xf7
-#define MIDI_START      0xFA
-#define MIDI_STOP       0xFC
-#define MIDI_CONTINUE   0xFB
-#define MIDI_F9         0xF9
-#define MIDI_FD         0xFD
-#define MIDI_RESET      0xFF
-#define MIDI_NOTE_ON    0x90
-#define MIDI_NOTE_OFF   0x80
-#define MIDI_CHANNEL_AT 0xD0
-#define MIDI_POLY_AT    0xA0
-#define MIDI_PROGRAM    0xC0
-#define MIDI_CONTROL    0xB0
-#define MIDI_PITCHBEND  0xE0
-#define MIDI_MTC        0xF1
-#define MIDI_SONGPOS    0xF2
-#define MIDI_SONGSEL    0xF3
-#define MIDI_TUNE       0xF6
-
-#define is_empty(midi) ((midi)->tail == (midi)->head)
-
-/* this is not static so that pm_init can set it directly if
- *   (see pmmac.c:pm_init())
- */
-int pm_initialized = FALSE;
-
-int pm_hosterror;
-char pm_hosterror_text[PM_HOST_ERROR_MSG_LEN];
-
-#ifdef PM_CHECK_ERRORS
-
-#include <stdio.h>
-
-#define STRING_MAX 80
-
-static void prompt_and_exit(void)
-{
-    char line[STRING_MAX];
-    printf("type ENTER...");
-    fgets(line, STRING_MAX, stdin);
-    /* this will clean up open ports: */
-    exit(-1);
-}
-
-
-static PmError pm_errmsg(PmError err)
-{
-    if (err == pmHostError) {
-        /* it seems pointless to allocate memory and copy the string,
-         * so I will do the work of Pm_GetHostErrorText directly
-         */
-        printf("PortMidi found host error...\n  %s\n", pm_hosterror_text);
-        pm_hosterror = FALSE;
-        pm_hosterror_text[0] = 0; /* clear the message */
-        prompt_and_exit();
-    } else if (err < 0) {
-        printf("PortMidi call failed...\n  %s\n", Pm_GetErrorText(err));
-        prompt_and_exit();
-    }
-    return err;
-}
-#else
-#define pm_errmsg(err) err
-#endif
-
-/*
-====================================================================
-system implementation of portmidi interface
-====================================================================
-*/
-
-int pm_descriptor_max = 0;
-int pm_descriptor_index = 0;
-descriptor_type descriptors = NULL;
-
-/* pm_add_device -- describe interface/device pair to library 
- *
- * This is called at intialization time, once for each 
- * interface (e.g. DirectSound) and device (e.g. SoundBlaster 1)
- * The strings are retained but NOT COPIED, so do not destroy them!
- *
- * returns pmInvalidDeviceId if device memory is exceeded
- * otherwise returns pmNoError
- */
-PmError pm_add_device(char *interf, char *name, int input, 
-                      void *descriptor, pm_fns_type dictionary) {
-    if (pm_descriptor_index >= pm_descriptor_max) {
-        // expand descriptors
-        descriptor_type new_descriptors = (descriptor_type) 
-            pm_alloc(sizeof(descriptor_node) * (pm_descriptor_max + 32));
-        if (!new_descriptors) return pmInsufficientMemory;
-        if (descriptors) {
-            memcpy(new_descriptors, descriptors, 
-                   sizeof(descriptor_node) * pm_descriptor_max);
-            free(descriptors);
-        }
-        pm_descriptor_max += 32;
-        descriptors = new_descriptors;
-    }
-    descriptors[pm_descriptor_index].pub.interf = interf;
-    descriptors[pm_descriptor_index].pub.name = name;
-    descriptors[pm_descriptor_index].pub.input = input;
-    descriptors[pm_descriptor_index].pub.output = !input;
-
-    /* default state: nothing to close (for automatic device closing) */
-    descriptors[pm_descriptor_index].pub.opened = FALSE;
-
-    /* ID number passed to win32 multimedia API open */
-    descriptors[pm_descriptor_index].descriptor = descriptor;
-    
-    /* points to PmInternal, allows automatic device closing */
-    descriptors[pm_descriptor_index].internalDescriptor = NULL;
-
-    descriptors[pm_descriptor_index].dictionary = dictionary;
-    
-    pm_descriptor_index++;
-    
-    return pmNoError;
-}
-
-
-/* utility to look up device, given a pattern, 
-   note: pattern is modified
- */
-int pm_find_default_device(char *pattern, int is_input)
-{
-    int id = pmNoDevice;
-    int i;
-    /* first parse pattern into name, interf parts */
-    char *interf_pref = ""; /* initially assume it is not there */
-    char *name_pref = strstr(pattern, ", ");
-
-    if (name_pref) { /* found separator, adjust the pointer */
-        interf_pref = pattern;
-        name_pref[0] = 0;
-        name_pref += 2;
-    } else {
-        name_pref = pattern; /* whole string is the name pattern */
-    }
-    for (i = 0; i < pm_descriptor_index; i++) {
-        const PmDeviceInfo *info = Pm_GetDeviceInfo(i);
-        if (info->input == is_input &&
-            strstr(info->name, name_pref) &&
-            strstr(info->interf, interf_pref)) {
-            id = i;
-            break;
-        }
-    }    
-    return id;
-}
-
-
-/*
-====================================================================
-portmidi implementation
-====================================================================
-*/
-
-int Pm_CountDevices( void ) {
-    Pm_Initialize();
-    /* no error checking -- Pm_Initialize() does not fail */
-    return pm_descriptor_index;
-}
-
-
-const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id ) {
-    Pm_Initialize(); /* no error check needed */
-    if (id >= 0 && id < pm_descriptor_index) {
-        return &descriptors[id].pub;
-    }
-    return NULL;
-}
-
-/* pm_success_fn -- "noop" function pointer */
-PmError pm_success_fn(PmInternal *midi) {
-    return pmNoError;
-}
-
-/* none_write -- returns an error if called */
-PmError none_write_short(PmInternal *midi, PmEvent *buffer) {
-    return pmBadPtr;
-}
-
-/* pm_fail_timestamp_fn -- placeholder for begin_sysex and flush */
-PmError pm_fail_timestamp_fn(PmInternal *midi, PmTimestamp timestamp) {
-    return pmBadPtr;
-}
-
-PmError none_write_byte(PmInternal *midi, unsigned char byte, 
-                        PmTimestamp timestamp) {
-    return pmBadPtr;
-}
-
-/* pm_fail_fn -- generic function, returns error if called */
-PmError pm_fail_fn(PmInternal *midi) {
-    return pmBadPtr;
-}
-
-static PmError none_open(PmInternal *midi, void *driverInfo) {
-    return pmBadPtr;
-}
-static void none_get_host_error(PmInternal * midi, char * msg, unsigned int len) {
-    strcpy(msg, "");
-}
-static unsigned int none_has_host_error(PmInternal * midi) {
-    return FALSE;
-}
-PmTimestamp none_synchronize(PmInternal *midi) {
-    return 0;
-}
-
-#define none_abort pm_fail_fn
-#define none_close pm_fail_fn
-
-pm_fns_node pm_none_dictionary = {
-    none_write_short,
-    none_sysex,
-    none_sysex,
-    none_write_byte,
-    none_write_short,
-    none_write_flush,
-    none_synchronize,
-    none_open,
-    none_abort, 
-    none_close,
-    none_poll,
-    none_has_host_error,
-    none_get_host_error 
-};
-
-
-const char *Pm_GetErrorText( PmError errnum ) {
-    const char *msg;
-
-    switch(errnum)
-    {
-    case pmNoError:                  
-        msg = ""; 
-        break;
-    case pmHostError:                
-        msg = "PortMidi: `Host error'"; 
-        break;
-    case pmInvalidDeviceId:          
-        msg = "PortMidi: `Invalid device ID'"; 
-        break;
-    case pmInsufficientMemory:       
-        msg = "PortMidi: `Insufficient memory'"; 
-        break;
-    case pmBufferTooSmall:           
-        msg = "PortMidi: `Buffer too small'"; 
-        break;
-    case pmBadPtr:                   
-        msg = "PortMidi: `Bad pointer'"; 
-        break;
-    case pmInternalError:            
-        msg = "PortMidi: `Internal PortMidi Error'"; 
-        break;
-    case pmBufferOverflow:
-        msg = "PortMidi: `Buffer overflow'";
-        break;
-    case pmBadData:
-        msg = "PortMidi: `Invalid MIDI message Data'";
-        break;
-    case pmBufferMaxSize:
-        msg = "PortMidi: `Buffer cannot be made larger'";
-        break;
-    default:                         
-        msg = "PortMidi: `Illegal error number'"; 
-        break;
-    }
-    return msg;
-}
-
-
-/* This can be called whenever you get a pmHostError return value.
- * The error will always be in the global pm_hosterror_text.
- */
-void Pm_GetHostErrorText(char * msg, unsigned int len) {
-    assert(msg);
-    assert(len > 0);
-    if (pm_hosterror) {
-        strncpy(msg, (char *) pm_hosterror_text, len);
-        pm_hosterror = FALSE;
-        pm_hosterror_text[0] = 0; /* clear the message; not necessary, but it
-                                     might help with debugging */
-        msg[len - 1] = 0; /* make sure string is terminated */
-    } else {
-        msg[0] = 0; /* no string to return */
-    }
-}
-
-
-int Pm_HasHostError(PortMidiStream * stream) {
-    if (pm_hosterror) return TRUE;
-    if (stream) {
-        PmInternal * midi = (PmInternal *) stream;
-        pm_hosterror = (*midi->dictionary->has_host_error)(midi);
-        if (pm_hosterror) {
-            midi->dictionary->host_error(midi, pm_hosterror_text, 
-                                         PM_HOST_ERROR_MSG_LEN);
-            /* now error message is global */
-            return TRUE;
-        }
-    }
-    return FALSE;
-}
-
-
-PmError Pm_Initialize( void ) {
-    if (!pm_initialized) {
-        pm_hosterror = FALSE;
-        pm_hosterror_text[0] = 0; /* the null string */
-        pm_init();
-        pm_initialized = TRUE;
-    }
-    return pmNoError;
-}
-
-
-PmError Pm_Terminate( void ) {
-    if (pm_initialized) {
-        pm_term();
-        // if there are no devices, descriptors might still be NULL
-        if (descriptors != NULL) {
-            free(descriptors);
-            descriptors = NULL;
-        }
-        pm_descriptor_index = 0;
-        pm_descriptor_max = 0;
-        pm_initialized = FALSE;
-    }
-    return pmNoError;
-}
-
-
-/* Pm_Read -- read up to length longs from source into buffer */
-/*
- * returns number of longs actually read, or error code
- */
-int Pm_Read(PortMidiStream *stream, PmEvent *buffer, long length) {
-    PmInternal *midi = (PmInternal *) stream;
-    int n = 0;
-    PmError err = pmNoError;
-    pm_hosterror = FALSE;
-    /* arg checking */
-    if(midi == NULL)
-        err = pmBadPtr;
-    else if(!descriptors[midi->device_id].pub.opened)
-        err = pmBadPtr;
-    else if(!descriptors[midi->device_id].pub.input)
-        err = pmBadPtr;    
-    /* First poll for data in the buffer...
-     * This either simply checks for data, or attempts first to fill the buffer
-     * with data from the MIDI hardware; this depends on the implementation.
-     * We could call Pm_Poll here, but that would redo a lot of redundant
-     * parameter checking, so I copied some code from Pm_Poll to here: */
-    else err = (*(midi->dictionary->poll))(midi);
-
-    if (err != pmNoError) {
-        if (err == pmHostError) {
-            midi->dictionary->host_error(midi, pm_hosterror_text, 
-                                         PM_HOST_ERROR_MSG_LEN);
-          pm_hosterror = TRUE;
-        }
-        return pm_errmsg(err);
-    }
-
-    while (n < length) {
-        PmError err = Pm_Dequeue(midi->queue, buffer++);
-        if (err == pmBufferOverflow) {
-            /* ignore the data we have retreived so far */
-            return pm_errmsg(pmBufferOverflow);
-        } else if (err == 0) { /* empty queue */
-            break;
-        }
-        n++;
-    }
-    return n;
-}
-
-PmError Pm_Poll( PortMidiStream *stream )
-{
-    PmInternal *midi = (PmInternal *) stream;
-    PmError err;
-
-    pm_hosterror = FALSE;
-    /* arg checking */
-    if(midi == NULL)
-        err = pmBadPtr;
-    else if (!descriptors[midi->device_id].pub.opened)
-        err = pmBadPtr;
-    else if (!descriptors[midi->device_id].pub.input)
-        err = pmBadPtr;
-    else
-        err = (*(midi->dictionary->poll))(midi);
-
-    if (err != pmNoError) {
-        if (err == pmHostError) {
-            midi->dictionary->host_error(midi, pm_hosterror_text, 
-                                         PM_HOST_ERROR_MSG_LEN);
-           pm_hosterror = TRUE;
-        }
-        return pm_errmsg(err);
-    }
-
-    return !Pm_QueueEmpty(midi->queue);
-}
-
-
-/* this is called from Pm_Write and Pm_WriteSysEx to issue a
- * call to the system-dependent end_sysex function and handle 
- * the error return
- */
-static PmError pm_end_sysex(PmInternal *midi)
-{
-    PmError err = (*midi->dictionary->end_sysex)(midi, 0);
-    midi->sysex_in_progress = FALSE;
-    if (err == pmHostError) {
-        midi->dictionary->host_error(midi, pm_hosterror_text, 
-                                     PM_HOST_ERROR_MSG_LEN);
-        pm_hosterror = TRUE;
-    }
-    return err;
-}
-
-
-/* to facilitate correct error-handling, Pm_Write, Pm_WriteShort, and
-   Pm_WriteSysEx all operate a state machine that "outputs" calls to
-   write_short, begin_sysex, write_byte, end_sysex, and write_realtime */
-
-PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, long length)
-{
-    PmInternal *midi = (PmInternal *) stream;
-    PmError err = pmNoError;
-    int i;
-    int bits;
-    
-    pm_hosterror = FALSE;
-    /* arg checking */
-    if(midi == NULL)
-        err = pmBadPtr;
-    else if(!descriptors[midi->device_id].pub.opened)
-        err = pmBadPtr;
-    else if(!descriptors[midi->device_id].pub.output)
-        err = pmBadPtr;
-    else
-        err = pmNoError;
-    
-    if (err != pmNoError) goto pm_write_error;
-    
-    if (midi->latency == 0) {
-        midi->now = 0;
-    } else {
-        midi->now = (*(midi->time_proc))(midi->time_info);
-        if (midi->first_message || midi->sync_time + 100 /*ms*/ < midi->now) {
-            /* time to resync */
-            midi->now = (*midi->dictionary->synchronize)(midi);
-            midi->first_message = FALSE;
-        }
-    }
-    /* error recovery: when a sysex is detected, we call
-     *   dictionary->begin_sysex() followed by calls to
-     *   dictionary->write_byte() and dictionary->write_realtime()
-     *   until an end-of-sysex is detected, when we call
-     *   dictionary->end_sysex(). After an error occurs, 
-     *   Pm_Write() continues to call functions. For example,
-     *   it will continue to call write_byte() even after
-     *   an error sending a sysex message, and end_sysex() will be
-     *   called when an EOX or non-real-time status is found.
-     * When errors are detected, Pm_Write() returns immediately, 
-     *   so it is possible that this will drop data and leave
-     *   sysex messages in a partially transmitted state.
-     */
-    for (i = 0; i < length; i++) {
-        unsigned long msg = buffer[i].message;
-        bits = 0;
-        /* is this a sysex message? */
-        if (Pm_MessageStatus(msg) == MIDI_SYSEX) {
-            if (midi->sysex_in_progress) {
-                /* error: previous sysex was not terminated by EOX */
-                midi->sysex_in_progress = FALSE;
-                err = pmBadData;
-                goto pm_write_error;
-            }
-            midi->sysex_in_progress = TRUE;
-            if ((err = (*midi->dictionary->begin_sysex)(midi, 
-                               buffer[i].timestamp)) != pmNoError)
-                goto pm_write_error;
-            if ((err = (*midi->dictionary->write_byte)(midi, MIDI_SYSEX,
-                               buffer[i].timestamp)) != pmNoError) 
-                goto pm_write_error;
-            bits = 8;
-            /* fall through to continue sysex processing */
-        } else if ((msg & MIDI_STATUS_MASK) && 
-                   (Pm_MessageStatus(msg) != MIDI_EOX)) {
-            /* a non-sysex message */
-            if (midi->sysex_in_progress) {
-                /* this should be a realtime message */
-                if (is_real_time(msg)) {
-                    if ((err = (*midi->dictionary->write_realtime)(midi, 
-                                       &(buffer[i]))) != pmNoError)
-                        goto pm_write_error;
-                } else {
-                    midi->sysex_in_progress = FALSE;
-                    err = pmBadData;
-                    /* ignore any error from this, because we already have one */
-                    /* pass 0 as timestamp -- it's ignored */
-                    (*midi->dictionary->end_sysex)(midi, 0);
-                    goto pm_write_error;
-                }
-            } else { /* regular short midi message */
-                if ((err = (*midi->dictionary->write_short)(midi, 
-                                   &(buffer[i]))) != pmNoError)
-                    goto pm_write_error;
-                continue;
-            }
-        }
-        if (midi->sysex_in_progress) { /* send sysex bytes until EOX */
-            /* see if we can accelerate data transfer */
-            if (bits == 0 && midi->fill_base && /* 4 bytes to copy */
-                (*midi->fill_offset_ptr) + 4 <= midi->fill_length &&
-                (msg & 0x80808080) == 0) { /* all data */
-                    /* copy 4 bytes from msg to fill_base + fill_offset */
-                    unsigned char *ptr = midi->fill_base + 
-                                         *(midi->fill_offset_ptr);
-                    ptr[0] = msg; ptr[1] = msg >> 8; 
-                    ptr[2] = msg >> 18; ptr[3] = msg >> 24;
-                    (*midi->fill_offset_ptr) += 4;
-                     continue;
-            }
-            /* no acceleration, so do byte-by-byte copying */
-            while (bits < 32) {
-                unsigned char midi_byte = (unsigned char) (msg >> bits);
-                if ((err = (*midi->dictionary->write_byte)(midi, midi_byte, 
-                                   buffer[i].timestamp)) != pmNoError)
-                    goto pm_write_error;
-                if (midi_byte == MIDI_EOX) {
-                    err = pm_end_sysex(midi);
-                    if (err != pmNoError) goto error_exit;
-                    break; /* from while loop */
-                }
-                bits += 8;
-            }
-        } else {
-            /* not in sysex mode, but message did not start with status */
-            err = pmBadData;
-            goto pm_write_error;
-        }
-    }
-    /* after all messages are processed, send the data */
-    if (!midi->sysex_in_progress)
-        err = (*midi->dictionary->write_flush)(midi, 0);
-pm_write_error:
-    if (err == pmHostError) {
-        midi->dictionary->host_error(midi, pm_hosterror_text, 
-                                     PM_HOST_ERROR_MSG_LEN);
-        pm_hosterror = TRUE;
-    }
-error_exit:
-    return pm_errmsg(err);
-}
-
-
-PmError Pm_WriteShort(PortMidiStream *stream, long when, long msg)
-{
-    PmEvent event;
-    
-    event.timestamp = when;
-    event.message = msg;
-    return Pm_Write(stream, &event, 1);
-}
-
-
-PmError Pm_WriteSysEx(PortMidiStream *stream, PmTimestamp when, 
-                      unsigned char *msg)
-{
-    /* allocate buffer space for PM_DEFAULT_SYSEX_BUFFER_SIZE bytes */
-    /* each PmEvent holds sizeof(PmMessage) bytes of sysex data */
-    #define BUFLEN (PM_DEFAULT_SYSEX_BUFFER_SIZE / sizeof(PmMessage))
-    PmEvent buffer[BUFLEN];
-    int buffer_size = 1; /* first time, send 1. After that, it's BUFLEN */
-    PmInternal *midi = (PmInternal *) stream;
-    /* the next byte in the buffer is represented by an index, bufx, and
-       a shift in bits */
-    int shift = 0;
-    int bufx = 0;
-    buffer[0].message = 0;
-    buffer[0].timestamp = when;
-
-    while (1) {
-        /* insert next byte into buffer */
-        buffer[bufx].message |= ((*msg) << shift);
-        shift += 8;
-        if (*msg++ == MIDI_EOX) break;
-        if (shift == 32) {
-            shift = 0;
-            bufx++;
-            if (bufx == buffer_size) {
-                PmError err = Pm_Write(stream, buffer, buffer_size);
-                /* note: Pm_Write has already called errmsg() */
-                if (err) return err;
-                /* prepare to fill another buffer */
-                bufx = 0;
-                buffer_size = BUFLEN;
-                /* optimization: maybe we can just copy bytes */
-                if (midi->fill_base) {
-                    PmError err;
-                    while (*(midi->fill_offset_ptr) < midi->fill_length) {
-                        midi->fill_base[(*midi->fill_offset_ptr)++] = *msg;
-                        if (*msg++ == MIDI_EOX) {
-                            err = pm_end_sysex(midi);
-                            if (err != pmNoError) return pm_errmsg(err);
-                            goto end_of_sysex;
-                        }
-                    }
-                    /* I thought that I could do a pm_Write here and
-                     * change this if to a loop, avoiding calls in Pm_Write
-                     * to the slower write_byte, but since 
-                     * sysex_in_progress is true, this will not flush
-                     * the buffer, and we'll infinite loop: */
-                    /* err = Pm_Write(stream, buffer, 0);
-                       if (err) return err; */
-                    /* instead, the way this works is that Pm_Write calls
-                     * write_byte on 4 bytes. The first, since the buffer
-                     * is full, will flush the buffer and allocate a new
-                     * one. This primes the buffer so
-                     * that we can return to the loop above and fill it
-                     * efficiently without a lot of function calls.
-                     */
-                    buffer_size = 1; /* get another message started */
-                }
-            }
-            buffer[bufx].message = 0;
-            buffer[bufx].timestamp = when;
-        } 
-        /* keep inserting bytes until you find MIDI_EOX */
-    }
-end_of_sysex:
-    /* we're finished sending full buffers, but there may
-     * be a partial one left.
-     */
-    if (shift != 0) bufx++; /* add partial message to buffer len */
-    if (bufx) { /* bufx is number of PmEvents to send from buffer */
-        PmError err = Pm_Write(stream, buffer, bufx);
-        if (err) return err;
-    }
-    return pmNoError;
-}
-
-
-
-PmError Pm_OpenInput(PortMidiStream** stream,
-                     PmDeviceID inputDevice,
-                     void *inputDriverInfo,
-                     long bufferSize,
-                     PmTimeProcPtr time_proc,
-                     void *time_info)
-{
-    PmInternal *midi;
-    PmError err = pmNoError;
-    pm_hosterror = FALSE;
-    *stream = NULL;
-    
-    /* arg checking */
-    if (inputDevice < 0 || inputDevice >= pm_descriptor_index) 
-        err = pmInvalidDeviceId;
-    else if (!descriptors[inputDevice].pub.input) 
-        err =  pmInvalidDeviceId;
-    else if(descriptors[inputDevice].pub.opened)
-        err =  pmInvalidDeviceId;
-    
-    if (err != pmNoError) 
-        goto error_return;
-
-    /* create portMidi internal data */
-    midi = (PmInternal *) pm_alloc(sizeof(PmInternal)); 
-    *stream = midi;
-    if (!midi) {
-        err = pmInsufficientMemory;
-        goto error_return;
-    }
-    midi->device_id = inputDevice;
-    midi->write_flag = FALSE;
-    midi->time_proc = time_proc;
-    midi->time_info = time_info;
-    /* windows adds timestamps in the driver and these are more accurate than
-       using a time_proc, so do not automatically provide a time proc. Non-win
-       implementations may want to provide a default time_proc in their
-       system-specific midi_out_open() method.
-     */
-    if (bufferSize <= 0) bufferSize = 256; /* default buffer size */
-    midi->queue = Pm_QueueCreate(bufferSize, sizeof(PmEvent));
-    if (!midi->queue) {
-        /* free portMidi data */
-        *stream = NULL;
-        pm_free(midi); 
-        err = pmInsufficientMemory;
-        goto error_return;
-    }
-    midi->buffer_len = bufferSize; /* portMidi input storage */
-    midi->latency = 0; /* not used */
-    midi->sysex_in_progress = FALSE;
-    midi->sysex_message = 0; 
-    midi->sysex_message_count = 0; 
-    midi->filters = PM_FILT_ACTIVE;
-    midi->channel_mask = 0xFFFF;
-    midi->sync_time = 0;
-    midi->first_message = TRUE;
-    midi->dictionary = descriptors[inputDevice].dictionary;
-    midi->fill_base = NULL;
-    midi->fill_offset_ptr = NULL;
-    midi->fill_length = 0;
-    descriptors[inputDevice].internalDescriptor = midi;
-    /* open system dependent input device */
-    err = (*midi->dictionary->open)(midi, inputDriverInfo);
-    if (err) {
-        *stream = NULL;
-        descriptors[inputDevice].internalDescriptor = NULL;
-        /* free portMidi data */
-        Pm_QueueDestroy(midi->queue);
-        pm_free(midi);
-    } else {
-        /* portMidi input open successful */
-        descriptors[inputDevice].pub.opened = TRUE;
-    }
-error_return:
-    /* note: if there is a pmHostError, it is the responsibility
-     * of the system-dependent code (*midi->dictionary->open)()
-     * to set pm_hosterror and pm_hosterror_text
-     */
-    return pm_errmsg(err);
-}
-
-
-PmError Pm_OpenOutput(PortMidiStream** stream,
-                      PmDeviceID outputDevice,
-                      void *outputDriverInfo,
-                      long bufferSize,
-                      PmTimeProcPtr time_proc,
-                      void *time_info,
-                      long latency ) 
-{
-    PmInternal *midi;
-    PmError err = pmNoError;
-    pm_hosterror = FALSE;
-    *stream =  NULL;
-    
-    /* arg checking */
-    if (outputDevice < 0 || outputDevice >= pm_descriptor_index)
-        err = pmInvalidDeviceId;
-    else if (!descriptors[outputDevice].pub.output) 
-        err = pmInvalidDeviceId;
-    else if (descriptors[outputDevice].pub.opened)
-        err = pmInvalidDeviceId;
-    if (err != pmNoError) 
-        goto error_return;
-
-    /* create portMidi internal data */
-    midi = (PmInternal *) pm_alloc(sizeof(PmInternal)); 
-    *stream = midi;                 
-    if (!midi) {
-        err = pmInsufficientMemory;
-        goto error_return;
-    }
-    midi->device_id = outputDevice;
-    midi->write_flag = TRUE;
-    midi->time_proc = time_proc;
-    /* if latency > 0, we need a time reference. If none is provided,
-       use PortTime library */
-    if (time_proc == NULL && latency != 0) {
-        if (!Pt_Started()) 
-            Pt_Start(1, 0, 0);
-        /* time_get does not take a parameter, so coerce */
-        midi->time_proc = (PmTimeProcPtr) Pt_Time;
-    }
-    midi->time_info = time_info;
-    midi->buffer_len = bufferSize;
-    midi->queue = NULL; /* unused by output */
-    /* if latency zero, output immediate (timestamps ignored) */
-    /* if latency < 0, use 0 but don't return an error */
-    if (latency < 0) latency = 0;
-    midi->latency = latency;
-    midi->sysex_in_progress = FALSE;
-    midi->sysex_message = 0; /* unused by output */
-    midi->sysex_message_count = 0; /* unused by output */
-    midi->filters = 0; /* not used for output */
-    midi->channel_mask = 0xFFFF;
-    midi->sync_time = 0;
-    midi->first_message = TRUE;
-    midi->dictionary = descriptors[outputDevice].dictionary;
-    midi->fill_base = NULL;
-    midi->fill_offset_ptr = NULL;
-    midi->fill_length = 0;
-    descriptors[outputDevice].internalDescriptor = midi;
-    /* open system dependent output device */
-    err = (*midi->dictionary->open)(midi, outputDriverInfo);
-    if (err) {
-        *stream = NULL;
-        descriptors[outputDevice].internalDescriptor = NULL;
-        /* free portMidi data */
-        pm_free(midi); 
-    } else {
-        /* portMidi input open successful */
-        descriptors[outputDevice].pub.opened = TRUE;
-    }
-error_return:
-    /* note: system-dependent code must set pm_hosterror and
-     * pm_hosterror_text if a pmHostError occurs
-     */
-    return pm_errmsg(err);
-}
-
-
-PmError Pm_SetChannelMask(PortMidiStream *stream, int mask)
-{
-    PmInternal *midi = (PmInternal *) stream;
-    PmError err = pmNoError;
-
-    if (midi == NULL)
-        err = pmBadPtr;
-    else
-        midi->channel_mask = mask;
-
-    return pm_errmsg(err);
-}
-
-
-PmError Pm_SetFilter(PortMidiStream *stream, long filters) {
-    PmInternal *midi = (PmInternal *) stream;
-    PmError err = pmNoError;
-
-    /* arg checking */
-    if (midi == NULL)
-        err = pmBadPtr;
-    else if (!descriptors[midi->device_id].pub.opened)
-        err = pmBadPtr;
-    else
-        midi->filters = filters;
-    return pm_errmsg(err);
-}
-
-
-PmError Pm_Close( PortMidiStream *stream ) {
-    PmInternal *midi = (PmInternal *) stream;
-    PmError err = pmNoError;
-
-    pm_hosterror = FALSE;
-    /* arg checking */
-    if (midi == NULL) /* midi must point to something */
-        err = pmBadPtr;
-    /* if it is an open device, the device_id will be valid */
-    else if (midi->device_id < 0 || midi->device_id >= pm_descriptor_index)
-        err = pmBadPtr;
-    /* and the device should be in the opened state */
-    else if (!descriptors[midi->device_id].pub.opened)
-        err = pmBadPtr;
-    
-    if (err != pmNoError) 
-        goto error_return;
-
-    /* close the device */
-    err = (*midi->dictionary->close)(midi);
-    /* even if an error occurred, continue with cleanup */
-    descriptors[midi->device_id].internalDescriptor = NULL;
-    descriptors[midi->device_id].pub.opened = FALSE;
-    if (midi->queue) Pm_QueueDestroy(midi->queue);
-    pm_free(midi); 
-error_return:
-    /* system dependent code must set pm_hosterror and
-     * pm_hosterror_text if a pmHostError occurs.
-     */
-    return pm_errmsg(err);
-}
-
-
-PmError Pm_Abort( PortMidiStream* stream ) {
-    PmInternal *midi = (PmInternal *) stream;
-    PmError err;
-    /* arg checking */
-    if (midi == NULL)
-        err = pmBadPtr;
-    else if (!descriptors[midi->device_id].pub.output)
-        err = pmBadPtr;
-    else if (!descriptors[midi->device_id].pub.opened)
-        err = pmBadPtr;
-    else
-        err = (*midi->dictionary->abort)(midi);
-
-    if (err == pmHostError) {
-        midi->dictionary->host_error(midi, pm_hosterror_text, 
-                                     PM_HOST_ERROR_MSG_LEN);
-        pm_hosterror = TRUE;
-    }
-    return pm_errmsg(err);
-}
-
-
-
-/* pm_channel_filtered returns non-zero if the channel mask is blocking the current channel */
-#define pm_channel_filtered(status, mask) \
-    ((((status) & 0xF0) != 0xF0) && (!(Pm_Channel((status) & 0x0F) & (mask))))
-
-
-/* The following two functions will checks to see if a MIDI message matches
-   the filtering criteria.  Since the sysex routines only want to filter realtime messages,
-   we need to have separate routines.
- */
-
-
-/* pm_realtime_filtered returns non-zero if the filter will kill the current message.
-   Note that only realtime messages are checked here.
- */
-#define pm_realtime_filtered(status, filters) \
-    ((((status) & 0xF0) == 0xF0) && ((1 << ((status) & 0xF)) & (filters)))
-
-/*
-    return ((status == MIDI_ACTIVE) && (filters & PM_FILT_ACTIVE))
-            ||  ((status == MIDI_CLOCK) && (filters & PM_FILT_CLOCK))
-            ||  ((status == MIDI_START) && (filters & PM_FILT_PLAY))
-            ||  ((status == MIDI_STOP) && (filters & PM_FILT_PLAY))
-            ||  ((status == MIDI_CONTINUE) && (filters & PM_FILT_PLAY))
-            ||  ((status == MIDI_F9) && (filters & PM_FILT_F9))
-            ||  ((status == MIDI_FD) && (filters & PM_FILT_FD))
-            ||  ((status == MIDI_RESET) && (filters & PM_FILT_RESET))
-            ||  ((status == MIDI_MTC) && (filters & PM_FILT_MTC))
-            ||  ((status == MIDI_SONGPOS) && (filters & PM_FILT_SONG_POSITION))
-            ||  ((status == MIDI_SONGSEL) && (filters & PM_FILT_SONG_SELECT))
-            ||  ((status == MIDI_TUNE) && (filters & PM_FILT_TUNE));
-}*/
-
-
-/* pm_status_filtered returns non-zero if a filter will kill the current message, based on status.
-   Note that sysex and real time are not checked.  It is up to the subsystem (winmm, core midi, alsa)
-   to filter sysex, as it is handled more easily and efficiently at that level.
-   Realtime message are filtered in pm_realtime_filtered.
- */
-#define pm_status_filtered(status, filters) ((1 << (16 + ((status) >> 4))) & (filters))
-
-
-/*
-    return  ((status == MIDI_NOTE_ON) && (filters & PM_FILT_NOTE))
-            ||  ((status == MIDI_NOTE_OFF) && (filters & PM_FILT_NOTE))
-            ||  ((status == MIDI_CHANNEL_AT) && (filters & PM_FILT_CHANNEL_AFTERTOUCH))
-            ||  ((status == MIDI_POLY_AT) && (filters & PM_FILT_POLY_AFTERTOUCH))
-            ||  ((status == MIDI_PROGRAM) && (filters & PM_FILT_PROGRAM))
-            ||  ((status == MIDI_CONTROL) && (filters & PM_FILT_CONTROL))
-            ||  ((status == MIDI_PITCHBEND) && (filters & PM_FILT_PITCHBEND));
-
-}
-*/
-
-static void pm_flush_sysex(PmInternal *midi, PmTimestamp timestamp)
-{
-    PmEvent event;
-    
-    /* there may be nothing in the buffer */
-    if (midi->sysex_message_count == 0) return; /* nothing to flush */
-    
-    event.message = midi->sysex_message;
-    event.timestamp = timestamp;
-    /* copied from pm_read_short, avoids filtering */
-    if (Pm_Enqueue(midi->queue, &event) == pmBufferOverflow) {
-        midi->sysex_in_progress = FALSE;
-    }
-    midi->sysex_message_count = 0;
-    midi->sysex_message = 0;
-}
-
-
-/* pm_read_short and pm_read_bytes
-   are the interface between system-dependent MIDI input handlers
-   and the system-independent PortMIDI code.
-   The input handler MUST obey these rules:
-   1) all short input messages must be sent to pm_read_short, which
-      enqueues them to a FIFO for the application.
-   2) each buffer of sysex bytes should be reported by calling pm_read_bytes
-      (which sets midi->sysex_in_progress). After the eox byte, 
-      pm_read_bytes will clear sysex_in_progress
- */
-
-/* pm_read_short is the place where all input messages arrive from 
-   system-dependent code such as pmwinmm.c. Here, the messages
-   are entered into the PortMidi input buffer. 
- */
-void pm_read_short(PmInternal *midi, PmEvent *event)
-{ 
-    int status;
-    /* arg checking */
-    assert(midi != NULL);
-    /* midi filtering is applied here */
-    status = Pm_MessageStatus(event->message);
-    if (!pm_status_filtered(status, midi->filters)
-        && (!is_real_time(status) || 
-            !pm_realtime_filtered(status, midi->filters))
-        && !pm_channel_filtered(status, midi->channel_mask)) {
-        /* if sysex is in progress and we get a status byte, it had
-           better be a realtime message or the starting SYSEX byte;
-           otherwise, we exit the sysex_in_progress state
-         */
-        if (midi->sysex_in_progress && (status & MIDI_STATUS_MASK)) {
-            /* two choices: real-time or not. If it's real-time, then
-             * this should be delivered as a sysex byte because it is
-             * embedded in a sysex message
-             */
-            if (is_real_time(status)) {
-                midi->sysex_message |= 
-                        (status << (8 * midi->sysex_message_count++));
-                if (midi->sysex_message_count == 4) {
-                    pm_flush_sysex(midi, event->timestamp);
-                }
-            } else { /* otherwise, it's not real-time. This interrupts
-                      * a sysex message in progress */
-                midi->sysex_in_progress = FALSE;
-            }
-        } else if (Pm_Enqueue(midi->queue, event) == pmBufferOverflow) {
-            midi->sysex_in_progress = FALSE;
-        }
-    }
-}
-
-/* pm_read_bytes -- read one (partial) sysex msg from MIDI data */
-/*
- * returns how many bytes processed
- */
-unsigned int pm_read_bytes(PmInternal *midi, unsigned char *data, 
-                    int len, PmTimestamp timestamp)
-{
-    int i = 0; /* index into data, must not be unsigned (!) */
-    PmEvent event;
-    event.timestamp = timestamp;
-    assert(midi);
-    /* note that since buffers may not have multiples of 4 bytes,
-     * pm_read_bytes may be called in the middle of an outgoing
-     * 4-byte PortMidi message. sysex_in_progress indicates that
-     * a sysex has been sent but no eox.
-     */
-    if (len == 0) return 0; /* sanity check */
-    if (!midi->sysex_in_progress) {
-        while (i < len) { /* process all data */
-            unsigned char byte = data[i++];
-            if (byte == MIDI_SYSEX &&
-                !pm_realtime_filtered(byte, midi->filters)) {
-                midi->sysex_in_progress = TRUE;
-                i--; /* back up so code below will get SYSEX byte */
-                break; /* continue looping below to process msg */
-            } else if (byte == MIDI_EOX) {
-                midi->sysex_in_progress = FALSE;
-                return i; /* done with one message */
-            } else if (byte & MIDI_STATUS_MASK) {
-                /* We're getting MIDI but no sysex in progress.
-                 * Either the SYSEX status byte was dropped or
-                 * the message was filtered. Drop the data, but
-                 * send any embedded realtime bytes.
-                 */
-                /* assume that this is a real-time message:
-                 * it is an error to pass non-real-time messages
-                 * to pm_read_bytes
-                 */
-                event.message = byte;
-                pm_read_short(midi, &event);
-            }
-        } /* all bytes in the buffer are processed */
-    }
-    /* Now, i<len implies sysex_in_progress. If sysex_in_progress
-     * becomes false in the loop, there must have been an overflow
-     * and we can just drop all remaining bytes 
-     */
-    while (i < len && midi->sysex_in_progress) {
-        if (midi->sysex_message_count == 0 && i <= len - 4 &&
-            ((event.message = (((long) data[i]) | 
-                             (((long) data[i+1]) << 8) |
-                             (((long) data[i+2]) << 16) |
-                             (((long) data[i+3]) << 24))) &
-             0x80808080) == 0) { /* all data, no status */ 
-            if (Pm_Enqueue(midi->queue, &event) == pmBufferOverflow) {
-                midi->sysex_in_progress = FALSE;
-            }
-            i += 4;
-        } else {
-            while (i < len) {
-                /* send one byte at a time */
-                unsigned char byte = data[i++];
-                if (is_real_time(byte) && 
-                    pm_realtime_filtered(byte, midi->filters)) {
-                    continue; /* real-time data is filtered, so omit */
-                }
-                midi->sysex_message |= 
-                    (byte << (8 * midi->sysex_message_count++));
-                if (byte == MIDI_EOX) {
-                    midi->sysex_in_progress = FALSE;
-                    pm_flush_sysex(midi, event.timestamp);
-                    return i;
-                } else if (midi->sysex_message_count == 4) {
-                    pm_flush_sysex(midi, event.timestamp);
-                    /* after handling at least one non-data byte
-                     * and reaching a 4-byte message boundary,
-                     * resume trying to send 4 at a time in outer loop
-                     */
-                    break;
-                }
-            }
-        }
-    }
-    return i;
-}
-
-
+#include "stdlib.h"
+#include "string.h"
+#include "portmidi.h"
+#include "porttime.h"
+#ifdef NEWBUFFER
+#include "pmutil.h"
+#endif
+#include "pminternal.h"
+#include <assert.h>
+
+#define MIDI_CLOCK      0xf8
+#define MIDI_ACTIVE     0xfe
+#define MIDI_STATUS_MASK 0x80
+#define MIDI_SYSEX      0xf0
+#define MIDI_EOX        0xf7
+#define MIDI_START      0xFA
+#define MIDI_STOP       0xFC
+#define MIDI_CONTINUE   0xFB
+#define MIDI_F9         0xF9
+#define MIDI_FD         0xFD
+#define MIDI_RESET      0xFF
+#define MIDI_NOTE_ON    0x90
+#define MIDI_NOTE_OFF   0x80
+#define MIDI_CHANNEL_AT 0xD0
+#define MIDI_POLY_AT    0xA0
+#define MIDI_PROGRAM    0xC0
+#define MIDI_CONTROL    0xB0
+#define MIDI_PITCHBEND  0xE0
+#define MIDI_MTC        0xF1
+#define MIDI_SONGPOS    0xF2
+#define MIDI_SONGSEL    0xF3
+#define MIDI_TUNE       0xF6
+
+#define is_empty(midi) ((midi)->tail == (midi)->head)
+
+static int pm_initialized = FALSE;
+int pm_hosterror;
+char pm_hosterror_text[PM_HOST_ERROR_MSG_LEN];
+
+#ifdef PM_CHECK_ERRORS
+
+#include <stdio.h>
+
+#define STRING_MAX 80
+
+static void prompt_and_exit(void)
+{
+    char line[STRING_MAX];
+    printf("type ENTER...");
+    fgets(line, STRING_MAX, stdin);
+    /* this will clean up open ports: */
+    exit(-1);
+}
+
+
+static PmError pm_errmsg(PmError err)
+{
+    if (err == pmHostError) {
+        /* it seems pointless to allocate memory and copy the string,
+         * so I will do the work of Pm_GetHostErrorText directly
+         */
+        printf("PortMidi found host error...\n  %s\n", pm_hosterror_text);
+        pm_hosterror = FALSE;
+        pm_hosterror_text[0] = 0; /* clear the message */
+        prompt_and_exit();
+    } else if (err < 0) {
+        printf("PortMidi call failed...\n  %s\n", Pm_GetErrorText(err));
+        prompt_and_exit();
+    }
+    return err;
+}
+#else
+#define pm_errmsg(err) err
+#endif
+
+/*
+====================================================================
+system implementation of portmidi interface
+====================================================================
+*/
+
+int pm_descriptor_max = 0;
+int pm_descriptor_index = 0;
+descriptor_type descriptors = NULL;
+
+/* pm_add_device -- describe interface/device pair to library 
+ *
+ * This is called at intialization time, once for each 
+ * interface (e.g. DirectSound) and device (e.g. SoundBlaster 1)
+ * The strings are retained but NOT COPIED, so do not destroy them!
+ *
+ * returns pmInvalidDeviceId if device memory is exceeded
+ * otherwise returns pmNoError
+ */
+PmError pm_add_device(char *interf, char *name, int input, 
+                      void *descriptor, pm_fns_type dictionary) {
+    if (pm_descriptor_index >= pm_descriptor_max) {
+        // expand descriptors
+        descriptor_type new_descriptors = 
+                pm_alloc(sizeof(descriptor_node) * (pm_descriptor_max + 32));
+        if (!new_descriptors) return pmInsufficientMemory;
+        if (descriptors) {
+            memcpy(new_descriptors, descriptors, 
+                   sizeof(descriptor_node) * pm_descriptor_max);
+            free(descriptors);
+        }
+        pm_descriptor_max += 32;
+        descriptors = new_descriptors;
+    }
+    descriptors[pm_descriptor_index].pub.interf = interf;
+    descriptors[pm_descriptor_index].pub.name = name;
+    descriptors[pm_descriptor_index].pub.input = input;
+    descriptors[pm_descriptor_index].pub.output = !input;
+
+    /* default state: nothing to close (for automatic device closing) */
+    descriptors[pm_descriptor_index].pub.opened = FALSE;
+
+    /* ID number passed to win32 multimedia API open */
+    descriptors[pm_descriptor_index].descriptor = descriptor;
+    
+    /* points to PmInternal, allows automatic device closing */
+    descriptors[pm_descriptor_index].internalDescriptor = NULL;
+
+    descriptors[pm_descriptor_index].dictionary = dictionary;
+    
+    pm_descriptor_index++;
+    
+    return pmNoError;
+}
+
+
+/*
+====================================================================
+portmidi implementation
+====================================================================
+*/
+
+int Pm_CountDevices( void ) {
+    Pm_Initialize();
+    /* no error checking -- Pm_Initialize() does not fail */
+    return pm_descriptor_index;
+}
+
+
+const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id ) {
+    Pm_Initialize(); /* no error check needed */
+    if (id >= 0 && id < pm_descriptor_index) {
+        return &descriptors[id].pub;
+    }
+    return NULL;
+}
+
+/* pm_success_fn -- "noop" function pointer */
+PmError pm_success_fn(PmInternal *midi) {
+    return pmNoError;
+}
+
+/* none_write -- returns an error if called */
+PmError none_write_short(PmInternal *midi, PmEvent *buffer) {
+    return pmBadPtr;
+}
+
+/* pm_fail_timestamp_fn -- placeholder for begin_sysex and flush */
+PmError pm_fail_timestamp_fn(PmInternal *midi, PmTimestamp timestamp) {
+    return pmBadPtr;
+}
+
+PmError none_write_byte(PmInternal *midi, unsigned char byte, 
+                        PmTimestamp timestamp) {
+    return pmBadPtr;
+}
+
+/* pm_fail_fn -- generic function, returns error if called */
+PmError pm_fail_fn(PmInternal *midi) {
+    return pmBadPtr;
+}
+
+static PmError none_open(PmInternal *midi, void *driverInfo) {
+    return pmBadPtr;
+}
+static void none_get_host_error(PmInternal * midi, char * msg, unsigned int len) {
+    strcpy(msg, "");
+}
+static unsigned int none_has_host_error(PmInternal * midi) {
+    return FALSE;
+}
+PmTimestamp none_synchronize(PmInternal *midi) {
+    return 0;
+}
+
+#define none_abort pm_fail_fn
+#define none_close pm_fail_fn
+
+pm_fns_node pm_none_dictionary = {
+    none_write_short,
+    none_sysex,
+    none_sysex,
+    none_write_byte,
+    none_write_short,
+    none_write_flush,
+    none_synchronize,
+    none_open,
+    none_abort, 
+    none_close,
+    none_poll,
+    none_has_host_error,
+    none_get_host_error 
+};
+
+
+const char *Pm_GetErrorText( PmError errnum ) {
+    const char *msg;
+
+    switch(errnum)
+    {
+    case pmNoError:                  
+        msg = ""; 
+        break;
+    case pmHostError:                
+        msg = "PortMidi: `Host error'"; 
+        break;
+    case pmInvalidDeviceId:          
+        msg = "PortMidi: `Invalid device ID'"; 
+        break;
+    case pmInsufficientMemory:       
+        msg = "PortMidi: `Insufficient memory'"; 
+        break;
+    case pmBufferTooSmall:           
+        msg = "PortMidi: `Buffer too small'"; 
+        break;
+    case pmBadPtr:                   
+        msg = "PortMidi: `Bad pointer'"; 
+        break;
+    case pmInternalError:            
+        msg = "PortMidi: `Internal PortMidi Error'"; 
+        break;
+    case pmBufferOverflow:
+        msg = "PortMidi: `Buffer overflow'";
+        break;
+    case pmBadData:
+        msg = "PortMidi: `Invalid MIDI message Data'";
+        break;
+    case pmBufferMaxSize:
+        msg = "PortMidi: `Buffer cannot be made larger'";
+        break;
+    default:                         
+        msg = "PortMidi: `Illegal error number'"; 
+        break;
+    }
+    return msg;
+}
+
+
+/* This can be called whenever you get a pmHostError return value.
+ * The error will always be in the global pm_hosterror_text.
+ */
+void Pm_GetHostErrorText(char * msg, unsigned int len) {
+    assert(msg);
+    assert(len > 0);
+    if (pm_hosterror) {
+        strncpy(msg, (char *) pm_hosterror_text, len);
+        pm_hosterror = FALSE;
+        pm_hosterror_text[0] = 0; /* clear the message; not necessary, but it
+                                     might help with debugging */
+        msg[len - 1] = 0; /* make sure string is terminated */
+    } else {
+        msg[0] = 0; /* no string to return */
+    }
+}
+
+
+int Pm_HasHostError(PortMidiStream * stream) {
+    if (pm_hosterror) return TRUE;
+    if (stream) {
+        PmInternal * midi = (PmInternal *) stream;
+        pm_hosterror = (*midi->dictionary->has_host_error)(midi);
+        if (pm_hosterror) {
+            midi->dictionary->host_error(midi, pm_hosterror_text, 
+                                         PM_HOST_ERROR_MSG_LEN);
+            /* now error message is global */
+            return TRUE;
+        }
+    }
+    return FALSE;
+}
+
+
+PmError Pm_Initialize( void ) {
+    if (!pm_initialized) {
+        pm_hosterror = FALSE;
+        pm_hosterror_text[0] = 0; /* the null string */
+        pm_init();
+        pm_initialized = TRUE;
+    }
+    return pmNoError;
+}
+
+
+PmError Pm_Terminate( void ) {
+    if (pm_initialized) {
+        pm_term();
+        // if there are no devices, descriptors might still be NULL
+        if (descriptors != NULL) {
+            free(descriptors);
+            descriptors = NULL;
+        }
+        pm_descriptor_index = 0;
+        pm_descriptor_max = 0;
+        pm_initialized = FALSE;
+    }
+    return pmNoError;
+}
+
+
+/* Pm_Read -- read up to length longs from source into buffer */
+/*
+ * returns number of longs actually read, or error code
+ */
+PmError Pm_Read(PortMidiStream *stream, PmEvent *buffer, long length) {
+    PmInternal *midi = (PmInternal *) stream;
+    int n = 0;
+#ifndef NEWBUFFER
+    long head;
+#endif
+    PmError err = pmNoError;
+    pm_hosterror = FALSE;
+    /* arg checking */
+    if(midi == NULL)
+        err = pmBadPtr;
+    else if(!descriptors[midi->device_id].pub.opened)
+        err = pmBadPtr;
+    else if(!descriptors[midi->device_id].pub.input)
+        err = pmBadPtr;    
+    /* First poll for data in the buffer...
+     * This either simply checks for data, or attempts first to fill the buffer
+     * with data from the MIDI hardware; this depends on the implementation.
+     * We could call Pm_Poll here, but that would redo a lot of redundant
+     * parameter checking, so I copied some code from Pm_Poll to here: */
+    else err = (*(midi->dictionary->poll))(midi);
+
+    if (err != pmNoError) {
+        if (err == pmHostError) {
+            midi->dictionary->host_error(midi, pm_hosterror_text, 
+                                         PM_HOST_ERROR_MSG_LEN);
+          pm_hosterror = TRUE;
+        }
+        return pm_errmsg(err);
+    }
+
+#ifdef NEWBUFFER
+    while (n < length) {
+        PmError err = Pm_Dequeue(midi->queue, buffer++);
+        if (err == pmBufferOverflow) {
+            /* ignore the data we have retreived so far */
+            return pm_errmsg(pmBufferOverflow);
+        } else if (err == 0) { /* empty queue */
+            break;
+        }
+        n++;
+    }
+#else
+    head = midi->head;
+    while (head != midi->tail && n < length) {
+        PmEvent event = midi->buffer[head++];
+        *buffer++ = event;
+        if (head == midi->buffer_len) head = 0;
+        n++;
+    }
+    midi->head = head;
+    if (midi->overflow) {
+        midi->head = midi->tail;
+        midi->overflow = FALSE;
+        return pm_errmsg(pmBufferOverflow);
+    }
+#endif
+    return n;
+}
+
+PmError Pm_Poll( PortMidiStream *stream )
+{
+    PmInternal *midi = (PmInternal *) stream;
+    PmError err;
+#ifdef NEWBUFFER
+    PmEvent *event;
+#endif
+
+    pm_hosterror = FALSE;
+    /* arg checking */
+    if(midi == NULL)
+        err = pmBadPtr;
+    else if(!descriptors[midi->device_id].pub.opened)
+        err = pmBadPtr;
+    else if(!descriptors[midi->device_id].pub.input)
+        err = pmBadPtr;
+    else
+        err = (*(midi->dictionary->poll))(midi);
+
+    if (err != pmNoError) {
+        if (err == pmHostError) {
+            midi->dictionary->host_error(midi, pm_hosterror_text, 
+                                         PM_HOST_ERROR_MSG_LEN);
+           pm_hosterror = TRUE;
+        }
+        return pm_errmsg(err);
+    }
+
+#ifdef NEWBUFFER
+    event = (PmEvent *) Pm_QueuePeek(midi->queue);
+    return event != NULL;
+#else
+    return midi->head != midi->tail;
+#endif
+}
+
+
+/* this is called from Pm_Write and Pm_WriteSysEx to issue a
+ * call to the system-dependent end_sysex function and handle 
+ * the error return
+ */
+static PmError pm_end_sysex(PmInternal *midi)
+{
+    PmError err = (*midi->dictionary->end_sysex)(midi, 0);
+    midi->sysex_in_progress = FALSE;
+    if (err == pmHostError) {
+        midi->dictionary->host_error(midi, pm_hosterror_text, 
+                                     PM_HOST_ERROR_MSG_LEN);
+        pm_hosterror = TRUE;
+    }
+    return err;
+}
+
+
+/* to facilitate correct error-handling, Pm_Write, Pm_WriteShort, and
+   Pm_WriteSysEx all operate a state machine that "outputs" calls to
+   write_short, begin_sysex, write_byte, end_sysex, and write_realtime */
+
+PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, long length)
+{
+    PmInternal *midi = (PmInternal *) stream;
+    PmError err;
+    int i;
+    int bits;
+    
+    pm_hosterror = FALSE;
+    /* arg checking */
+    if(midi == NULL)
+        err = pmBadPtr;
+    else if(!descriptors[midi->device_id].pub.opened)
+        err = pmBadPtr;
+    else if(!descriptors[midi->device_id].pub.output)
+        err = pmBadPtr;
+    else
+        err = pmNoError;
+    
+    if (err != pmNoError) goto pm_write_error;
+    
+    if (midi->latency == 0) {
+        midi->now = 0;
+    } else {
+        midi->now = (*(midi->time_proc))(midi->time_info);
+        if (midi->first_message || midi->sync_time + 100 /*ms*/ < midi->now) {
+            /* time to resync */
+            midi->now = (*midi->dictionary->synchronize)(midi);
+            midi->first_message = FALSE;
+        }
+    }
+    /* error recovery: when a sysex is detected, we call
+     *   dictionary->begin_sysex() followed by calls to
+     *   dictionary->write_byte() and dictionary->write_realtime()
+     *   until an end-of-sysex is detected, when we call
+     *   dictionary->end_sysex(). After an error occurs, 
+     *   Pm_Write() continues to call functions. For example,
+     *   it will continue to call write_byte() even after
+     *   an error sending a sysex message, and end_sysex() will be
+     *   called when an EOX or non-real-time status is found.
+     * When errors are detected, Pm_Write() returns immediately, 
+     *   so it is possible that this will drop data and leave
+     *   sysex messages in a partially transmitted state.
+     */
+    for (i = 0; i < length; i++) {
+        unsigned long msg = buffer[i].message;
+        bits = 0;
+        /* is this a sysex message? */
+        if (Pm_MessageStatus(msg) == MIDI_SYSEX) {
+            if (midi->sysex_in_progress) {
+                /* error: previous sysex was not terminated by EOX */
+                midi->sysex_in_progress = FALSE;
+                err = pmBadData;
+                goto pm_write_error;
+            }
+            midi->sysex_in_progress = TRUE;
+            if ((err = (*midi->dictionary->begin_sysex)(midi, 
+                               buffer[i].timestamp)) != pmNoError)
+                goto pm_write_error;
+            if ((err = (*midi->dictionary->write_byte)(midi, MIDI_SYSEX,
+                               buffer[i].timestamp)) != pmNoError) 
+                goto pm_write_error;
+            bits = 8;
+            /* fall through to continue sysex processing */
+        } else if ((msg & MIDI_STATUS_MASK) && 
+                   (Pm_MessageStatus(msg) != MIDI_EOX)) {
+            /* a non-sysex message */
+            if (midi->sysex_in_progress) {
+                /* this should be a realtime message */
+                if (is_real_time(msg)) {
+                    if ((err = (*midi->dictionary->write_realtime)(midi, 
+                                       &(buffer[i]))) != pmNoError)
+                        goto pm_write_error;
+                } else {
+                    midi->sysex_in_progress = FALSE;
+                    err = pmBadData;
+                    /* ignore any error from this, because we already have one */
+                    /* pass 0 as timestamp -- it's ignored */
+                    (*midi->dictionary->end_sysex)(midi, 0);
+                    goto pm_write_error;
+                }
+            } else { /* regular short midi message */
+                if ((err = (*midi->dictionary->write_short)(midi, 
+                                   &(buffer[i]))) != pmNoError)
+                    goto pm_write_error;
+                continue;
+            }
+        }
+        if (midi->sysex_in_progress) { /* send sysex bytes until EOX */
+            /* see if we can accelerate data transfer */
+            if (bits == 0 && midi->fill_base && /* 4 bytes to copy */
+                (*midi->fill_offset_ptr) + 4 <= midi->fill_length &&
+                (msg & 0x80808080) == 0) { /* all data */
+                    /* copy 4 bytes from msg to fill_base + fill_offset */
+                    unsigned char *ptr = midi->fill_base + 
+                                         *(midi->fill_offset_ptr);
+                    ptr[0] = msg; ptr[1] = msg >> 8; 
+                    ptr[2] = msg >> 18; ptr[3] = msg >> 24;
+                    (*midi->fill_offset_ptr) += 4;
+                     continue;
+            }
+            /* no acceleration, so do byte-by-byte copying */
+            while (bits < 32) {
+                unsigned char midi_byte = (unsigned char) (msg >> bits);
+                if ((err = (*midi->dictionary->write_byte)(midi, midi_byte, 
+                                   buffer[i].timestamp)) != pmNoError)
+                    goto pm_write_error;
+                if (midi_byte == MIDI_EOX) {
+                    err = pm_end_sysex(midi);
+                    if (err != pmNoError) goto error_exit;
+                    break; /* from while loop */
+                }
+                bits += 8;
+            }
+        } else {
+            /* not in sysex mode, but message did not start with status */
+            err = pmBadData;
+            goto pm_write_error;
+        }
+    }
+    /* after all messages are processed, send the data */
+    if (!midi->sysex_in_progress)
+        err = (*midi->dictionary->write_flush)(midi, 0);
+pm_write_error:
+    if (err == pmHostError) {
+        midi->dictionary->host_error(midi, pm_hosterror_text, 
+                                     PM_HOST_ERROR_MSG_LEN);
+        pm_hosterror = TRUE;
+    }
+error_exit:
+    return pm_errmsg(err);
+}
+
+
+PmError Pm_WriteShort( PortMidiStream *stream, long when, long msg)
+{
+    PmEvent event;
+    
+    event.timestamp = when;
+    event.message = msg;
+    return Pm_Write(stream, &event, 1);
+}
+
+
+PmError Pm_WriteSysEx(PortMidiStream *stream, PmTimestamp when, 
+                      unsigned char *msg)
+{
+    /* allocate buffer space for PM_DEFAULT_SYSEX_BUFFER_SIZE bytes */
+    /* each PmEvent holds sizeof(PmMessage) bytes of sysex data */
+#define BUFLEN (PM_DEFAULT_SYSEX_BUFFER_SIZE / sizeof(PmMessage))
+    PmEvent buffer[BUFLEN];
+    int buffer_size = 1; /* first time, send 1. After that, it's BUFLEN */
+    PmInternal *midi = (PmInternal *) stream;
+    /* the next byte in the buffer is represented by an index, bufx, and
+       a shift in bits */
+    int shift = 0;
+    int bufx = 0;
+    buffer[0].message = 0;
+    buffer[0].timestamp = when;
+
+    while (1) {
+        /* insert next byte into buffer */
+        buffer[bufx].message |= ((*msg) << shift);
+        shift += 8;
+        if (*msg++ == MIDI_EOX) break;
+        if (shift == 32) {
+            shift = 0;
+            bufx++;
+            if (bufx == buffer_size) {
+                PmError err = Pm_Write(stream, buffer, buffer_size);
+                /* note: Pm_Write has already called errmsg() */
+                if (err) return err;
+                /* prepare to fill another buffer */
+                bufx = 0;
+                buffer_size = BUFLEN;
+                /* optimization: maybe we can just copy bytes */
+                if (midi->fill_base) {
+                    PmError err;
+                    while (*(midi->fill_offset_ptr) < midi->fill_length) {
+                        midi->fill_base[(*midi->fill_offset_ptr)++] = *msg;
+                        if (*msg++ == MIDI_EOX) {
+                            err = pm_end_sysex(midi);
+                            if (err != pmNoError) return pm_errmsg(err);
+                            goto end_of_sysex;
+                        }
+                    }
+                    /* I thought that I could do a pm_Write here and
+                     * change this if to a loop, avoiding calls in Pm_Write
+                     * to the slower write_byte, but since 
+                     * sysex_in_progress is true, this will not flush
+                     * the buffer, and we'll infinite loop: */
+                    /* err = Pm_Write(stream, buffer, 0);
+                       if (err) return err; */
+                    /* instead, the way this works is that Pm_Write calls
+                     * write_byte on 4 bytes. The first, since the buffer
+                     * is full, will flush the buffer and allocate a new
+                     * one. This primes the buffer so
+                     * that we can return to the loop above and fill it
+                     * efficiently without a lot of function calls.
+                     */
+                    buffer_size = 1; /* get another message started */
+                }
+            }
+            buffer[bufx].message = 0;
+            buffer[bufx].timestamp = when;
+        } 
+        /* keep inserting bytes until you find MIDI_EOX */
+    }
+end_of_sysex:
+    /* we're finished sending full buffers, but there may
+     * be a partial one left.
+     */
+    if (shift != 0) bufx++; /* add partial message to buffer len */
+    if (bufx) { /* bufx is number of PmEvents to send from buffer */
+        PmError err = Pm_Write(stream, buffer, bufx);
+        if (err) return err;
+    }
+    return pmNoError;
+}
+
+
+
+PmError Pm_OpenInput(PortMidiStream** stream,
+                     PmDeviceID inputDevice,
+                     void *inputDriverInfo,
+                     long bufferSize,
+                     PmTimeProcPtr time_proc,
+                     void *time_info) {
+    PmInternal *midi;
+    PmError err = pmNoError;
+    pm_hosterror = FALSE;
+    *stream = NULL;
+    
+    /* arg checking */
+    if (inputDevice < 0 || inputDevice >= pm_descriptor_index) 
+        err = pmInvalidDeviceId;
+    else if (!descriptors[inputDevice].pub.input) 
+        err =  pmBadPtr;
+    else if(descriptors[inputDevice].pub.opened)
+        err =  pmBadPtr;
+    
+    if (err != pmNoError) 
+        goto error_return;
+
+    /* create portMidi internal data */
+    midi = (PmInternal *) pm_alloc(sizeof(PmInternal)); 
+    *stream = midi;
+    if (!midi) {
+        err = pmInsufficientMemory;
+        goto error_return;
+    }
+    midi->device_id = inputDevice;
+    midi->write_flag = FALSE;
+    midi->time_proc = time_proc;
+    midi->time_info = time_info;
+    /* windows adds timestamps in the driver and these are more accurate than
+       using a time_proc, so do not automatically provide a time proc. Non-win
+       implementations may want to provide a default time_proc in their
+       system-specific midi_out_open() method.
+     */
+    if (bufferSize <= 0) bufferSize = 256; /* default buffer size */
+#ifdef NEWBUFFER
+    midi->queue = Pm_QueueCreate(bufferSize, sizeof(PmEvent));
+    if (!midi->queue) {
+#else
+    else bufferSize++; /* buffer holds N-1 msgs, so increase request by 1 */
+    midi->buffer = (PmEvent *) pm_alloc(sizeof(PmEvent) * midi->buffer_len); 
+    midi->head = 0;
+    midi->tail = 0;
+    midi->overflow = FALSE;
+    if (!midi->buffer) { 
+#endif
+        /* free portMidi data */
+        *stream = NULL;
+        pm_free(midi); 
+        err = pmInsufficientMemory;
+        goto error_return;
+    }
+    midi->buffer_len = bufferSize; /* portMidi input storage */
+    midi->latency = 0; /* not used */
+    midi->sysex_in_progress = FALSE;
+    midi->sysex_message = 0; 
+    midi->sysex_message_count = 0; 
+    midi->filters = PM_FILT_ACTIVE;
+    midi->channel_mask = 0xFFFF;
+    midi->sync_time = 0;
+    midi->first_message = TRUE;
+    midi->dictionary = descriptors[inputDevice].dictionary;
+    midi->fill_base = NULL;
+    midi->fill_offset_ptr = NULL;
+    midi->fill_length = 0;
+    descriptors[inputDevice].internalDescriptor = midi;
+    /* open system dependent input device */
+    err = (*midi->dictionary->open)(midi, inputDriverInfo);
+    if (err) {
+        *stream = NULL;
+        descriptors[inputDevice].internalDescriptor = NULL;
+        /* free portMidi data */
+#ifdef NEWBUFFER
+        Pm_QueueDestroy(midi->queue);
+#else
+        pm_free(midi->buffer);  
+#endif
+        pm_free(midi);
+    } else {
+        /* portMidi input open successful */
+        descriptors[inputDevice].pub.opened = TRUE;
+    }
+error_return:
+    /* note: if there is a pmHostError, it is the responsibility
+     * of the system-dependent code (*midi->dictionary->open)()
+     * to set pm_hosterror and pm_hosterror_text
+     */
+    return pm_errmsg(err);
+}
+
+
+PmError Pm_OpenOutput(PortMidiStream** stream,
+                      PmDeviceID outputDevice,
+                      void *outputDriverInfo,
+                      long bufferSize,
+                      PmTimeProcPtr time_proc,
+                      void *time_info,
+                      long latency ) {
+    PmInternal *midi;
+    PmError err = pmNoError;
+    pm_hosterror = FALSE;
+    *stream =  NULL;
+    
+    /* arg checking */
+    if (outputDevice < 0 || outputDevice >= pm_descriptor_index)
+        err = pmInvalidDeviceId;
+    else if (!descriptors[outputDevice].pub.output) 
+        err = pmInvalidDeviceId;
+    else if (descriptors[outputDevice].pub.opened)
+        err = pmInvalidDeviceId;
+    if (err != pmNoError) 
+        goto error_return;
+
+    /* create portMidi internal data */
+    midi = (PmInternal *) pm_alloc(sizeof(PmInternal)); 
+    *stream = midi;                 
+    if (!midi) {
+        err = pmInsufficientMemory;
+        goto error_return;
+    }
+    midi->device_id = outputDevice;
+    midi->write_flag = TRUE;
+    midi->time_proc = time_proc;
+    /* if latency > 0, we need a time reference. If none is provided,
+       use PortTime library */
+    if (time_proc == NULL && latency != 0) {
+        if (!Pt_Started()) 
+            Pt_Start(1, 0, 0);
+        /* time_get does not take a parameter, so coerce */
+        midi->time_proc = (PmTimeProcPtr) Pt_Time;
+    }
+    midi->time_info = time_info;
+    midi->buffer_len = bufferSize;
+#ifdef NEWBUFFER
+    midi->queue = NULL; /* unused by output */
+#else
+    midi->buffer = NULL;
+    midi->head = 0; /* unused by output */
+    midi->tail = 0; /* unused by output */
+    midi->overflow = FALSE; /* not used */
+#endif
+    /* if latency zero, output immediate (timestamps ignored) */
+    /* if latency < 0, use 0 but don't return an error */
+    if (latency < 0) latency = 0;
+    midi->latency = latency;
+    midi->sysex_in_progress = FALSE;
+    midi->sysex_message = 0; /* unused by output */
+    midi->sysex_message_count = 0; /* unused by output */
+    midi->filters = 0; /* not used for output */
+    midi->channel_mask = 0xFFFF;
+    midi->sync_time = 0;
+    midi->first_message = TRUE;
+    midi->dictionary = descriptors[outputDevice].dictionary;
+    midi->fill_base = NULL;
+    midi->fill_offset_ptr = NULL;
+    midi->fill_length = 0;
+    descriptors[outputDevice].internalDescriptor = midi;
+    /* open system dependent output device */
+    err = (*midi->dictionary->open)(midi, outputDriverInfo);
+    if (err) {
+        *stream = NULL;
+        descriptors[outputDevice].internalDescriptor = NULL;
+        /* free portMidi data */
+        pm_free(midi); 
+    } else {
+        /* portMidi input open successful */
+        descriptors[outputDevice].pub.opened = TRUE;
+    }
+error_return:
+    /* note: system-dependent code must set pm_hosterror and
+     * pm_hosterror_text if a pmHostError occurs
+     */
+    return pm_errmsg(err);
+}
+
+
+PmError Pm_SetChannelMask(PortMidiStream *stream, int mask)
+{
+    PmInternal *midi = (PmInternal *) stream;
+    PmError err = pmNoError;
+
+    if (midi == NULL)
+        err = pmBadPtr;
+    else
+        midi->channel_mask = mask;
+
+    return pm_errmsg(err);
+}
+
+
+PmError Pm_SetFilter(PortMidiStream *stream, long filters) {
+    PmInternal *midi = (PmInternal *) stream;
+    PmError err = pmNoError;
+
+    /* arg checking */
+    if (midi == NULL)
+        err = pmBadPtr;
+    else if (!descriptors[midi->device_id].pub.opened)
+        err = pmBadPtr;
+    else
+        midi->filters = filters;
+    return pm_errmsg(err);
+}
+
+
+PmError Pm_Close( PortMidiStream *stream ) {
+    PmInternal *midi = (PmInternal *) stream;
+    PmError err = pmNoError;
+
+    pm_hosterror = FALSE;
+    /* arg checking */
+    if (midi == NULL) /* midi must point to something */
+        err = pmBadPtr;
+    /* if it is an open device, the device_id will be valid */
+    else if (midi->device_id < 0 || midi->device_id >= pm_descriptor_index)
+        err = pmBadPtr;
+    /* and the device should be in the opened state */
+    else if (!descriptors[midi->device_id].pub.opened)
+        err = pmBadPtr;
+    
+    if (err != pmNoError) 
+        goto error_return;
+
+    /* close the device */
+    err = (*midi->dictionary->close)(midi);
+    /* even if an error occurred, continue with cleanup */
+    descriptors[midi->device_id].internalDescriptor = NULL;
+    descriptors[midi->device_id].pub.opened = FALSE;
+#ifdef NEWBUFFER
+    if (midi->queue) Pm_QueueDestroy(midi->queue);
+#else
+    if (midi->buffer) pm_free(midi->buffer);       
+#endif
+    pm_free(midi); 
+error_return:
+    /* system dependent code must set pm_hosterror and
+     * pm_hosterror_text if a pmHostError occurs.
+     */
+    return pm_errmsg(err);
+}
+
+
+PmError Pm_Abort( PortMidiStream* stream ) {
+    PmInternal *midi = (PmInternal *) stream;
+    PmError err;
+    /* arg checking */
+    if (midi == NULL)
+        err = pmBadPtr;
+    if (!descriptors[midi->device_id].pub.output)
+        err = pmBadPtr;
+    if (!descriptors[midi->device_id].pub.opened)
+        err = pmBadPtr;
+    else
+        err = (*midi->dictionary->abort)(midi);
+
+    if (err == pmHostError) {
+        midi->dictionary->host_error(midi, pm_hosterror_text, 
+                                     PM_HOST_ERROR_MSG_LEN);
+        pm_hosterror = TRUE;
+    }
+    return pm_errmsg(err);
+}
+
+#ifndef NEWBUFFER
+/* this is apparently an orphan routine -- I can find no reference to it now -RBD */
+
+/* in win32 multimedia API (via callbacks) some of these functions used; assume never fail */
+long pm_next_time(PmInternal *midi) {
+
+    /* arg checking */
+    assert(midi != NULL);
+    
+    return midi->buffer[midi->head].timestamp;
+}
+#endif
+
+
+/* pm_channel_filtered returns non-zero if the channel mask is blocking the current channel */
+#define pm_channel_filtered(status, mask) \
+    ((((status) & 0xF0) != 0xF0) && (!(Pm_Channel((status) & 0x0F) & (mask))))
+
+
+/* The following two functions will checks to see if a MIDI message matches
+   the filtering criteria.  Since the sysex routines only want to filter realtime messages,
+   we need to have separate routines.
+ */
+
+
+/* pm_realtime_filtered returns non-zero if the filter will kill the current message.
+   Note that only realtime messages are checked here.
+ */
+#define pm_realtime_filtered(status, filters) \
+    ((((status) & 0xF0) == 0xF0) && ((1 << ((status) & 0xF)) & (filters)))
+
+/*
+    return ((status == MIDI_ACTIVE) && (filters & PM_FILT_ACTIVE))
+            ||  ((status == MIDI_CLOCK) && (filters & PM_FILT_CLOCK))
+            ||  ((status == MIDI_START) && (filters & PM_FILT_PLAY))
+            ||  ((status == MIDI_STOP) && (filters & PM_FILT_PLAY))
+            ||  ((status == MIDI_CONTINUE) && (filters & PM_FILT_PLAY))
+            ||  ((status == MIDI_F9) && (filters & PM_FILT_F9))
+            ||  ((status == MIDI_FD) && (filters & PM_FILT_FD))
+            ||  ((status == MIDI_RESET) && (filters & PM_FILT_RESET))
+            ||  ((status == MIDI_MTC) && (filters & PM_FILT_MTC))
+            ||  ((status == MIDI_SONGPOS) && (filters & PM_FILT_SONG_POSITION))
+            ||  ((status == MIDI_SONGSEL) && (filters & PM_FILT_SONG_SELECT))
+            ||  ((status == MIDI_TUNE) && (filters & PM_FILT_TUNE));
+}*/
+
+
+/* pm_status_filtered returns non-zero if a filter will kill the current message, based on status.
+   Note that sysex and real time are not checked.  It is up to the subsystem (winmm, core midi, alsa)
+   to filter sysex, as it is handled more easily and efficiently at that level.
+   Realtime message are filtered in pm_realtime_filtered.
+ */
+#define pm_status_filtered(status, filters) ((1 << (16 + ((status) >> 4))) & (filters))
+
+
+/*
+    return  ((status == MIDI_NOTE_ON) && (filters & PM_FILT_NOTE))
+            ||  ((status == MIDI_NOTE_OFF) && (filters & PM_FILT_NOTE))
+            ||  ((status == MIDI_CHANNEL_AT) && (filters & PM_FILT_CHANNEL_AFTERTOUCH))
+            ||  ((status == MIDI_POLY_AT) && (filters & PM_FILT_POLY_AFTERTOUCH))
+            ||  ((status == MIDI_PROGRAM) && (filters & PM_FILT_PROGRAM))
+            ||  ((status == MIDI_CONTROL) && (filters & PM_FILT_CONTROL))
+            ||  ((status == MIDI_PITCHBEND) && (filters & PM_FILT_PITCHBEND));
+
+}
+*/
+
+void pm_flush_sysex(PmInternal *midi, PmTimestamp timestamp)
+{
+    PmEvent event;
+    
+    /* there may be nothing in the buffer */
+    if (midi->sysex_message_count == 0) return; /* nothing to flush */
+    
+    event.message = midi->sysex_message;
+    event.timestamp = timestamp;
+    /* copied from pm_read_short, avoids filtering */
+    if (Pm_Enqueue(midi->queue, &event) == pmBufferOverflow) {
+        midi->sysex_in_progress = FALSE;
+    }
+    midi->sysex_message_count = 0;
+    midi->sysex_message = 0;
+}
+
+
+/* pm_read_short and pm_read_bytes
+   are the interface between system-dependent MIDI input handlers
+   and the system-independent PortMIDI code.
+   The input handler MUST obey these rules:
+   1) all short input messages must be sent to pm_read_short, which
+      enqueues them to a FIFO for the application.
+   2) eash buffer of sysex bytes should be reported by calling pm_read_bytes
+      (which sets midi->sysex_in_progress). After the eox byte, 
+      pm_read_bytes will clear sysex_in_progress
+ */
+
+/* pm_read_short is the place where all input messages arrive from 
+   system-dependent code such as pmwinmm.c. Here, the messages
+   are entered into the PortMidi input buffer. 
+ */
+void pm_read_short(PmInternal *midi, PmEvent *event)
+{ 
+#ifndef NEWBUFFER
+    long tail;
+#endif
+    int status;
+    /* arg checking */
+    assert(midi != NULL);
+    /* midi filtering is applied here */
+    status = Pm_MessageStatus(event->message);
+    if (!pm_status_filtered(status, midi->filters)
+        && (!is_real_time(status) || 
+            !pm_realtime_filtered(status, midi->filters))
+        && !pm_channel_filtered(status, midi->channel_mask)) {
+        /* if sysex is in progress and we get a status byte, it had
+           better be a realtime message or the starting SYSEX byte;
+           otherwise, we exit the sysex_in_progress state
+         */
+        if (midi->sysex_in_progress && (status & MIDI_STATUS_MASK)) {
+            /* two choices: real-time or not. If it's real-time, then
+             * this should be delivered as a sysex byte because it is
+             * embedded in a sysex message
+             */
+            if (is_real_time(status)) {
+                midi->sysex_message |= 
+                        (status << (8 * midi->sysex_message_count++));
+                if (midi->sysex_message_count == 4) {
+                    pm_flush_sysex(midi, event->timestamp);
+                }
+            } else { /* otherwise, it's not real-time. This interrupts
+                      * a sysex message in progress */
+                midi->sysex_in_progress = FALSE;
+            }
+#ifdef NEWBUFFER
+        } else if (Pm_Enqueue(midi->queue, event) == pmBufferOverflow) {
+            midi->sysex_in_progress = FALSE;
+        }
+#else
+        } else {
+            /* don't try to do anything more in an overflow state */
+            if (midi->overflow) return;
+
+            /* insert the message */
+            tail = midi->tail;
+            midi->buffer[tail++] = *event;
+            if (tail == midi->buffer_len) tail = 0;
+            if (tail == midi->head || midi->overflow) {
+                midi->overflow = TRUE;
+                midi->sysex_in_progress = FALSE; 
+                /* drop the rest of the message, this must be cleared 
+                   by caller when EOX is received */
+                   return;
+            }
+            midi->tail = tail; /* complete the write */
+        }
+#endif
+    }
+}
+
+/* pm_read_bytes -- read one (partial) sysex msg from MIDI data */
+/*
+ * returns how many bytes processed
+ */
+unsigned int pm_read_bytes(PmInternal *midi, unsigned char *data, 
+                    int len, PmTimestamp timestamp)
+{
+    unsigned int i = 0; /* index into data */
+    PmEvent event;
+    event.timestamp = timestamp;
+    assert(midi);
+    /* note that since buffers may not have multiples of 4 bytes,
+     * pm_read_bytes may be called in the middle of an outgoing
+     * 4-byte PortMidi message. sysex_in_progress indicates that
+     * a sysex has been sent but no eox.
+     */
+    if (len == 0) return 0; /* sanity check */
+    if (!midi->sysex_in_progress) {
+        while (i < len) { /* process all data */
+            unsigned char byte = data[i++];
+            if (byte == MIDI_SYSEX &&
+                !pm_realtime_filtered(byte, midi->filters)) {
+                midi->sysex_in_progress = TRUE;
+                i--; /* back up so code below will get SYSEX byte */
+                break; /* continue looping below to process msg */
+            } else if (byte == MIDI_EOX) {
+                midi->sysex_in_progress = FALSE;
+                return i; /* done with one message */
+            } else if (byte & MIDI_STATUS_MASK) {
+                /* We're getting MIDI but no sysex in progress.
+                 * Either the SYSEX status byte was dropped or
+                 * the message was filtered. Drop the data, but
+                 * send any embedded realtime bytes.
+                 */
+                /* assume that this is a real-time message:
+                 * it is an error to pass non-real-time messages
+                 * to pm_read_bytes
+                 */
+                event.message = byte;
+                pm_read_short(midi, &event);
+            }
+        } /* all bytes in the buffer are processed */
+    }
+    /* Now, i<len implies sysex_in_progress. If sysex_in_progress
+     * becomes false in the loop, there must have been an overflow
+     * and we can just drop all remaining bytes 
+     */
+    while (i < len && midi->sysex_in_progress) {
+        if (midi->sysex_message_count == 0 && i <= len - 4 &&
+            ((event.message = (((long) data[i]) | 
+                             (((long) data[i+1]) << 8) |
+                             (((long) data[i+2]) << 16) |
+                             (((long) data[i+3]) << 24))) &
+             0x80808080) == 0) { /* all data, no status */ 
+            if (Pm_Enqueue(midi->queue, &event) == pmBufferOverflow) {
+                midi->sysex_in_progress = FALSE;
+            }
+            i += 4;
+        } else {
+            while (i < len) {
+                /* send one byte at a time */
+                unsigned char byte = data[i++];
+                if (is_real_time(byte) && 
+                    pm_realtime_filtered(byte, midi->filters)) {
+                    continue; /* real-time data is filtered, so omit */
+                }
+                midi->sysex_message |= 
+                    (byte << (8 * midi->sysex_message_count++));
+                if (byte == MIDI_EOX) {
+                    midi->sysex_in_progress = FALSE;
+                    pm_flush_sysex(midi, event.timestamp);
+                    return i;
+                } else if (midi->sysex_message_count == 4) {
+                    pm_flush_sysex(midi, event.timestamp);
+                    /* after handling at least one non-data byte
+                     * and reaching a 4-byte message boundary,
+                     * resume trying to send 4 at a time in outer loop
+                     */
+                    break;
+                }
+            }
+        }
+    }
+    return i;
+}
+
+
+#ifndef NEWBUFFER
+/* this code is apparently never called */
+int pm_queue_full(PmInternal *midi)
+{
+    long tail;
+
+    /* arg checking */
+    assert(midi != NULL);
+    
+    tail = midi->tail + 1;
+    if (tail == midi->buffer_len) tail = 0;
+    return tail == midi->head;
+}
+#endif
diff --git a/portmidi/pm_common/portmidi.h b/portmidi/pm_common/portmidi.h
index 6601fc83a..8f4879f38 100644
--- a/portmidi/pm_common/portmidi.h
+++ b/portmidi/pm_common/portmidi.h
@@ -7,7 +7,12 @@ extern "C" {
 /*
  * PortMidi Portable Real-Time MIDI Library
  * PortMidi API Header File
- * Latest version available at: http://sourceforge.net/projects/portmedia
+ * Latest version available at: http://www.cs.cmu.edu/~music/portmidi/
+ *
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ * Copyright (c) 2001-2006 Roger B. Dannenberg
+ *
+ * Latest version available at: http://www.cs.cmu.edu/~music/portmidi/
  *
  * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
  * Copyright (c) 2001-2006 Roger B. Dannenberg
@@ -46,6 +51,24 @@ extern "C" {
 /* CHANGELOG FOR PORTMIDI
  *     (see ../CHANGELOG.txt)
  *
+ * IMPORTANT INFORMATION ABOUT A WIN32 BUG:
+ *
+ *    Windows apparently has a serious midi bug -- if you do not close ports, Windows
+ *    may crash. PortMidi tries to protect against this by using a DLL to clean up.
+ *
+ *    If client exits for example with:
+ *      i)  assert 
+ *      ii) Ctrl^c, 
+ *    then DLL clean-up routine called. However, when client does something 
+ *    really bad (e.g. assigns value to NULL pointer) then DLL CLEANUP ROUTINE
+ *    NEVER RUNS! In this state, if you wait around long enough, you will
+ *    probably get the blue screen of death. Can also go into Pview and there will
+ *    exist zombie process that you can't kill.
+ *
+ *    You can enable the DLL cleanup routine by defining USE_DLL_FOR_CLEANUP.
+ *    Do not define this preprocessor symbol if you do not want to use this
+ *    feature.
+ *
  * NOTES ON HOST ERROR REPORTING: 
  *
  *    PortMidi errors (of type PmError) are generic, system-independent errors.
@@ -90,6 +113,8 @@ extern "C" {
  *    PM_CHECK_ERRORS more-or-less takes over error checking for return values,
  *        stopping your program and printing error messages when an error
  *        occurs. This also uses stdio for console text I/O.
+ *    USE_DLL_FOR_CLEANUP is described above. (Windows only.)
+ *    
  */ 
 
 #ifndef FALSE
@@ -102,13 +127,11 @@ extern "C" {
 /* default size of buffers for sysex transmission: */
 #define PM_DEFAULT_SYSEX_BUFFER_SIZE 1024
 
-/** List of portmidi errors.*/
+
 typedef enum {
     pmNoError = 0,
-    pmNoData = 0, /**< A "no error" return that also indicates no data avail. */
-    pmGotData = 1, /**< A "no error" return that also indicates data available */
     pmHostError = -10000,
-    pmInvalidDeviceId, /** out of range or 
+    pmInvalidDeviceId, /* out of range or 
                         * output device when input is requested or 
                         * input device when output is requested or
                         * device is already opened 
@@ -116,34 +139,33 @@ typedef enum {
     pmInsufficientMemory,
     pmBufferTooSmall,
     pmBufferOverflow,
-    pmBadPtr, /* PortMidiStream parameter is NULL or
-               * stream is not opened or
-               * stream is output when input is required or
-               * stream is input when output is required */
-    pmBadData, /** illegal midi data, e.g. missing EOX */
+    pmBadPtr,
+    pmBadData, /* illegal midi data, e.g. missing EOX */
     pmInternalError,
-    pmBufferMaxSize /** buffer is already as large as it can be */
+    pmBufferMaxSize /* buffer is already as large as it can be */
     /* NOTE: If you add a new error type, be sure to update Pm_GetErrorText() */
 } PmError;
 
-/**
+/*
     Pm_Initialize() is the library initialisation function - call this before
     using the library.
 */
+
 PmError Pm_Initialize( void );
 
-/**
+/*
     Pm_Terminate() is the library termination function - call this after
     using the library.
 */
+
 PmError Pm_Terminate( void );
 
-/**  A single PortMidiStream is a descriptor for an open MIDI device.
+/*  A single PortMidiStream is a descriptor for an open MIDI device.
 */
 typedef void PortMidiStream;
 #define PmStream PortMidiStream
 
-/**
+/*
     Test whether stream has a pending host error. Normally, the client finds
     out about errors through returned error codes, but some errors can occur
     asynchronously where the client does not
@@ -160,13 +182,13 @@ typedef void PortMidiStream;
 int Pm_HasHostError( PortMidiStream * stream );
 
 
-/**  Translate portmidi error number into human readable message.
+/*  Translate portmidi error number into human readable message.
     These strings are constants (set at compile time) so client has 
     no need to allocate storage
 */
 const char *Pm_GetErrorText( PmError errnum );
 
-/**  Translate portmidi host error into human readable message.
+/*  Translate portmidi host error into human readable message.
     These strings are computed at run time, so client has to allocate storage.
     After this routine executes, the host error is cleared. 
 */
@@ -176,7 +198,7 @@ void Pm_GetHostErrorText(char * msg, unsigned int len);
 #define PM_HOST_ERROR_MSG_LEN 256u /* any host error msg will occupy less 
                                       than this number of characters */
 
-/**
+/*
     Device enumeration mechanism.
 
     Device ids range from 0 to Pm_CountDevices()-1.
@@ -185,77 +207,75 @@ void Pm_GetHostErrorText(char * msg, unsigned int len);
 typedef int PmDeviceID;
 #define pmNoDevice -1
 typedef struct {
-    int structVersion; /**< this internal structure version */ 
-    const char *interf; /**< underlying MIDI API, e.g. MMSystem or DirectX */
-    const char *name;   /**< device name, e.g. USB MidiSport 1x1 */
-    int input; /**< true iff input is available */
-    int output; /**< true iff output is available */
-    int opened; /**< used by generic PortMidi code to do error checking on arguments */
+    int structVersion; 
+    const char *interf; /* underlying MIDI API, e.g. MMSystem or DirectX */
+    const char *name;   /* device name, e.g. USB MidiSport 1x1 */
+    int input; /* true iff input is available */
+    int output; /* true iff output is available */
+    int opened; /* used by generic PortMidi code to do error checking on arguments */
 
 } PmDeviceInfo;
 
-/**  Get devices count, ids range from 0 to Pm_CountDevices()-1. */
+
 int Pm_CountDevices( void );
-/**
+/*
     Pm_GetDefaultInputDeviceID(), Pm_GetDefaultOutputDeviceID()
 
     Return the default device ID or pmNoDevice if there are no devices.
-    The result (but not pmNoDevice) can be passed to Pm_OpenMidi().
-    
-    The default device can be specified using a small application
-    named pmdefaults that is part of the PortMidi distribution. This
-    program in turn uses the Java Preferences object created by
-    java.util.prefs.Preferences.userRoot().node("/PortMidi"); the
-    preference is set by calling 
-        prefs.put("PM_RECOMMENDED_OUTPUT_DEVICE", prefName);
-    or  prefs.put("PM_RECOMMENDED_INPUT_DEVICE", prefName);
+    The result can be passed to Pm_OpenMidi().
     
-    In the statements above, prefName is a string describing the
-    MIDI device in the form "interf, name" where interf identifies
-    the underlying software system or API used by PortMdi to access
-    devices and name is the name of the device. These correspond to 
-    the interf and name fields of a PmDeviceInfo. (Currently supported
-    interfaces are "MMSystem" for Win32, "ALSA" for Linux, and 
-    "CoreMIDI" for OS X, so in fact, there is no choice of interface.)
-    In "interf, name", the strings are actually substrings of 
-    the full interface and name strings. For example, the preference 
-    "Core, Sport" will match a device with interface "CoreMIDI"
-    and name "In USB MidiSport 1x1". It will also match "CoreMIDI"
-    and "In USB MidiSport 2x2". The devices are enumerated in device
-    ID order, so the lowest device ID that matches the pattern becomes
-    the default device. Finally, if the comma-space (", ") separator
-    between interface and name parts of the preference is not found,
-    the entire preference string is interpreted as a name, and the
-    interface part is the empty string, which matches anything.
-
-    On the MAC, preferences are stored in 
-      /Users/$NAME/Library/Preferences/com.apple.java.util.prefs.plist
-    which is a binary file. In addition to the pmdefaults program,
-    there are utilities that can read and edit this preference file.
-
-    On the PC, 
-
-    On Linux, 
+    On the PC, the user can specify a default device by
+    setting an environment variable. For example, to use device #1.
 
+        set PM_RECOMMENDED_OUTPUT_DEVICE=1
+    
+    The user should first determine the available device ID by using
+    the supplied application "testin" or "testout".
+
+    In general, the registry is a better place for this kind of info,
+    and with USB devices that can come and go, using integers is not
+    very reliable for device identification. Under Windows, if
+    PM_RECOMMENDED_OUTPUT_DEVICE (or PM_RECOMMENDED_INPUT_DEVICE) is
+    *NOT* found in the environment, then the default device is obtained
+    by looking for a string in the registry under:
+        HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Input_Device
+    and HKEY_LOCAL_MACHINE/SOFTWARE/PortMidi/Recommended_Output_Device
+    for a string. The number of the first device with a substring that
+    matches the string exactly is returned. For example, if the string
+    in the registry is "USB", and device 1 is named 
+    "In USB MidiSport 1x1", then that will be the default
+    input because it contains the string "USB".
+
+    In addition to the name, PmDeviceInfo has the member "interf", which
+    is the interface name. (The "interface" is the underlying software
+    system or API used by PortMidi to access devices. Examples are 
+    MMSystem, DirectX (not implemented), ALSA, OSS (not implemented), etc.)
+    At present, the only Win32 interface is "MMSystem", the only Linux
+    interface is "ALSA", and the only Max OS X interface is "CoreMIDI".
+    To specify both the interface and the device name in the registry,
+    separate the two with a comma and a space, e.g.:
+        MMSystem, In USB MidiSport 1x1
+    In this case, the string before the comma must be a substring of
+    the "interf" string, and the string after the space must be a 
+    substring of the "name" name string in order to match the device.
+
+    Note: in the current release, the default is simply the first device
+    (the input or output device with the lowest PmDeviceID).
 */
 PmDeviceID Pm_GetDefaultInputDeviceID( void );
-/** see PmDeviceID Pm_GetDefaultInputDeviceID() */
 PmDeviceID Pm_GetDefaultOutputDeviceID( void );
 
-/**
+/*
     PmTimestamp is used to represent a millisecond clock with arbitrary
     start time. The type is used for all MIDI timestampes and clocks.
 */
 typedef long PmTimestamp;
 typedef PmTimestamp (*PmTimeProcPtr)(void *time_info);
 
-/** TRUE if t1 before t2 */
+/* TRUE if t1 before t2 */
 #define PmBefore(t1,t2) ((t1-t2) < 0)
-/** 
-    \defgroup grp_device Input/Output Devices Handling
-    @{
-*/
-/**
+
+/*
     Pm_GetDeviceInfo() returns a pointer to a PmDeviceInfo structure
     referring to the device specified by id.
     If id is out of range the function returns NULL.
@@ -266,7 +286,7 @@ typedef PmTimestamp (*PmTimeProcPtr)(void *time_info);
 */
 const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id );
 
-/**
+/*
     Pm_OpenInput() and Pm_OpenOutput() open devices.
 
     stream is the address of a PortMidiStream pointer which will receive
@@ -296,10 +316,10 @@ const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id );
     latency is the delay in milliseconds applied to timestamps to determine 
     when the output should actually occur. (If latency is < 0, 0 is assumed.) 
     If latency is zero, timestamps are ignored and all output is delivered
-    immediately. If latency is greater than zero, output is delayed until the
-    message timestamp plus the latency. (NOTE: the time is measured relative 
-    to the time source indicated by time_proc. Timestamps are absolute,
-    not relative delays or offsets.) In some cases, PortMidi can obtain
+    immediately. If latency is greater than zero, output is delayed until
+    the message timestamp plus the latency. (NOTE: time is measured relative
+    to the time source indicated by time_proc. Timestamps are absolute, not
+    relative delays or offsets.) In some cases, PortMidi can obtain
     better timing than your application by passing timestamps along to the
     device driver or hardware. Latency may also help you to synchronize midi
     data to audio data by matching midi latency to the audio buffer latency.
@@ -314,11 +334,7 @@ const PmDeviceInfo* Pm_GetDeviceInfo( PmDeviceID id );
     time_proc result values are appended to incoming MIDI data, and time_proc
     times are used to schedule outgoing MIDI data (when latency is non-zero).
 
-    time_info is a pointer passed to time_proc.
-
-    Example: If I provide a timestamp of 5000, latency is 1, and time_proc
-    returns 4990, then the desired output time will be when time_proc returns
-    timestamp+latency = 5001. This will be 5001-4990 = 11ms from now.
+    time_info is a pointer passed to time_proc. 
 
     return value:
     Upon success Pm_Open() returns PmNoError and places a pointer to a
@@ -344,14 +360,8 @@ PmError Pm_OpenOutput( PortMidiStream** stream,
                 PmTimeProcPtr time_proc,
                 void *time_info,
                 long latency );
-  /** @} */
-
-/**
-   \defgroup grp_events_filters Events and Filters Handling
-   @{
-*/
 
-/*  \function PmError Pm_SetFilter( PortMidiStream* stream, long filters )
+/* 
     Pm_SetFilter() sets filters on an open input stream to drop selected
     input types. By default, only active sensing messages are filtered.
     To prohibit, say, active sensing and sysex messages, call
@@ -364,57 +374,55 @@ PmError Pm_OpenOutput( PortMidiStream** stream,
     Or you may be using a sequencer or drum-machine for MIDI clock information but want to
     exclude any notes it may play.
  */
-    
-/* Filter bit-mask definitions */
-/** filter active sensing messages (0xFE): */
+
+/* filter active sensing messages (0xFE): */
 #define PM_FILT_ACTIVE (1 << 0x0E)
-/** filter system exclusive messages (0xF0): */
+/* filter system exclusive messages (0xF0): */
 #define PM_FILT_SYSEX (1 << 0x00)
-/** filter MIDI clock message (0xF8) */
-#define PM_FILT_CLOCK (1 << 0x08)
-/** filter play messages (start 0xFA, stop 0xFC, continue 0xFB) */
-#define PM_FILT_PLAY ((1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B))
-/** filter tick messages (0xF9) */
+/* filter clock messages (CLOCK 0xF8, START 0xFA, STOP 0xFC, and CONTINUE 0xFB) */
+#define PM_FILT_CLOCK ((1 << 0x08) | (1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B))
+/* filter play messages (start 0xFA, stop 0xFC, continue 0xFB) */
+#define PM_FILT_PLAY (1 << 0x0A)
+/* filter tick messages (0xF9) */
 #define PM_FILT_TICK (1 << 0x09)
-/** filter undefined FD messages */
+/* filter undefined FD messages */
 #define PM_FILT_FD (1 << 0x0D)
-/** filter undefined real-time messages */
+/* filter undefined real-time messages */
 #define PM_FILT_UNDEFINED PM_FILT_FD
-/** filter reset messages (0xFF) */
+/* filter reset messages (0xFF) */
 #define PM_FILT_RESET (1 << 0x0F)
-/** filter all real-time messages */
+/* filter all real-time messages */
 #define PM_FILT_REALTIME (PM_FILT_ACTIVE | PM_FILT_SYSEX | PM_FILT_CLOCK | \
     PM_FILT_PLAY | PM_FILT_UNDEFINED | PM_FILT_RESET | PM_FILT_TICK)
-/** filter note-on and note-off (0x90-0x9F and 0x80-0x8F */
+/* filter note-on and note-off (0x90-0x9F and 0x80-0x8F */
 #define PM_FILT_NOTE ((1 << 0x19) | (1 << 0x18))
-/** filter channel aftertouch (most midi controllers use this) (0xD0-0xDF)*/
+/* filter channel aftertouch (most midi controllers use this) (0xD0-0xDF)*/
 #define PM_FILT_CHANNEL_AFTERTOUCH (1 << 0x1D)
-/** per-note aftertouch (0xA0-0xAF) */
+/* per-note aftertouch (0xA0-0xAF) */
 #define PM_FILT_POLY_AFTERTOUCH (1 << 0x1A)
-/** filter both channel and poly aftertouch */
+/* filter both channel and poly aftertouch */
 #define PM_FILT_AFTERTOUCH (PM_FILT_CHANNEL_AFTERTOUCH | PM_FILT_POLY_AFTERTOUCH)
-/** Program changes (0xC0-0xCF) */
+/* Program changes (0xC0-0xCF) */
 #define PM_FILT_PROGRAM (1 << 0x1C)
-/** Control Changes (CC's) (0xB0-0xBF)*/
+/* Control Changes (CC's) (0xB0-0xBF)*/
 #define PM_FILT_CONTROL (1 << 0x1B)
-/** Pitch Bender (0xE0-0xEF*/
+/* Pitch Bender (0xE0-0xEF*/
 #define PM_FILT_PITCHBEND (1 << 0x1E)
-/** MIDI Time Code (0xF1)*/
+/* MIDI Time Code (0xF1)*/
 #define PM_FILT_MTC (1 << 0x01)
-/** Song Position (0xF2) */
+/* Song Position (0xF2) */
 #define PM_FILT_SONG_POSITION (1 << 0x02)
-/** Song Select (0xF3)*/
+/* Song Select (0xF3)*/
 #define PM_FILT_SONG_SELECT (1 << 0x03)
-/** Tuning request (0xF6)*/
+/* Tuning request (0xF6)*/
 #define PM_FILT_TUNE (1 << 0x06)
-/** All System Common messages (mtc, song position, song select, tune request) */
+/* All System Common messages (mtc, song position, song select, tune request) */
 #define PM_FILT_SYSTEMCOMMON (PM_FILT_MTC | PM_FILT_SONG_POSITION | PM_FILT_SONG_SELECT | PM_FILT_TUNE)
 
 
 PmError Pm_SetFilter( PortMidiStream* stream, long filters );
 
-#define Pm_Channel(channel) (1<<(channel))
-/**
+/*
     Pm_SetChannelMask() filters incoming messages based on channel.
     The mask is a 16-bit bitfield corresponding to appropriate channels
     The Pm_Channel macro can assist in calling this function.
@@ -425,9 +433,11 @@ PmError Pm_SetFilter( PortMidiStream* stream, long filters );
 
     All channels are allowed by default
 */
+#define Pm_Channel(channel) (1<<(channel))
+
 PmError Pm_SetChannelMask(PortMidiStream *stream, int mask);
 
-/**
+/*
     Pm_Abort() terminates outgoing messages immediately
     The caller should immediately close the output port;
     this call may result in transmission of a partial midi message.
@@ -437,14 +447,14 @@ PmError Pm_SetChannelMask(PortMidiStream *stream, int mask);
  */
 PmError Pm_Abort( PortMidiStream* stream );
      
-/**
+/*
     Pm_Close() closes a midi stream, flushing any pending buffers.
     (PortMidi attempts to close open streams when the application 
     exits -- this is particularly difficult under Windows.)
 */
 PmError Pm_Close( PortMidiStream* stream );
 
-/**
+/*
     Pm_Message() encodes a short Midi message into a long word. If data1
     and/or data2 are not present, use zero.
 
@@ -459,9 +469,7 @@ PmError Pm_Close( PortMidiStream* stream );
 #define Pm_MessageData1(msg) (((msg) >> 8) & 0xFF)
 #define Pm_MessageData2(msg) (((msg) >> 16) & 0xFF)
 
-typedef long PmMessage; /**< see PmEvent */
-/**
-   All midi data comes in the form of PmEvent structures. A sysex
+/* All midi data comes in the form of PmEvent structures. A sysex
    message is encoded as a sequence of PmEvent structures, with each
    structure carrying 4 bytes of the message, i.e. only the first
    PmEvent carries the status byte.
@@ -503,7 +511,7 @@ typedef long PmMessage; /**< see PmEvent */
    latency (the latency parameter used when opening the output port.)
    Do not expect PortMidi to sort data according to timestamps -- 
    messages should be sent in the correct order, and timestamps MUST 
-   be non-decreasing. See also "Example" for Pm_OpenOutput() above.
+   be non-decreasing.
 
    A sysex message will generally fill many PmEvent structures. On 
    output to a PortMidiStream with non-zero latency, the first timestamp
@@ -525,18 +533,13 @@ typedef long PmMessage; /**< see PmEvent */
    the interrupting real-time message to insure that timestamps are
    non-decreasing.
  */
+typedef long PmMessage;
 typedef struct {
     PmMessage      message;
     PmTimestamp    timestamp;
 } PmEvent;
 
-/** 
-    @}
-*/
-/** \defgroup grp_io Reading and Writing Midi Messages
-    @{
-*/
-/**
+/*
     Pm_Read() retrieves midi data into a buffer, and returns the number
     of events read. Result is a non-negative number unless an error occurs, 
     in which case a PmError value will be returned.
@@ -560,15 +563,15 @@ typedef struct {
     message" and will be flushed as well.
 
 */
-int Pm_Read( PortMidiStream *stream, PmEvent *buffer, long length );
+PmError Pm_Read( PortMidiStream *stream, PmEvent *buffer, long length );
 
-/**
+/*
     Pm_Poll() tests whether input is available, 
     returning TRUE, FALSE, or an error value.
 */
 PmError Pm_Poll( PortMidiStream *stream);
 
-/** 
+/* 
     Pm_Write() writes midi data from a buffer. This may contain:
         - short messages 
     or 
@@ -583,7 +586,7 @@ PmError Pm_Poll( PortMidiStream *stream);
 */
 PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, long length );
 
-/**
+/*
     Pm_WriteShort() writes a timestamped non-system-exclusive midi message.
     Messages are delivered in order as received, and timestamps must be 
     non-decreasing. (But timestamps are ignored if the stream was opened
@@ -591,12 +594,11 @@ PmError Pm_Write( PortMidiStream *stream, PmEvent *buffer, long length );
 */
 PmError Pm_WriteShort( PortMidiStream *stream, PmTimestamp when, long msg);
 
-/**
+/*
     Pm_WriteSysEx() writes a timestamped system-exclusive midi message.
 */
 PmError Pm_WriteSysEx( PortMidiStream *stream, PmTimestamp when, unsigned char *msg);
 
-/** @} */
 
 #ifdef __cplusplus
 }
diff --git a/portmidi/pm_linux/README_LINUX.txt b/portmidi/pm_linux/README_LINUX.txt
index ab6e456fb..d3adf5a9b 100644
--- a/portmidi/pm_linux/README_LINUX.txt
+++ b/portmidi/pm_linux/README_LINUX.txt
@@ -24,24 +24,6 @@ check for errors yourself.
 This code has not been carefully tested; however, 
 all test programs in pm_test seem to run properly.
 
-A NOTE ABOUT AMD64:
-
-When compiling portmidi under linux on an AMD64, I had to add the -fPIC
-flag to the gcc flags.
-
-Reason: when trying to build John Harrison's pyPortMidi gcc bailed out
-with this error:
-
-./linux/libportmidi.a(pmlinux.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC
-./linux/libportmidi.a: could not read symbols: Bad value
-collect2: ld returned 1 exit status
-error: command 'gcc' failed with exit status 1
-
-What they said:
-http://www.gentoo.org/proj/en/base/amd64/howtos/index.xml?part=1&chap=3
-On certain architectures (AMD64 amongst them), shared libraries *must* 
-be "PIC-enabled".
-
 CHANGELOG
 
 29-aug-2006 Roger B. Dannenberg
diff --git a/portmidi/pm_linux/pmlinuxalsa.c b/portmidi/pm_linux/pmlinuxalsa.c
index 1574b8dd9..6132e0906 100644
--- a/portmidi/pm_linux/pmlinuxalsa.c
+++ b/portmidi/pm_linux/pmlinuxalsa.c
@@ -9,7 +9,9 @@
 
 #include "stdlib.h"
 #include "portmidi.h"
+#ifdef NEWBUFFER
 #include "pmutil.h"
+#endif
 #include "pminternal.h"
 #include "pmlinuxalsa.h"
 #include "string.h"
diff --git a/portmidi/pm_mac/finddefault.c b/portmidi/pm_mac/finddefault.c
deleted file mode 100644
index a155c9e41..000000000
--- a/portmidi/pm_mac/finddefault.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/* finddefault.c -- find_default_device() implementation
-   Roger Dannenberg, June 2008
-*/
-
-#include <stdlib.h>
-#include <string.h>
-#include "portmidi.h"
-#include "pmmacosxcm.h"
-#include "readbinaryplist.h"
-
-/* Parse preference files, find default device, search devices --
-   This parses the preference file(s) once for input and once for
-   output, which is inefficient but much simpler to manage. Note
-   that using the readbinaryplist.c module, you cannot keep two
-   plist files (user and system) open at once (due to a simple
-   memory management scheme).
-*/
-PmDeviceID find_default_device(char *path, int input, PmDeviceID id)
-/* path -- the name of the preference we are searching for
-   input -- true iff this is an input device
-   id -- current default device id
-   returns matching device id if found, otherwise id
-*/
-{
-    static char *pref_file = "com.apple.java.util.prefs.plist";
-    char *pref_str = NULL;
-    // read device preferences
-    value_ptr prefs = bplist_read_user_pref(pref_file);
-    if (prefs) {
-        value_ptr pref_val = value_dict_lookup_using_path(prefs, path);
-        if (pref_val) {
-            pref_str = value_get_asciistring(pref_val);
-        }
-    }
-    if (!pref_str) {
-        bplist_free_data(); /* look elsewhere */
-        prefs = bplist_read_system_pref(pref_file);
-        if (prefs) {
-            value_ptr pref_val = value_dict_lookup_using_path(prefs, path);
-            if (pref_val) {
-                pref_str = value_get_asciistring(pref_val);
-            }
-        }
-    }
-    if (pref_str) { /* search devices for match */
-        int i = pm_find_default_device(pref_str, input);
-        if (i != pmNoDevice) {
-            id = i;
-	}
-    }
-    if (prefs) {
-        bplist_free_data();
-    }
-    return id;
-}
diff --git a/portmidi/pm_mac/pmmac.c b/portmidi/pm_mac/pmmac.c
index 13ac68300..fbf31c83d 100644
--- a/portmidi/pm_mac/pmmac.c
+++ b/portmidi/pm_mac/pmmac.c
@@ -11,44 +11,27 @@ non-CoreMIDI devices.
 
 #include "stdlib.h"
 #include "portmidi.h"
-#include "pmutil.h"
-#include "pminternal.h"
 #include "pmmacosxcm.h"
 
-PmDeviceID pm_default_input_device_id = -1;
-PmDeviceID pm_default_output_device_id = -1;
-
-void pm_init()
+PmError pm_init()
 {
-    PmError err = pm_macosxcm_init();
-    // this is set when we return to Pm_Initialize, but we need it
-    // now in order to (successfully) call Pm_CountDevices()
-    pm_initialized = TRUE;
-    if (!err) {
-        pm_default_input_device_id = find_default_device(
-                "/PortMidi/PM_RECOMMENDED_INPUT_DEVICE", TRUE, 
-                pm_default_input_device_id);
-        pm_default_output_device_id = find_default_device(
-                "/PortMidi/PM_RECOMMENDED_OUTPUT_DEVICE", FALSE, 
-                pm_default_output_device_id);
-    }
+    return pm_macosxcm_init();
 }
 
-
 void pm_term(void)
 {
     pm_macosxcm_term();
 }
 
+PmDeviceID pm_default_input_device_id = -1;
+PmDeviceID pm_default_output_device_id = -1;
 
 PmDeviceID Pm_GetDefaultInputDeviceID()
 {
-    Pm_Initialize();
     return pm_default_input_device_id;
 }
 
 PmDeviceID Pm_GetDefaultOutputDeviceID() {
-    Pm_Initialize();
     return pm_default_output_device_id;
 }
 
diff --git a/portmidi/pm_mac/pmmacosxcm.c b/portmidi/pm_mac/pmmacosxcm.c
index 14c5f8167..4971da1b6 100644
--- a/portmidi/pm_mac/pmmacosxcm.c
+++ b/portmidi/pm_mac/pmmacosxcm.c
@@ -26,7 +26,9 @@
 //#define CM_DEBUG 1
 
 #include "portmidi.h"
+#ifdef NEWBUFFER
 #include "pmutil.h"
+#endif
 #include "pminternal.h"
 #include "porttime.h"
 #include "pmmac.h"
@@ -100,7 +102,7 @@ midi_length(long msg)
         3, 3, 3, 3, 2, 2, 3, 1          /* 0x80 through 0xf0 */
     };
     static int low_lengths[] = {
-        1, 2, 3, 2, 1, 1, 1, 1,         /* 0xf0 through 0xf8 */
+        1, 1, 3, 2, 1, 1, 1, 1,         /* 0xf0 through 0xf8 */
         1, 1, 1, 1, 1, 1, 1, 1          /* 0xf9 through 0xff */
     };
 
@@ -108,7 +110,7 @@ midi_length(long msg)
     high = status >> 4;
     low = status & 15;
 
-    return (high != 0xF) ? high_lengths[high] : low_lengths[low];
+    return (high != 0xF0) ? high_lengths[high] : low_lengths[low];
 }
 
 static PmTimestamp midi_synchronize(PmInternal *midi)
@@ -418,18 +420,7 @@ midi_out_close(PmInternal *midi)
 static PmError
 midi_abort(PmInternal *midi)
 {
-    PmError err = pmNoError;
-    OSStatus macHostError;
-    MIDIEndpointRef endpoint =
-            (MIDIEndpointRef) descriptors[midi->device_id].descriptor;
-    macHostError = MIDIFlushOutput(endpoint);
-    if (macHostError != noErr) {
-        pm_hosterror = macHostError;
-        sprintf(pm_hosterror_text,
-                "Host error %ld: MIDIFlushOutput()", macHostError);
-        err = pmHostError;
-    }
-    return err;
+    return pmNoError;
 }
 
 
@@ -561,7 +552,13 @@ midi_end_sysex(PmInternal *midi, PmTimestamp when)
     /* make sure we don't go backward in time */
     if (m->sysex_timestamp < m->last_time) m->sysex_timestamp = m->last_time;
     
-    /* now send what's in the buffer */
+        /* if flush has been called in the meantime, packet list is NULL */
+    if (m->packet == NULL) {
+        m->packet = MIDIPacketListInit(m->packetList);
+        assert(m->packet);
+    }
+
+        /* now send what's in the buffer */
     err = send_packet(midi, m->sysex_buffer, m->sysex_byte_count,
                       m->sysex_timestamp);
     m->sysex_byte_count = 0;
@@ -682,10 +679,6 @@ CFStringRef EndpointName(MIDIEndpointRef endpoint, bool isExternal)
   
   str = NULL;
   MIDIObjectGetStringProperty(device, kMIDIPropertyName, &str);
-  if (CFStringGetLength(result) == 0) {
-      CFRelease(result);
-      return str;
-  }
   if (str != NULL) {
     // if an external device has only one entity, throw away
     // the endpoint name and just use the device name
@@ -693,10 +686,6 @@ CFStringRef EndpointName(MIDIEndpointRef endpoint, bool isExternal)
       CFRelease(result);
       return str;
     } else {
-      if (CFStringGetLength(str) == 0) {
-        CFRelease(str);
-        return result;
-      }
       // does the entity name already start with the device name?
       // (some drivers do this though they shouldn't)
       // if so, do not prepend
@@ -714,7 +703,6 @@ CFStringRef EndpointName(MIDIEndpointRef endpoint, bool isExternal)
   return result;
 }
 
-
 // Obtain the name of an endpoint, following connections.
 // The result should be released by the caller.
 static CFStringRef ConnectedEndpointName(MIDIEndpointRef endpoint)
diff --git a/portmidi/pm_mac/pmmacosxcm.h b/portmidi/pm_mac/pmmacosxcm.h
index 97235b5dd..172593595 100644
--- a/portmidi/pm_mac/pmmacosxcm.h
+++ b/portmidi/pm_mac/pmmacosxcm.h
@@ -1,6 +1,4 @@
 /* system-specific definitions */
 
 PmError pm_macosxcm_init(void);
-void pm_macosxcm_term(void);
-
-PmDeviceID find_default_device(char *path, int input, PmDeviceID id);
+void pm_macosxcm_term(void);
\ No newline at end of file
diff --git a/portmidi/pm_mac/readbinaryplist.c b/portmidi/pm_mac/readbinaryplist.c
deleted file mode 100644
index 027121523..000000000
--- a/portmidi/pm_mac/readbinaryplist.c
+++ /dev/null
@@ -1,1079 +0,0 @@
-/*
-
-readbinaryplist.c -- Roger B. Dannenberg, Jun 2008
-Based on ReadBinaryPList.m by Jens Ayton, 2007
-
-Here are his comments:
-
-Reader for binary property list files (version 00).
-
-This has been found to work on all 566 binary plists in my ~/Library/Preferences/
-and /Library/Preferences/ directories. This probably does not provide full
-test coverage. It has also been found to provide different data to Apple's
-implementation when presented with a key-value archive. This is because Apple's
-implementation produces undocumented CFKeyArchiverUID objects. My implementation
-produces dictionaries instead, matching the in-file representation used in XML
-and OpenStep plists. See extract_uid().
-
-Full disclosure: in implementing this software, I read one comment and one
-struct defintion in CFLite, Apple's implementation, which is under the APSL
-license. I also deduced the information about CFKeyArchiverUID from that code.
-However, none of the implementation was copied.
-
-Copyright (C) 2007 Jens Ayton
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-*/
-
-/* A note about memory management:
-Strings and possibly other values are unique and because the values
-associated with IDs are cached, you end up with a directed graph rather
-than a tree. It is tricky to free the data because if you do a simple
-depth-first search to free nodes, you will free nodes twice. I decided
-to allocate memory from blocks of 1024 bytes and keep the blocks in a
-list associated with but private to this module. So the user should
-access this module by calling:
-    bplist_read_file() or bplist_read_user_pref() or 
-    bplist_read_system_pref()
-which returns a value. When you are done with the value, call
-    bplist_free_data()
-This will of course free the value_ptr returned by bplist_read_*()
-
-To deal with memory exhaustion (what happens when malloc returns
-NULL?), use setjmp/longjmp -- a single setjmp protects the whole
-parser, and allocate uses longjmp to abort. After abort, memory
-is freed and NULL is returned to caller. There is not much here
-in the way of error reporting.
-
-Memory is obtained by calling allocate which either returns the
-memory requested or calls longjmp, so callers don't have to check.
-
-*/
-
-#include <sys/types.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-#include <stdio.h>
-#include <sys/stat.h>
-#include "readbinaryplist.h"
-#include <Carbon/Carbon.h>
-
-#define NO 0
-#define YES 1
-#define BOOL int
-
-#define MAXPATHLEN 256
-/* #define BPLIST_LOG_VERBOSE 1 */
-
-#if BPLIST_LOG_VERBOSE
-    #ifndef BPLIST_LOG
-        #define BPLIST_LOG 1
-    #endif
-#endif
-
-#if BPLIST_LOG
-    #define bplist_log printf
-#else
-    #define bplist_log(...)
-#endif
-
-#if BPLIST_LOG_VERBOSE
-    #define bplist_log_verbose bplist_log
-#else
-    #define bplist_log_verbose(...)
-#endif
-
-
-/********* MEMORY MANAGEMENT ********/
-#define BLOCK_SIZE 1024
-// memory is aligned to multiples of this; assume malloc automatically
-// aligns to this number and assume this number is > sizeof(void *)
-#define ALIGNMENT 8
-static void *block_list = NULL;
-static char *free_ptr = NULL;
-static char *end_ptr = NULL;
-static jmp_buf abort_parsing;
-
-static void *allocate(size_t size)
-{
-    void *result;
-    if (free_ptr + size > end_ptr) {
-        size_t how_much = BLOCK_SIZE;
-        // align everything to 8 bytes
-        if (size > BLOCK_SIZE - ALIGNMENT) {
-            how_much = size + ALIGNMENT;
-        }
-        result = malloc(how_much);
-        if (result == NULL) {
-            /* serious problem */
-            longjmp(abort_parsing, 1);
-        }
-        *((void **)result) = block_list;
-        block_list = result;
-        free_ptr = ((char *) result) + ALIGNMENT;
-        end_ptr = ((char *) result) + how_much;
-    }
-    // now, there is enough rooom at free_ptr
-    result = free_ptr;
-    free_ptr += size;
-    return result;
-}
-
-void bplist_free_data()
-{
-    while (block_list) {
-        void *next = *(void **)block_list;
-        free(block_list);
-        block_list = next;
-    }
-    free_ptr = NULL;
-    end_ptr = NULL;
-}
-
-// layout of trailer -- last 32 bytes in plist data
-    uint8_t unused[6];
-    uint8_t offset_int_size;
-    uint8_t object_ref_size;
-    uint64_t object_count;
-    uint64_t top_level_object;
-    uint64_t offset_table_offset;
-
-
-enum
-{
-    kHEADER_SIZE = 8,
-    kTRAILER_SIZE = 32, //sizeof(bplist_trailer_node),
-    kMINIMUM_SANE_SIZE = kHEADER_SIZE + kTRAILER_SIZE
-};
-
-
-static const char kHEADER_BYTES[kHEADER_SIZE] = "bplist00";
-
-// map from UID key to previously parsed value
-typedef struct cache_struct {
-    uint64_t key;
-    value_ptr value;
-    struct cache_struct *next;
-} cache_node, *cache_ptr;
-
-
-typedef struct bplist_info
-{
-    uint64_t object_count;
-    const uint8_t *data_bytes;
-    uint64_t length;
-    uint64_t offset_table_offset;
-    uint8_t offset_int_size;
-    uint8_t object_ref_size;
-    cache_ptr cache;
-} bplist_info_node, *bplist_info_ptr;
-
-
-static value_ptr bplist_read_pldata(pldata_ptr data);
-static value_ptr bplist_read_pref(char *filename, OSType folder_type);
-static uint64_t read_sized_int(bplist_info_ptr bplist, uint64_t offset, uint8_t size);
-static uint64_t read_offset(bplist_info_ptr bplist, uint64_t index);
-static BOOL read_self_sized_int(bplist_info_ptr bplist, uint64_t offset, uint64_t *outValue, size_t *outSize);
-
-static value_ptr extract_object(bplist_info_ptr bplist, uint64_t objectRef);
-static value_ptr extract_simple(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_int(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_real(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_date(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_data(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_ascii_string(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_unicode_string(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_uid(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_array(bplist_info_ptr bplist, uint64_t offset);
-static value_ptr extract_dictionary(bplist_info_ptr bplist, uint64_t offset);
-
-
-value_ptr value_create()
-{
-    value_ptr value = (value_ptr) allocate(sizeof(value_node));
-    return value;
-}
-
-
-void value_set_integer(value_ptr v, int64_t i) {
-    v->tag = kTAG_INT; v->integer = i;
-}
-
-void value_set_real(value_ptr v, double d) {
-    v->tag = kTAG_REAL; v->real = d;
-}
-
-// d is seconds since 1 January 2001
-void value_set_date(value_ptr v, double d) {
-    v->tag = kTAG_DATE; v->real = d;
-}
-
-void value_set_ascii_string(value_ptr v, const uint8_t *s, size_t len) {
-    v->tag = kTAG_ASCIISTRING;
-    v->string = (char *) allocate(len + 1);
-    memcpy(v->string, s, len);
-    v->string[len] = 0;
-}
-
-void value_set_unicode_string(value_ptr v, const uint8_t *s, size_t len) {
-    v->tag = kTAG_UNICODESTRING;
-    v->string = (char *) allocate(len + 1);
-    memcpy(v->string, s, len);
-    v->string[len] = 0;
-}
-
-void value_set_uid(value_ptr v, uint64_t uid)
-{
-    v->tag = kTAG_UID; v->uinteger = uid;
-}
-
-// value->data points to a pldata that points to the actual bytes
-// the bytes are copied, so caller must free byte source (*data)
-void value_set_data(value_ptr v, const uint8_t *data, size_t len) {
-    v->tag = kTAG_DATA;
-    pldata_ptr pldata = (pldata_ptr) allocate(sizeof(pldata_node));
-    pldata->data = (uint8_t *) allocate(len);
-    memcpy(pldata->data, data, len);
-    pldata->len = len;
-    v->data = pldata;
-    printf("value at %p gets data at %p\n", v, pldata);
-}
-
-// caller releases ownership of array to value_ptr v
-void value_set_array(value_ptr v, value_ptr *array, size_t length) {
-    array_ptr a = (array_ptr) allocate(sizeof(array_node));
-    a->array = array;
-    a->length = length;
-    v->tag = kTAG_ARRAY;
-    v->array = a;
-}
-
-// caller releases ownership of dict to value_ptr v
-void value_set_dict(value_ptr v, dict_ptr dict) {
-    v->tag = kTAG_DICTIONARY;
-    v->dict = dict;
-}
-
-
-// look up an objectref in the cache, a ref->value_ptr mapping
-value_ptr cache_lookup(cache_ptr cache, uint64_t ref)
-{
-    while (cache) {
-        if (cache->key == ref) {
-            return cache->value;
-        }
-        cache = cache->next;
-    }
-    return NULL;
-}
-
-
-// insert an objectref and value in the cache
-void cache_insert(cache_ptr *cache, uint64_t ref, value_ptr value)
-{
-    cache_ptr c = (cache_ptr) allocate(sizeof(cache_node));
-    c->key = ref;
-    c->value = value;
-    c->next = *cache;
-    *cache = c;
-}
-
-
-// insert an objectref and value in a dictionary
-void dict_insert(dict_ptr *dict, value_ptr key, value_ptr value)
-{
-    dict_ptr d = (dict_ptr) allocate(sizeof(dict_node));
-    d->key = key;
-    d->value = value;
-    d->next = *dict;
-    *dict = d;
-}
-
-
-BOOL is_binary_plist(pldata_ptr data)
-{
-    if (data->len < kMINIMUM_SANE_SIZE)  return NO;
-    return memcmp(data->data, kHEADER_BYTES, kHEADER_SIZE) == 0;
-}
-
-
-value_ptr bplist_read_file(char *filename)
-{
-    struct stat stbuf;
-    pldata_node pldata;
-    FILE *file;
-    size_t n;
-    value_ptr value;
-    int rslt = stat(filename, &stbuf);
-    if (rslt) {
-        perror("in stat: ");
-        bplist_log("Could not stat %s, error %d\n", filename, rslt);
-        return NULL;
-    }
-    pldata.len = stbuf.st_size;
-    // note: this is supposed to be malloc, not allocate. It is separate
-    // from the graph structure, large, and easy to free right after
-    // parsing.
-    pldata.data = (uint8_t *) malloc(pldata.len);
-    if (!pldata.data) {
-        bplist_log("Could not allocate %d bytes for %s\n",
-                   (long) pldata.len, filename);
-        return NULL;
-    }
-    file = fopen(filename, "rb");
-    if (!file) {
-        bplist_log("Could not open %s\n", filename);
-        return NULL;
-    }
-    n = fread(pldata.data, 1, pldata.len, file);
-    if (n != pldata.len) {
-        bplist_log("Error reading from %s\n", filename);
-        return NULL;
-    }
-    value = bplist_read_pldata(&pldata);
-    free(pldata.data);
-    return value;
-}
-
-
-value_ptr bplist_read_pref(char *filename, OSType folder_type)
-{
-    FSRef prefdir;
-    char cstr[MAXPATHLEN];
-
-    OSErr err = FSFindFolder(kOnAppropriateDisk, folder_type,
-                             FALSE, &prefdir);
-    if (err) {
-        bplist_log("Error finding preferences folder: %d\n", err);
-        return NULL;
-    }
-    err = FSRefMakePath(&prefdir, (UInt8 *) cstr, (UInt32) (MAXPATHLEN - 1));
-    if (err) {
-        bplist_log("Error making path name for preferences folder: %d\n", err);
-        return NULL;
-    }
-    strlcat(cstr, "/", MAXPATHLEN);
-    strlcat(cstr, filename, MAXPATHLEN);
-    return bplist_read_file(cstr);
-}
-
-
-value_ptr bplist_read_system_pref(char *filename) {
-    return bplist_read_pref(filename, kSystemPreferencesFolderType);
-}
-
-
-value_ptr bplist_read_user_pref(char *filename) {
-    return bplist_read_pref(filename, kPreferencesFolderType);
-}
-
-
-// data is stored with high-order bytes first.
-// read from plist data in a machine-independent fashion
-//
-uint64_t convert_uint64(uint8_t *ptr)
-{
-    uint64_t rslt = 0;
-    int i;
-    // shift in bytes, high-order first
-    for (i = 0; i < sizeof(uint64_t); i++) {
-        rslt <<= 8;
-        rslt += ptr[i];
-    }
-    return rslt;
-}
-
-
-value_ptr bplist_read_pldata(pldata_ptr data)
-{
-    value_ptr result = NULL;
-    bplist_info_node bplist;
-    uint8_t *ptr;
-    uint64_t top_level_object;
-    int i;
-
-    if (data == NULL)  return NULL;
-    if (!is_binary_plist(data)) {
-        bplist_log("Bad binary plist: too short or invalid header.\n");
-        return NULL;
-    }
-        
-    // read trailer
-    ptr = (uint8_t *) (data->data + data->len - kTRAILER_SIZE);
-    bplist.offset_int_size = ptr[6];
-    bplist.object_ref_size = ptr[7];
-    bplist.object_count = convert_uint64(ptr + 8);
-    top_level_object = convert_uint64(ptr + 16);
-    bplist.offset_table_offset = convert_uint64(ptr + 24);
-        
-    // Basic sanity checks
-    if (bplist.offset_int_size < 1 || bplist.offset_int_size > 8 ||
-        bplist.object_ref_size < 1 || bplist.object_ref_size > 8 ||
-        bplist.offset_table_offset < kHEADER_SIZE) {
-        bplist_log("Bad binary plist: trailer declared insane.\n");
-        return NULL;                
-    }
-        
-    // Ensure offset table is inside file
-    uint64_t offsetTableSize = bplist.offset_int_size * bplist.object_count;
-    if (offsetTableSize + bplist.offset_table_offset + kTRAILER_SIZE > 
-        data->len) {
-        bplist_log("Bad binary plist: offset table overlaps end of container.\n");
-        return NULL;
-    }
-        
-    bplist.data_bytes = data->data;
-    bplist.length = data->len;
-    bplist.cache = NULL; /* dictionary is empty */
-
-    bplist_log_verbose("Got a sane bplist with %llu items, offset_int_size: %u, object_ref_size: %u\n", 
-                      bplist.object_count, bplist.offset_int_size, 
-                      bplist.object_ref_size);
-    /* at this point, we are ready to do some parsing which allocates
-        memory for the result data structure. If memory allocation (using
-        allocate fails, a longjmp will return to here and we simply give up
-     */
-    i = setjmp(abort_parsing);
-    if (i == 0) {
-        result = extract_object(&bplist, top_level_object);
-    } else {
-        bplist_log("allocate() failed to allocate memory. Giving up.\n");
-        result = NULL;
-    }
-    if (!result) {
-        bplist_free_data();
-    }
-    return result;
-}
-
-
-static value_ptr extract_object(bplist_info_ptr bplist, uint64_t objectRef)
-{
-    uint64_t offset;
-    value_ptr result = NULL;
-    uint8_t objectTag;
-    
-    if (objectRef >= bplist->object_count) {
-        // Out-of-range object reference.
-        bplist_log("Bad binary plist: object index is out of range.\n");
-        return NULL;
-    }
-        
-    // Use cached object if it exists
-    result = cache_lookup(bplist->cache, objectRef);
-    if (result != NULL)  return result;
-        
-    // Otherwise, find object in file.
-    offset = read_offset(bplist, objectRef);
-    if (offset > bplist->length) {
-        // Out-of-range offset.
-        bplist_log("Bad binary plist: object outside container.\n");
-        return NULL;
-    }
-    objectTag = *(bplist->data_bytes + offset);
-    switch (objectTag & 0xF0) {
-    case kTAG_SIMPLE:
-        result = extract_simple(bplist, offset);
-        break;
-                
-    case kTAG_INT:
-        result = extract_int(bplist, offset);
-        break;
-                        
-    case kTAG_REAL:
-        result = extract_real(bplist, offset);
-        break;
-                        
-    case kTAG_DATE:
-        result = extract_date(bplist, offset);
-        break;
-                        
-    case kTAG_DATA:
-        result = extract_data(bplist, offset);
-        break;
-                        
-    case kTAG_ASCIISTRING:
-        result = extract_ascii_string(bplist, offset);
-        break;
-                        
-    case kTAG_UNICODESTRING:
-        result = extract_unicode_string(bplist, offset);
-        break;
-        
-    case kTAG_UID:
-        result = extract_uid(bplist, offset);
-        break;
-        
-    case kTAG_ARRAY:
-        result = extract_array(bplist, offset);
-        break;
-        
-    case kTAG_DICTIONARY:
-        result = extract_dictionary(bplist, offset);
-        break;
-        
-    default:
-        // Unknown tag.
-        bplist_log("Bad binary plist: unknown tag 0x%X.\n", 
-                   (objectTag & 0x0F) >> 4);
-        result = NULL;
-    }
-    
-    // Cache and return result.
-    if (result != NULL)  
-        cache_insert(&bplist->cache, objectRef, result);
-    return result;
-}
-
-
-static uint64_t read_sized_int(bplist_info_ptr bplist, uint64_t offset, 
-                               uint8_t size)
-{
-    assert(bplist->data_bytes != NULL && size >= 1 && size <= 8 && 
-           offset + size <= bplist->length);
-        
-    uint64_t result = 0;
-    const uint8_t *byte = bplist->data_bytes + offset;
-        
-    do {
-        // note that ints seem to be high-order first
-        result = (result << 8) | *byte++;
-    } while (--size);
-        
-    return result;
-}
-
-
-static uint64_t read_offset(bplist_info_ptr bplist, uint64_t index)
-{
-    assert(index < bplist->object_count);
-        
-    return read_sized_int(bplist, 
-            bplist->offset_table_offset + bplist->offset_int_size * index, 
-            bplist->offset_int_size);
-}
-
-
-static BOOL read_self_sized_int(bplist_info_ptr bplist, uint64_t offset, 
-                             uint64_t *outValue, size_t *outSize)
-{
-    uint32_t size;
-    int64_t value;
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-    size = 1 << (bplist->data_bytes[offset] & 0x0F);
-    if (size > 8) {
-        // Maximum allowable size in this implementation is 1<<3 = 8 bytes.
-        // This also happens to be the biggest we can handle.
-        return NO;
-    }
-        
-    if (offset + 1 + size > bplist->length) {
-        // Out of range.
-        return NO;
-    }
-        
-    value = read_sized_int(bplist, offset + 1, size);
-    
-    if (outValue != NULL) *outValue = value;
-    if (outSize != NULL) *outSize = size + 1; // +1 for tag byte.
-    return YES;
-}
-
-
-static value_ptr extract_simple(bplist_info_ptr bplist, uint64_t offset)
-{
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-    value_ptr value = value_create();
-        
-    switch (bplist->data_bytes[offset]) {
-    case kVALUE_NULL:
-        value->tag = kVALUE_NULL;
-        return value;
-        
-    case kVALUE_TRUE:
-        value->tag = kVALUE_TRUE;
-        return value;
-                        
-    case kVALUE_FALSE:
-        value->tag = kVALUE_FALSE;
-        return value;
-    }
-        
-    // Note: kVALUE_FILLER is treated as invalid, because it, er, is.
-    bplist_log("Bad binary plist: invalid atom.\n");
-    free(value);
-    return NULL;
-}
-
-
-static value_ptr extract_int(bplist_info_ptr bplist, uint64_t offset)
-{
-    value_ptr value = value_create();
-    value->tag = kTAG_INT;
-
-    if (!read_self_sized_int(bplist, offset, &value->uinteger, NULL)) {
-        bplist_log("Bad binary plist: invalid integer object.\n");
-    }
-        
-    /* NOTE: originally, I sign-extended here. This was the wrong thing; it
-       turns out that negative ints are always stored as 64-bit, and smaller
-       ints are unsigned.
-    */
-    return value;
-}
-
-
-static value_ptr extract_real(bplist_info_ptr bplist, uint64_t offset)
-{
-    value_ptr value = value_create();
-    uint32_t size;
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-    
-    size = 1 << (bplist->data_bytes[offset] & 0x0F);
-        
-    // FIXME: what to do if faced with other sizes for float/double?
-    assert (sizeof (float) == sizeof (uint32_t) && 
-            sizeof (double) == sizeof (uint64_t));
-        
-    if (offset + 1 + size > bplist->length) {
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                  "floating-point number");
-        free(value);
-        return NULL;
-    }
-        
-    if (size == sizeof (float)) {
-        uint32_t i = read_sized_int(bplist, offset + 1, size); 
-        // Note that this handles byte swapping.
-        value_set_real(value, *(float *)&i);
-        return value;
-    } else if (size == sizeof (double)) {
-        uint64_t i = read_sized_int(bplist, offset + 1, size);
-        // Note that this handles byte swapping.
-        value_set_real(value, *(double *)&i);
-        return value;
-    } else {
-        // Can't handle floats of other sizes.
-        bplist_log("Bad binary plist: can't handle %u-byte float.\n", size);
-        free(value);
-        return NULL;
-    }
-}
-
-
-static value_ptr extract_date(bplist_info_ptr bplist, uint64_t offset)
-{
-    value_ptr value;
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-    // Data has size code like int and real, but only 3 (meaning 8 bytes) is valid.
-    if (bplist->data_bytes[offset] != kVALUE_FULLDATETAG) {
-        bplist_log("Bad binary plist: invalid size for date object.\n");
-        return NULL;
-    }
-        
-    if (offset + 1 + sizeof (double) > bplist->length) {
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                  "date");
-        return NULL;
-    }
-        
-    // FIXME: what to do if faced with other sizes for double?
-    assert (sizeof (double) == sizeof (uint64_t));
-        
-    uint64_t date = read_sized_int(bplist, offset + 1, sizeof(double));
-    // Note that this handles byte swapping.
-    value = value_create();
-    value_set_date(value, *(double *)&date);
-    return value;
-}
-
-
-uint64_t bplist_get_a_size(bplist_info_ptr bplist, 
-                           uint64_t *offset_ptr, char *msg)
-{
-    uint64_t size = bplist->data_bytes[*offset_ptr] & 0x0F;
-    (*offset_ptr)++;
-    if (size == 0x0F) {
-        // 0x0F means separate int size follows. 
-        // Smaller values are used for short data.
-        size_t extra; // the length of the data size we are about to read
-        if ((bplist->data_bytes[*offset_ptr] & 0xF0) != kTAG_INT) {
-            // Bad data, mistagged size int
-            bplist_log("Bad binary plist: %s object size is not tagged as int.\n",
-                       msg);
-            return UINT64_MAX; // error
-        }
-                
-        // read integer data as size, extra tells how many bytes to skip
-        if (!read_self_sized_int(bplist, *offset_ptr, &size, &extra)) {
-            bplist_log("Bad binary plist: invalid %s object size tag.\n", 
-                      "data");
-            return UINT64_MAX; // error
-        }
-        (*offset_ptr) += extra;
-    }
-
-    if (*offset_ptr + size > bplist->length) {
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                  "data");
-        return UINT64_MAX; // error
-    }
-    return size;
-}
-
-
-static value_ptr extract_data(bplist_info_ptr bplist, uint64_t offset)
-{
-    uint64_t size;
-    value_ptr value;
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-    if ((size = bplist_get_a_size(bplist, &offset, "data")) == UINT64_MAX) 
-        return NULL;
-        
-    value = value_create();
-    value_set_data(value, bplist->data_bytes + offset, size);
-    return value;
-}
-
-
-static value_ptr extract_ascii_string(bplist_info_ptr bplist, uint64_t offset)
-{
-    uint64_t size;
-    value_ptr value; // return value
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-    if ((size = bplist_get_a_size(bplist, &offset, "ascii string")) ==
-        UINT64_MAX) 
-        return NULL;
-
-    value = value_create();
-    value_set_ascii_string(value, bplist->data_bytes + offset, size);
-    return value;
-}
-
-
-static value_ptr extract_unicode_string(bplist_info_ptr bplist, uint64_t offset)
-{
-    uint64_t size;
-    value_ptr value;
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-    if ((size = bplist_get_a_size(bplist, &offset, "unicode string")) == 
-        UINT64_MAX)
-        return NULL;
-        
-    value = value_create();
-    value_set_unicode_string(value, bplist->data_bytes + offset, size);
-    return value;
-}
-
-
-static value_ptr extract_uid(bplist_info_ptr bplist, uint64_t offset)
-{
-    /* UIDs are used by Cocoa's key-value coder.
-       When writing other plist formats, they are expanded to dictionaries of
-       the form <dict><key>CF$UID</key><integer>value</integer></dict>, so we
-       do the same here on reading. This results in plists identical to what
-       running plutil -convert xml1 gives us. However, this is not the same
-       result as [Core]Foundation's plist parser, which extracts them as un-
-       introspectable CF objects. In fact, it even seems to convert the CF$UID
-       dictionaries from XML plists on the fly.
-    */
-        
-    value_ptr value;
-    uint64_t uid;
-        
-    if (!read_self_sized_int(bplist, offset, &uid, NULL)) {
-        bplist_log("Bad binary plist: invalid UID object.\n");
-        return NULL;
-    }
-        
-    assert(NO); // original code suggests using a string for a key
-    // but our dictionaries all use big ints for keys, so I don't know
-    // what to do here
-
-    value = value_create();
-    value_set_uid(value, uid);
-    // return [NSDictionary dictionaryWithObject:
-    //         [NSNumber numberWithUnsignedLongLong:value] 
-    //         forKey:"CF$UID"];
-}
-
-
-static value_ptr extract_array(bplist_info_ptr bplist, uint64_t offset)
-{
-    uint64_t i, count;
-    uint64_t size;
-    uint64_t elementID;
-    value_ptr element = NULL;
-    value_ptr *array = NULL;
-    value_ptr value = NULL;
-    BOOL ok = YES;
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-    if ((count = bplist_get_a_size(bplist, &offset, "array")) == UINT64_MAX)
-        return NULL;
-        
-    if (count > UINT64_MAX / bplist->object_ref_size - offset) {
-        // Offset overflow.
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                   "array");
-        return NULL;
-    }
-        
-    size = bplist->object_ref_size * count;
-    if (size + offset > bplist->length) {
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                   "array");
-        return NULL;
-    }
-        
-    // got count, the number of array elements
-
-    value = value_create();
-    assert(value);
-
-    if (count == 0) {
-        value_set_array(value, array, count);
-        return value;
-    }
-        
-    array = allocate(sizeof(value_ptr) * count);
-        
-    for (i = 0; i != count; ++i) {
-        bplist_log_verbose("[%u]\n", i);
-        elementID = read_sized_int(bplist, offset + i * bplist->object_ref_size, 
-                                 bplist->object_ref_size);
-        element = extract_object(bplist, elementID);
-        if (element != NULL) {
-            array[i] = element;
-        } else {
-            ok = NO;
-            break;
-        }
-    }
-    if (ok) {
-        value_set_array(value, array, count);
-    }
-
-    return value;
-}
-
-
-static value_ptr extract_dictionary(bplist_info_ptr bplist, uint64_t offset)
-{
-    uint64_t i, count;
-    uint64_t size;
-    uint64_t elementID;
-    value_ptr value = NULL;
-    dict_ptr dict = NULL;
-    BOOL ok = YES;
-        
-    assert(bplist->data_bytes != NULL && offset < bplist->length);
-        
-        
-    if ((count = bplist_get_a_size(bplist, &offset, "array")) == UINT64_MAX)
-        return NULL;
-
-    if (count > UINT64_MAX / (bplist->object_ref_size * 2) - offset) {
-        // Offset overflow.
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                   "dictionary");
-        return NULL;
-    }
-    
-    size = bplist->object_ref_size * count * 2;
-    if (size + offset > bplist->length) {
-        bplist_log("Bad binary plist: %s object overlaps end of container.\n", 
-                   "dictionary");
-        return NULL;
-    }
-    
-    value = value_create();
-    if (count == 0) {
-        value_set_dict(value, NULL);
-        return value;
-    }
-
-    for (i = 0; i != count; ++i) {
-        value_ptr key;
-        value_ptr val;
-        elementID = read_sized_int(bplist, offset + i * bplist->object_ref_size, 
-                                 bplist->object_ref_size);
-        key = extract_object(bplist, elementID);
-        if (key != NULL) {
-            bplist_log_verbose("key: %p\n", key);
-        } else {
-            ok = NO;
-            break;
-        }
-                    
-        elementID = read_sized_int(bplist, 
-                            offset + (i + count) * bplist->object_ref_size, 
-                            bplist->object_ref_size);
-        val = extract_object(bplist, elementID);
-        if (val != NULL) {
-            dict_insert(&dict, key, val);
-        } else {
-            ok = NO;
-            break;
-        }
-    }
-    if (ok) {
-        value_set_dict(value, dict);
-    }
-    
-    return value;
-}
-
-/*************** functions for accessing values ****************/
-
-
-char *value_get_asciistring(value_ptr v)
-{
-    if (v->tag != kTAG_ASCIISTRING) return NULL;
-    return v->string;
-}
-
-
-value_ptr value_dict_lookup_using_string(value_ptr v, char *key)
-{
-    dict_ptr dict;
-    if (v->tag != kTAG_DICTIONARY) return NULL; // not a dictionary
-    dict = v->dict;
-    /* search for key */
-    while (dict) {
-        if (dict->key && dict->key->tag == kTAG_ASCIISTRING &&
-            strcmp(key, dict->key->string) == 0) { // found it
-            return dict->value;
-        }
-        dict = dict->next;
-    }
-    return NULL; /* not found */
-}
-
-value_ptr value_dict_lookup_using_path(value_ptr v, char *path)
-{
-    char key[MAX_KEY_SIZE];
-    while (*path) { /* more to the path */
-        int i = 0;
-        while (i < MAX_KEY_SIZE - 1) {
-            key[i] = *path++;
-            if (key[i] == '/') { /* end of entry in path */
-                key[i + 1] = 0;
-                break;
-            }
-            if (!key[i]) {
-                path--; /* back up to end of string char */
-                break;  /* this will cause outer loop to exit */
-            }
-            i++;
-        }
-        if (!v || v->tag != kTAG_DICTIONARY) return NULL;
-        /* now, look up the key to get next value */
-        v = value_dict_lookup_using_string(v, key);
-        if (v == NULL) return NULL;
-    }
-    return v;
-}
-                
-
-/*************** functions for debugging ***************/
-
-void plist_print(value_ptr v)
-{
-    size_t i;
-    int comma_needed;
-    dict_ptr dict;
-    if (!v) {
-        printf("NULL");
-        return;
-    }
-    switch (v->tag & 0xF0) {
-    case kTAG_SIMPLE:
-        switch (v->tag) {
-        case kVALUE_NULL: 
-            printf("NULL@%p", v); break;
-        case kVALUE_FALSE: 
-            printf("FALSE@%p", v); break;
-        case kVALUE_TRUE:
-            printf("TRUE@%p", v); break;
-        default:
-            printf("UNKNOWN tag=%x@%p", v->tag, v); break;
-        }
-        break;
-    case kTAG_INT:
-        printf("%lld@%p", v->integer, v); break;
-    case kTAG_REAL:
-        printf("%g@%p", v->real, v); break;
-    case kTAG_DATE:
-        printf("date:%g@%p", v->real, v); break;
-    case kTAG_DATA:
-        printf("data@%p->%p:[%p:", v, v->data, v->data->data);
-        for (i = 0; i < v->data->len; i++) {
-            printf(" %2x", v->data->data[i]);
-        }
-        printf("]"); break;
-    case kTAG_ASCIISTRING:
-        printf("%p:\"%s\"@%p", v->string, v->string, v); break;
-    case kTAG_UNICODESTRING:
-        printf("unicode:%p:\"%s\"@%p", v->string, v->string, v); break;
-    case kTAG_UID:
-        printf("UID:%llu@%p", v->uinteger, v); break;
-    case kTAG_ARRAY:
-        comma_needed = FALSE;
-        printf("%p->%p:[%p:", v, v->array, v->array->array);
-        for (i = 0; i < v->array->length; i++) {
-            if (comma_needed) printf(", ");
-            plist_print(v->array->array[i]);
-            comma_needed = TRUE;
-        }
-        printf("]"); break;
-    case kTAG_DICTIONARY:
-        comma_needed = FALSE;
-        printf("%p:[", v);
-        dict = v->dict;
-        while (dict) {
-            if (comma_needed) printf(", ");
-            printf("%p:", dict);
-            plist_print(dict->key);
-            printf("->");
-            plist_print(dict->value);
-            comma_needed = TRUE;
-            dict = dict->next;
-        }
-        printf("]"); break;
-    default:
-        printf("UNKNOWN tag=%x", v->tag);
-        break;
-    }
-}
-
-            
diff --git a/portmidi/pm_mac/readbinaryplist.h b/portmidi/pm_mac/readbinaryplist.h
deleted file mode 100644
index 596138a02..000000000
--- a/portmidi/pm_mac/readbinaryplist.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/* readbinaryplist.h -- header to read preference files
-
-   Roger B. Dannenberg, Jun 2008
-*/
-
-#include <stdint.h>
-
-#ifndef TRUE
-    #define TRUE 1
-    #define FALSE 0
-#endif
-
-#define MAX_KEY_SIZE 256
-
-enum
-{
-    // Object tags (high nybble)
-    kTAG_SIMPLE = 0x00,        // Null, true, false, filler, or invalid
-    kTAG_INT = 0x10,
-    kTAG_REAL = 0x20,
-    kTAG_DATE = 0x30,
-    kTAG_DATA = 0x40,
-    kTAG_ASCIISTRING = 0x50,
-    kTAG_UNICODESTRING = 0x60,
-    kTAG_UID = 0x80,
-    kTAG_ARRAY = 0xA0,
-    kTAG_DICTIONARY = 0xD0,
-    
-    // "simple" object values
-    kVALUE_NULL = 0x00,
-    kVALUE_FALSE = 0x08,
-    kVALUE_TRUE = 0x09,
-    kVALUE_FILLER = 0x0F,
-    
-    kVALUE_FULLDATETAG = 0x33        // Dates are tagged with a whole byte.
-};
-
-
-typedef struct {
-    uint8_t *data;
-    size_t len;
-} pldata_node, *pldata_ptr;
-
-
-typedef struct {
-    struct value_struct **array;
-    uint64_t length;
-} array_node, *array_ptr;
-
-
-// a dict_node is a list of <key, value> pairs
-typedef struct dict_struct {
-    struct value_struct *key;
-    struct value_struct *value;
-    struct dict_struct *next;
-} dict_node, *dict_ptr;
-
-
-// an value_node is a value with a tag telling the type
-typedef struct value_struct {
-    int tag;
-    union {
-        int64_t integer;
-        uint64_t uinteger;
-        double real;
-        char *string;
-        pldata_ptr data;
-        array_ptr array;
-        struct dict_struct *dict;
-    };
-} value_node, *value_ptr;
-
-
-value_ptr bplist_read_file(char *filename);
-value_ptr bplist_read_user_pref(char *filename);
-value_ptr bplist_read_system_pref(char *filename);
-void bplist_free_data();
-
-/*************** functions for accessing values ****************/
-
-char *value_get_asciistring(value_ptr v);
-value_ptr value_dict_lookup_using_string(value_ptr v, char *key);
-value_ptr value_dict_lookup_using_path(value_ptr v, char *path);
-
-/*************** functions for debugging ***************/
-
-void plist_print(value_ptr v);
-
diff --git a/portmidi/pm_win/README_WIN.txt b/portmidi/pm_win/README_WIN.txt
index 29549cb18..3fe5ee417 100644
--- a/portmidi/pm_win/README_WIN.txt
+++ b/portmidi/pm_win/README_WIN.txt
@@ -1,12 +1,19 @@
 File: PortMidi Win32 Readme
 Author: Belinda Thom, June 16 2002
-Revised by: Roger Dannenberg, June 2002, May 2004, June 2007, 
-            Umpei Kurokawa, June 2007
+Revised by: Roger Dannenberg, June 2002, May 2004
 
 =============================================================================
 USING PORTMIDI:
 =============================================================================
 
+PortMidi has been created using a DLL because the Win32 MMedia API doesn't 
+handle midiInput properly in the debugger. Specifically, it doesn't clean up
+after itself if the user (i.e. you, a PortMidi application) hasn't explicitly
+closed all open midi input devices. This lack of cleanup can lead to much
+pain and agony, including the blue-screen-of-death. This situation becomes
+increasingly unacceptable when you are debugging your code, so a portMidi DLL
+seemed to be the most elegant solution.
+
 Using Microsoft Visual C++ project files (provided with PortMidi), there
 are two configurations of the PortMidi library. The Debug version is 
 intended for debugging, especially in a console application. The Debug
@@ -31,9 +38,9 @@ See <...>\pm_dll_test\test.c or <...>\multithread\test.c for usage examples.
 =============================================================================
 TO INSTALL PORTMIDI:
 =============================================================================
-1)  get current source from the portmedia project at SourceForge.net
+1)  download portmidi.zip
 
-2)  copy source into directory: <...>\portmidi
+2)  unzip portmidi.zip into directory: <...>\portmidi
 
 =============================================================================
 TO COMPILE PORTMIDI:
@@ -41,59 +48,58 @@ TO COMPILE PORTMIDI:
 
 3)  cd to or open the portmidi directory
 
-4)  start or click on the portmidi.sln workspace (note, there is also
-    portmidi-VC9.sln for Visual C++ version 9 users).
-	
+4)  start or click on the portmidi.dsw workspace
+
 5)  the following projects exist within this workspace:
     - portmidi (the PortMidi library)
-    - porttime (a small portable library implementing timer facilities)
-    - test (simple midi I/O testing)
-    - midithread (an example illustrating low-latency MIDI processing
-        using a dedicated low-latency thread)
-    - sysex (simple sysex message I/O testing)
-    - latency (uses porttime to measure system latency)
-    - midithru (an example illustrating software MIDI THRU)
-    - qtest (a test of the new multicore-safe queue implementation)
-    - mm  (allows monitoring of midi messages)
-    - pmjni (a dll to provide an interface to PortMidi for Java)
-
-6)  open the pmjni project properties
-    - visit Configuration Properties, C/C++, General
-    - find Additional Include Directories property and open the editor (...)
-    - at the end of the list, you will find two paths beginning with E:\
-    - these are absolute paths to the Java SDK; you'll need to install the
-      Java SDK (from Sun) and update these directories in order to build
-      this project.
+	- pm_dll (the dll library used to close midi ports on program exit)
+	- porttime (a small portable library implementing timer facilities)
+	- test (simple midi I/O testing)
+	- multithread (an example illustrating low-latency MIDI processing
+            using a dedicated low-latency thread)
+	- sysex (simple sysex message I/O testing)
+	- latency (uses porttime to measure system latency)
 
 6)  verify that all project settings are for Win32 Debug release:
-    - type Alt-F7
-    - highlight all three projects in left part of Project Settings window; 
-    - "Settings For" should say "Win32 Debug"
-	
-    -In Visual C++ 2005 Express Edition, there is a drop down menu in 
-     the top toolbar to select the Win32 and Debug option.
+	- type Alt-F7
+	- highlight all three projects in left part of Project Settings window; 
+	- "Settings For" should say "Win32 Debug"
 
 7)  use Build->Batch Build ... to build everything in the project
-	
-    -In Visual C++ 2005 Express Edition, use Build->Build Solution
-	
+
 8)  The settings for these projects were distributed in the zip file, so
     compile should just work.
 
-9)  run test project; use the menu that shows up from the command prompt to
+9)  IMPORTANT! PortMidi uses a DLL, pm_dll.dll, but there is no simple way
+    to set up projects to use pm_dll. THEREFORE, you need to copy DLLs
+    as follows (you can do this with <...>\portmidi\pm_win\copy-dll.bat):
+        copy <...>\portmidi\pm_win\Debug\pm_dll.dll to:
+            <...>\portmidi\pm_test\latencyDebug\pm_dll.dll
+            <...>\portmidi\pm_test\midithreadDebug\pm_dll.dll
+            <...>\portmidi\pm_test\sysexDebug\pm_dll.dll
+            <...>\portmidi\pm_test\testDebug\pm_dll.dll
+            <...>\portmidi\pm_test\midithruDebug\pm_dll.dll
+        and copy <...>\portmidi\pm_win\Release\pm_dll.dll to:
+            <...>\portmidi\pm_test\latencyRelease\pm_dll.dll
+            <...>\portmidi\pm_test\midithreadRelease\pm_dll.dll
+            <...>\portmidi\pm_test\sysexRelease\pm_dll.dll
+            <...>\portmidi\pm_test\testRelease\pm_dll.dll
+            <...>\portmidi\pm_test\midithruRelease\pm_dll.dll
+    each time you rebuild the pm_dll project, these copies must be redone!
+
+    Since Windows will look in the executable directory for DLLs, we 
+    recommend that you always install a copy of pm_dll.dll (either the
+    debug version or the release version) in the same directory as the
+    application using PortMidi. The release DLL is about 40KB. This will 
+    ensure that the application uses the correct DLL.
+
+10) run test project; use the menu that shows up from the command prompt to
     test that portMidi works on your system. tests include: 
 		- verify midi output works
 		- verify midi input works
+		- verify midi input w/midi thru works
 
-10) run other projects if you wish: sysex, latency, midithread, mm, 
-    qtest, midithru
-
-11) use pm_java/make.bat (run in a cmd window from pm_java) to compile
-    the java code.
-
-12) run pm_java/pmdefaults.bat (run in a cmd window from pm_java) to
-    run the PmDefaults program. This lets you select the default input
-    and output devices for PortMidi.
+11) run other projects if you wish: sysex, latency, midithread, mm, qtest
 
 ============================================================================
 TO CREATE YOUR OWN PORTMIDI CLIENT APPLICATION:
@@ -113,35 +119,43 @@ The easiest way is to start a new project w/in the portMidi workspace:
       in the next step)
 	- Click OK
 	- Select "An Empty Project" and click Finish
-	
-	In Visual C++ 2005 Express Edition, 
-	- File->New->Projects
-	- Location: <...>\portmidi\<yourProjectName>
-	- select Add to solution
-	- select CLR Empty project in CLR
-	- select Win32 Console Application in Win32
-	- select Empty project in General
-	
+
 2) Now this project will be the active project. Make it explicitly depend
    on PortMidi dll:
 	- Project->Dependencies
 	- Click pm_dll
 
-3) add whatever files you wish to add to your new project, using portMidi
+3) Important! in order to be able to use portMidi DLL from your new project
+   and set breakpoints,	copy following files from <...>\pm_dll\Debug into 
+   <...>\<yourProjectName>\Debug directory:
+		pm_dll.lib
+		pm_dll.dll
+    each time you rebuild pm_dll, these copies must be redone!
+
+4) add whatever files you wish to add to your new project, using portMidi
    calls as desired (see USING PORTMIDI at top of this readme)
 
-4) when you include portMidi files, do so like this:
-	- #include "..\pm_common\portmidi.h"
+5) when you include portMidi files, do so like this:
+	- #include "..\pm_dll\portmidi.h"
 	- etc.
 
-5) build and run your project
+6) build and run your project
 
 ============================================================================
 DESIGN NOTES
 ============================================================================
 
-PortMidi for Win32 exists as a simple static library,
+The DLL is used so that PortMidi can (usually) close open devices when the
+program terminates. Failure to close input devices under WinNT, Win2K, and
+probably later systems causes the OS to crash.
+
+This is accomplished with a .LIB/.DLL pair, linking to the .LIB
+in order to access functions in the .DLL. 
+
+PortMidi for Win32 exists as a simple library,
 with Win32-specific code in pmwin.c and MM-specific code in pmwinmm.c.
+pmwin.c uses a DLL in pmdll.c to call Pm_Terminate() when the program
+exits to make sure that all MIDI ports are closed.
 
 Orderly cleanup after errors are encountered is based on a fixed order of
 steps and state changes to reflect each step. Here's the order:
@@ -157,8 +171,10 @@ To open input:
         set descriptor field of PmInternal structure
         - open device
         set handle field of midiwinmm_type structure
-        - allocate buffers
-        - start device
+        - allocate buffer 1 for sysex
+        buffer is added to input port
+        - allocate buffer 2 for sysex
+        buffer is added to input port
         - return
     - return
 
@@ -271,15 +287,5 @@ part of PortMidi is allowed to directly copy sysex bytes to
 "fill_base[*fill_offset_ptr++]" until *fill_offset_ptr reaches
 fill_length. See the code for details.
 
------------
-
-Additional notes on using VS 2005 (maybe this is obsolete now?):
-
-1) Make sure "Configuration: All Configurations" is selected in all of the following Properties modifications!
-
-2) In my case the project defaulted to compiling all .c files with the C++ compiler, which was disastrous. I had to go to set Properties for each file, to wit: Expand Configuration Properties, Expand C/C++, Select Advanced, set the Compile As popup to Compile as C Code (/TC). (For better or worse, the project I inherited has a bunch of .c files that rely on C++ features, so I couldn't reliably set this the project properties level.)
-
-3) While you're there, make sure that the C/C++ -> General -> "Compile with Common Language Runtime support" is set to "No Common Language Runtime support" (the C compiler *can't* support CLR, but VS won't do anything useful like automatically set the two options to match)-.
-
-4) I never got VS precompiled header thing to work sensibly, so I took the path of least resistance and turned PCH's off for all my files. Properties -> Configuration Properties -> C/C++ -> Precompiled Headers -> Create/Use Precompiled Header popup set to "Not Using Precompiled Headers". The compiler is reasonably fast even if it has to parse all the header files, so unless someone wants to explain VS's PCHs to me, the hell with it, I say.
 
+  
\ No newline at end of file
diff --git a/portmidi/pm_win/pmwin.c b/portmidi/pm_win/pmwin.c
index 5b4dec63f..716b68fa5 100644
--- a/portmidi/pm_win/pmwin.c
+++ b/portmidi/pm_win/pmwin.c
@@ -9,7 +9,6 @@
    be separate from the main portmidi.c file because it is system
    dependent, and it is separate from, say, pmwinmm.c, because it
    might need to register devices for winmm, directx, and others.
-
  */
 
 #include "stdlib.h"
@@ -17,10 +16,12 @@
 #include "pmutil.h"
 #include "pminternal.h"
 #include "pmwinmm.h"
+#ifdef USE_DLL_FOR_CLEANUP
+#include "pmdll.h" /* used to close ports on exit */
+#endif
 #ifdef DEBUG
 #include "stdio.h"
 #endif
-#include <windows.h>
 
 /* pm_exit is called when the program exits.
    It calls pm_term to make sure PortMidi is properly closed.
@@ -44,9 +45,20 @@ static void pm_exit(void) {
 /* pm_init is the windows-dependent initialization.*/
 void pm_init(void)
 {
+#ifdef USE_DLL_FOR_CLEANUP
+    /* we were hoping a DLL could offer more robust cleanup after errors,
+       but the DLL does not seem to run after crashes. Thus, the atexit()
+       mechanism is just as powerful, and simpler to implement.
+     */
+    pm_set_close_function(pm_exit);
+#ifdef DEBUG
+    printf("registered pm_term with cleanup DLL\n");
+#endif
+#else
     atexit(pm_exit);
 #ifdef DEBUG
     printf("registered pm_exit with atexit()\n");
+#endif
 #endif
     pm_winmm_init();
     /* initialize other APIs (DirectX?) here */
@@ -58,77 +70,37 @@ void pm_term(void) {
 }
 
 
-static PmDeviceID pm_get_default_device_id(int is_input, char *key) {
-    HKEY hkey;
-#define PATTERN_MAX 256
-    char pattern[PATTERN_MAX];
-    long pattern_max = PATTERN_MAX;
-    DWORD dwType;
-    /* Find first input or device -- this is the default. */
-    PmDeviceID id = pmNoDevice;
-    int i, j;
+PmDeviceID Pm_GetDefaultInputDeviceID() {
+    /* This routine should check the environment and the registry
+       as specified in portmidi.h, but for now, it just returns
+       the first device of the proper input/output flavor.
+     */
+    int i;
     Pm_Initialize(); /* make sure descriptors exist! */
     for (i = 0; i < pm_descriptor_index; i++) {
-        if (descriptors[i].pub.input == is_input) {
-            id = i;
-            break;
+        if (descriptors[i].pub.input) {
+            return i;
         }
     }
-    /* Look in registry for a default device name pattern. */
-    if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey) != 
-        ERROR_SUCCESS) {
-        return id;
-    }
-    if (RegOpenKeyEx(hkey, "JavaSoft", 0, KEY_READ, &hkey) !=
-        ERROR_SUCCESS) {
-        return id;
-    }
-    if (RegOpenKeyEx(hkey, "Prefs", 0, KEY_READ, &hkey) !=
-        ERROR_SUCCESS) {
-        return id;
-    }
-    if (RegOpenKeyEx(hkey, "/Port/Midi", 0, KEY_READ, &hkey) !=
-        ERROR_SUCCESS) {
-        return id;
-    }
-    if (RegQueryValueEx(hkey, key, NULL, &dwType, pattern, &pattern_max) != 
-	ERROR_SUCCESS) {
-        return id;
-    }
-
-    /* decode pattern: upper case encoded with "/" prefix */
-    i = j = 0;
-    while (pattern[i]) {
-        if (pattern[i] == '/' && pattern[i + 1]) {
-            pattern[j++] = toupper(pattern[++i]);
-	} else {
-            pattern[j++] = tolower(pattern[i]);
-	}
-        i++;
-    }
-    pattern[j] = 0; /* end of string */
-
-    /* now pattern is the string from the registry; search for match */
-    i = pm_find_default_device(pattern, is_input);
-    if (i != pmNoDevice) {
-        id = i;
-    }
-    return id;
+    return pmNoDevice;
 }
 
-
-PmDeviceID Pm_GetDefaultInputDeviceID() {
-    return pm_get_default_device_id(TRUE, 
-           "/P/M_/R/E/C/O/M/M/E/N/D/E/D_/I/N/P/U/T_/D/E/V/I/C/E");
-}
-
-
 PmDeviceID Pm_GetDefaultOutputDeviceID() {
-  return pm_get_default_device_id(FALSE,
-          "/P/M_/R/E/C/O/M/M/E/N/D/E/D_/O/U/T/P/U/T_/D/E/V/I/C/E");
+    /* This routine should check the environment and the registry
+       as specified in portmidi.h, but for now, it just returns
+       the first device of the proper input/output flavor.
+     */
+    int i;
+    Pm_Initialize(); /* make sure descriptors exist! */
+    for (i = 0; i < pm_descriptor_index; i++) {
+        if (descriptors[i].pub.output) {
+            return i;
+        }
+    }
+    return pmNoDevice;
+    return 0;
 }
 
-
 #include "stdio.h" 
 
 void *pm_alloc(size_t s) {
@@ -140,4 +112,3 @@ void pm_free(void *ptr) {
     free(ptr); 
 }
 
-
diff --git a/portmidi/pm_win/pmwinmm.c b/portmidi/pm_win/pmwinmm.c
index 502e0592c..395b1134c 100644
--- a/portmidi/pm_win/pmwinmm.c
+++ b/portmidi/pm_win/pmwinmm.c
@@ -1,23 +1,18 @@
 /* pmwinmm.c -- system specific definitions */
 
-#ifdef _MSC_VER
- #pragma warning(disable: 4133) // stop warnings about implicit typecasts
-#endif
-
-#ifndef _WIN32_WINNT
-    /* without this define, InitializeCriticalSectionAndSpinCount is 
-     * undefined. This version level means "Windows 2000 and higher" 
-     */
-    #define _WIN32_WINNT 0x0500
-#endif
+/* without this define, InitializeCriticalSectionAndSpinCount is undefined */
+/* this version level means "Windows 2000 and higher" */
+#define _WIN32_WINNT 0x0500
 
 #include "windows.h"
 #include "mmsystem.h"
 #include "portmidi.h"
+#ifdef NEWBUFFER
 #include "pmutil.h"
+#endif
 #include "pminternal.h"
 #include "pmwinmm.h"
-#include <string.h>
+#include "string.h"
 #include "porttime.h"
 
 /* asserts used to verify portMidi code logic is sound; later may want
@@ -163,8 +158,8 @@ static void pm_winmm_general_inputs()
     UINT i;
     WORD wRtn;
     midi_num_inputs = midiInGetNumDevs();
-    midi_in_caps = (MIDIINCAPS *) pm_alloc(sizeof(MIDIINCAPS) * 
-                                           midi_num_inputs);
+    midi_in_caps = pm_alloc(sizeof(MIDIINCAPS) * midi_num_inputs);
+
     if (midi_in_caps == NULL) {
         /* if you can't open a particular system-level midi interface
          * (such as winmm), we just consider that system or API to be
@@ -580,12 +575,11 @@ static PmError winmm_in_open(PmInternal *midi, void *driverInfo)
      */
     InitializeCriticalSectionAndSpinCount(&m->lock, 4000);
     /* open device */
-    pm_hosterror = midiInOpen(
-	    &(m->handle.in),  /* input device handle */
-	    dwDevice,  /* device ID */
-	    (DWORD_PTR) winmm_in_callback,  /* callback address */
-	    (DWORD_PTR) midi,  /* callback instance data */
-	    CALLBACK_FUNCTION); /* callback is a procedure */
+    pm_hosterror = midiInOpen(&(m->handle.in),  /* input device handle */
+                              dwDevice,  /* device ID */
+                              (DWORD) winmm_in_callback,  /* callback address */
+                              (DWORD) midi,  /* callback instance data */
+                              CALLBACK_FUNCTION); /* callback is a procedure */
     if (pm_hosterror) goto free_descriptor;
 
     if (num_input_buffers < MIN_INPUT_BUFFERS)
@@ -674,29 +668,22 @@ static void FAR PASCAL winmm_in_callback(
     PmInternal *midi = (PmInternal *) dwInstance;
     midiwinmm_type m = (midiwinmm_type) midi->descriptor;
 
-    /* NOTE: we do not just EnterCriticalSection() here because an
-     * MIM_CLOSE message arrives when the port is closed, but then
-     * the m->lock has been destroyed.
+    /* if this callback is reentered with data, we're in trouble. It's hard
+     * to imagine that Microsoft would allow callbacks to be reentrant --
+     * isn't the model that this is like a hardware interrupt? -- but I've
+     * seen reentrant behavior using a debugger, so it happens.
      */
+    EnterCriticalSection(&m->lock);
 
     switch (wMsg) {
     case MIM_DATA: {
-        /* if this callback is reentered with data, we're in trouble. 
-         * It's hard to imagine that Microsoft would allow callbacks 
-         * to be reentrant -- isn't the model that this is like a 
-         * hardware interrupt? -- but I've seen reentrant behavior 
-         * using a debugger, so it happens.
-         */
-        long new_driver_time;
-        EnterCriticalSection(&m->lock);
-
         /* dwParam1 is MIDI data received, packed into DWORD w/ 1st byte of
                 message LOB;
            dwParam2 is time message received by input device driver, specified
             in [ms] from when midiInStart called.
            each message is expanded to include the status byte */
 
-        new_driver_time = dwParam2;
+        long new_driver_time = dwParam2;
 
         if ((dwParam1 & 0x80) == 0) {
             /* not a status byte -- ignore it. This happened running the
@@ -712,16 +699,13 @@ static void FAR PASCAL winmm_in_callback(
             event.message = dwParam1;
             pm_read_short(midi, &event);
         }
-        LeaveCriticalSection(&m->lock);
         break;
     }
     case MIM_LONGDATA: {
         MIDIHDR *lpMidiHdr = (MIDIHDR *) dwParam1;
-        unsigned char *data = (unsigned char *) lpMidiHdr->lpData;
+        unsigned char *data = lpMidiHdr->lpData;
         unsigned int processed = 0;
         int remaining = lpMidiHdr->dwBytesRecorded;
-
-        EnterCriticalSection(&m->lock);
         /* printf("midi_in_callback -- lpMidiHdr %x, %d bytes, %2x...\n", 
                 lpMidiHdr, lpMidiHdr->dwBytesRecorded, *data); */
         if (midi->time_proc)
@@ -734,7 +718,38 @@ static void FAR PASCAL winmm_in_callback(
             remaining -= amt;
             processed += amt;
         }
-
+#ifdef DELETE_THIS
+        unsigned int i = 0;
+        long size = sizeof(MIDIHDR) + lpMidiHdr->dwBufferLength;
+
+        while (i < lpMidiHdr->dwBytesRecorded) {
+            /* optimization: if message_count == 0, we are on an (output)
+             * message boundary so we can transfer data directly to the
+             * queue
+             */
+            PmEvent event;
+            if (midi->sysex_message_count == 0 &&
+                !midi->flush &&
+                i <= lpMidiHdr->dwBytesRecorded - 4 &&
+                ((event.message = (((long) data[0]) | 
+                        (((long) data[1]) << 8) | (((long) data[2]) << 16) |
+                        (((long) data[3]) << 24))) &
+                 0x80808080) == 0) { /* all data, no status */
+                event.timestamp = dwParam2;
+                if (Pm_Enqueue(midi->queue, &event) == pmBufferOverflow) {
+                    midi->flush = TRUE;
+                }
+                i += 4;
+                data += 4;
+            /* non-optimized: process one byte at a time. This is used to 
+             * handle any embedded SYSEX or EOX bytes and to finish */
+            } else {
+                pm_read_byte(midi, *data, dwParam2);
+                data++;
+                i++;
+            }
+        }
+#endif
         /* when a device is closed, the pending MIM_LONGDATA buffers are
            returned to this callback with dwBytesRecorded == 0. In this
            case, we do not want to send them back to the interface (if
@@ -742,7 +757,6 @@ static void FAR PASCAL winmm_in_callback(
         if (lpMidiHdr->dwBytesRecorded > 0) {
             lpMidiHdr->dwBytesRecorded = 0;
             lpMidiHdr->dwFlags = 0;
-			
             /* note: no error checking -- can this actually fail? */
             assert(midiInPrepareHeader(hMidiIn, lpMidiHdr, 
                         sizeof(MIDIHDR)) == MMSYSERR_NOERROR);
@@ -753,10 +767,7 @@ static void FAR PASCAL winmm_in_callback(
              */
             assert(midiInAddBuffer(hMidiIn, lpMidiHdr, 
                         sizeof(MIDIHDR)) == MMSYSERR_NOERROR);
-            LeaveCriticalSection(&m->lock);
         } else {
-            midiInUnprepareHeader(hMidiIn,lpMidiHdr,sizeof(MIDIHDR));
-            LeaveCriticalSection(&m->lock);
             pm_free(lpMidiHdr);
         }
         break;
@@ -774,6 +785,7 @@ static void FAR PASCAL winmm_in_callback(
     default:
         break;
     }
+    LeaveCriticalSection(&m->lock);
 }
 
 /*
@@ -862,22 +874,20 @@ static PmError winmm_out_open(PmInternal *midi, void *driverInfo)
     /* open device */
     if (midi->latency == 0) {
         /* use simple midi out calls */
-        pm_hosterror = midiOutOpen(
-                (LPHMIDIOUT) & m->handle.out,  /* device Handle */
-		dwDevice,  /* device ID  */
-		/* note: same callback fn as for StreamOpen: */
-		(DWORD_PTR) winmm_streamout_callback, /* callback fn */
-		(DWORD_PTR) midi,  /* callback instance data */
-		CALLBACK_FUNCTION); /* callback type */
+        pm_hosterror = midiOutOpen((LPHMIDIOUT) & m->handle.out,  /* device Handle */
+                                   dwDevice,  /* device ID  */
+                                   /* note: same callback fn as for StreamOpen: */
+                                   (DWORD) winmm_streamout_callback, /* callback fn */
+                                   (DWORD) midi,  /* callback instance data */
+                                   CALLBACK_FUNCTION); /* callback type */
     } else {
         /* use stream-based midi output (schedulable in future) */
-        pm_hosterror = midiStreamOpen(
-	        &m->handle.stream,  /* device Handle */
-		(LPUINT) & dwDevice,  /* device ID pointer */
-		1,  /* reserved, must be 1 */
-		(DWORD_PTR) winmm_streamout_callback,
-		(DWORD_PTR) midi,  /* callback instance data */
-		CALLBACK_FUNCTION);
+        pm_hosterror = midiStreamOpen(&m->handle.stream,  /* device Handle */
+                                      (LPUINT) & dwDevice,  /* device ID pointer */
+                                      1,  /* reserved, must be 1 */
+                                      (DWORD) winmm_streamout_callback,
+                                      (DWORD) midi,  /* callback instance data */
+                                      CALLBACK_FUNCTION);
     }
     if (pm_hosterror != MMSYSERR_NOERROR) {
         goto free_descriptor;
@@ -1205,7 +1215,7 @@ static PmError winmm_write_byte(PmInternal *midi, unsigned char byte,
     if (!hdr) {
         m->hdr = hdr = get_free_output_buffer(midi);
         assert(hdr);
-        midi->fill_base = (unsigned char *) m->hdr->lpData;
+        midi->fill_base = m->hdr->lpData;
         midi->fill_offset_ptr = &(hdr->dwBytesRecorded);
         /* when buffer fills, Pm_WriteSysEx will revert to calling
          * pmwin_write_byte, which expect to have space, so leave
@@ -1309,12 +1319,10 @@ static void CALLBACK winmm_out_callback(HMIDIOUT hmo, UINT wMsg,
        buffers are free, so we need to do something to flag empty buffers if
        we leave them prepared
      */
-    /*
     printf("out_callback: hdr %x, wMsg %x, MOM_DONE %x\n", 
            hdr, wMsg, MOM_DONE);
-    */
     if (wMsg == MOM_DONE)
-        assert(midiOutUnprepareHeader(m->handle.out, hdr,
+    assert(midiOutUnprepareHeader(m->handle.out, hdr,
                         sizeof(MIDIHDR)) == MMSYSERR_NOERROR);
     /* notify waiting sender that a buffer is available */
     err = SetEvent(m->buffer_signal);
diff --git a/portmidi/porttime/porttime.h b/portmidi/porttime/porttime.h
index eff0f782e..029ea7779 100644
--- a/portmidi/porttime/porttime.h
+++ b/portmidi/porttime/porttime.h
@@ -13,11 +13,11 @@ extern "C" {
 
 
 typedef enum {
-    ptNoError = 0,         /* success */
-    ptHostError = -10000,  /* a system-specific error occurred */
-    ptAlreadyStarted,      /* cannot start timer because it is already started */
-    ptAlreadyStopped,      /* cannot stop timer because it is already stopped */
-    ptInsufficientMemory   /* memory could not be allocated */
+    ptNoError = 0,
+    ptHostError = -10000,
+    ptAlreadyStarted,
+    ptAlreadyStopped,
+    ptInsufficientMemory
 } PtError;
 
 
@@ -25,48 +25,12 @@ typedef long PtTimestamp;
 
 typedef void (PtCallback)( PtTimestamp timestamp, void *userData );
 
-/*
-    Pt_Start() starts a real-time service.
 
-    resolution is the timer resolution in ms. The time will advance every
-    resolution ms.
-
-    callback is a function pointer to be called every resolution ms.
-
-    userData is passed to callback as a parameter.
-
-    return value:
-    Upon success, returns ptNoError. See PtError for other values.
-*/
 PtError Pt_Start(int resolution, PtCallback *callback, void *userData);
-
-/*
-    Pt_Stop() stops the timer.
-
-    return value:
-    Upon success, returns ptNoError. See PtError for other values.
-*/
 PtError Pt_Stop();
-
-/*
-    Pt_Started() returns true iff the timer is running.
-*/
 int Pt_Started();
-
-/* 
-    Pt_Time() returns the current time in ms.
-*/
 PtTimestamp Pt_Time();
 
-/*
-    Pt_Sleep() pauses, allowing other threads to run.
-
-    duration is the length of the pause in ms. The true duration 
-    of the pause may be rounded to the nearest or next clock tick
-    as determined by resolution in Pt_Start().
-*/
-void Pt_Sleep(long duration);
-
 #ifdef __cplusplus
 }
 #endif
diff --git a/portmidi/porttime/ptlinux.c b/portmidi/porttime/ptlinux.c
index b43ca8b27..468575aa3 100644
--- a/portmidi/porttime/ptlinux.c
+++ b/portmidi/porttime/ptlinux.c
@@ -59,7 +59,7 @@ static void *Pt_CallbackProc(void *p)
     /* printf("pt_callback_proc_id %d, id %d\n", pt_callback_proc_id,
            parameters->id); */
     if (geteuid() == 0) setpriority(PRIO_PROCESS, 0, -20);
-    while (pt_callback_proc_id == parameters->id) {
+	while (pt_callback_proc_id == parameters->id) {
         /* wait for a multiple of resolution ms */
         struct timeval timeout;
         int delay = mytime++ * parameters->resolution - Pt_Time();
@@ -124,10 +124,4 @@ PtTimestamp Pt_Time()
 }
 
 
-void Pt_Sleep(long duration)
-{
-    usleep(duration * 1000);
-}
-
-
 
diff --git a/portmidi/porttime/ptmacosx_cf.c b/portmidi/porttime/ptmacosx_cf.c
index 09a8c6145..c0c22a32e 100644
--- a/portmidi/porttime/ptmacosx_cf.c
+++ b/portmidi/porttime/ptmacosx_cf.c
@@ -133,8 +133,3 @@ PtTimestamp Pt_Time()
     return (PtTimestamp) ((now - startTime) * 1000.0);
 }
 
-
-void Pt_Sleep(long duration)
-{
-    usleep(duration * 1000);
-}
diff --git a/portmidi/porttime/ptmacosx_mach.c b/portmidi/porttime/ptmacosx_mach.c
index f0fdcf96a..37d4318b7 100644
--- a/portmidi/porttime/ptmacosx_mach.c
+++ b/portmidi/porttime/ptmacosx_mach.c
@@ -8,7 +8,6 @@
 #import <mach/mach_error.h>
 #import <mach/mach_time.h>
 #import <mach/clock.h>
-#include <unistd.h>
 
 #include "porttime.h"
 #include "sys/time.h"
@@ -123,8 +122,3 @@ PtTimestamp Pt_Time()
     return (PtTimestamp)(nsec_time / NSEC_PER_MSEC);
 }
 
-
-void Pt_Sleep(long duration)
-{
-    usleep(duration * 1000);
-}
diff --git a/portmidi/porttime/ptwinmm.c b/portmidi/porttime/ptwinmm.c
index 581441586..bbfebb0ec 100644
--- a/portmidi/porttime/ptwinmm.c
+++ b/portmidi/porttime/ptwinmm.c
@@ -14,8 +14,8 @@ static long time_resolution;
 static MMRESULT timer_id;
 static PtCallback *time_callback;
 
-void CALLBACK winmm_time_callback(UINT uID, UINT uMsg, DWORD_PTR dwUser, 
-                                  DWORD_PTR dw1, DWORD_PTR dw2)
+void CALLBACK winmm_time_callback(UINT uID, UINT uMsg, DWORD dwUser, 
+                                  DWORD dw1, DWORD dw2)
 {
     (*time_callback)(Pt_Time(), (void *) dwUser);
 }
@@ -31,7 +31,7 @@ PtError Pt_Start(int resolution, PtCallback *callback, void *userData)
     time_callback = callback;
     if (callback) {
         timer_id = timeSetEvent(resolution, 1, winmm_time_callback, 
-            (DWORD_PTR) userData, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
+            (DWORD) userData, TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
         if (!timer_id) return ptHostError;
     }
     return ptNoError;
@@ -63,8 +63,3 @@ PtTimestamp Pt_Time()
     return timeGetTime() - time_offset;
 }
 
-
-void Pt_Sleep(long duration)
-{
-    Sleep(duration);
-}
diff --git a/src/aclocal.m4 b/src/aclocal.m4
new file mode 100644
index 000000000..88318d177
--- /dev/null
+++ b/src/aclocal.m4
@@ -0,0 +1,14 @@
+# generated automatically by aclocal 1.11 -*- Autoconf -*-
+
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005, 2006, 2007, 2008, 2009  Free Software Foundation, Inc.
+# 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.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
+# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE.
+
+m4_include([acinclude.m4])
diff --git a/src/config.h b/src/config.h
new file mode 100644
index 000000000..a8ffe9c58
--- /dev/null
+++ b/src/config.h
@@ -0,0 +1,226 @@
+/* config.h.  Generated from config.h.in by configure.  */
+/* config.h.in.  Generated from configure.in by autoheader.  */
+
+/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
+   systems. This function is required for `alloca.c' support on those systems.
+   */
+/* #undef CRAY_STACKSEG_END */
+
+/* Define to 1 if using `alloca.c'. */
+/* #undef C_ALLOCA */
+
+/* Define to 1 if you have `alloca', as a function or macro. */
+#define HAVE_ALLOCA 1
+
+/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
+   */
+#define HAVE_ALLOCA_H 1
+
+/* Define this to indicate the ${ATAN2F_DESCRIP} library */
+#define HAVE_ATAN2F 1
+
+/* Define to indicate the ${ATAN2F_DESCRIP} library version */
+#define HAVE_ATAN2F_VERSION /**/
+
+/* Define this to indicate the ${ATANF_DESCRIP} library */
+#define HAVE_ATANF 1
+
+/* Define to indicate the ${ATANF_DESCRIP} library version */
+#define HAVE_ATANF_VERSION /**/
+
+/* Define to 1 if you have the <bstring.h> header file. */
+/* #undef HAVE_BSTRING_H */
+
+/* Define this to indicate the ${COSF_DESCRIP} library */
+#define HAVE_COSF 1
+
+/* Define to indicate the ${COSF_DESCRIP} library version */
+#define HAVE_COSF_VERSION /**/
+
+/* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */
+/* #undef HAVE_DOPRNT */
+
+/* Define this to indicate the ${EXPF_DESCRIP} library */
+#define HAVE_EXPF 1
+
+/* Define to indicate the ${EXPF_DESCRIP} library version */
+#define HAVE_EXPF_VERSION /**/
+
+/* Define this to indicate the ${FABSF_DESCRIP} library */
+#define HAVE_FABSF 1
+
+/* Define to indicate the ${FABSF_DESCRIP} library version */
+#define HAVE_FABSF_VERSION /**/
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <io.h> header file. */
+/* #undef HAVE_IO_H */
+
+/* Define to 1 if you have the `tcl84' library (-ltcl84). */
+/* #undef HAVE_LIBTCL84 */
+
+/* Define to 1 if you have the `tcl85' library (-ltcl85). */
+/* #undef HAVE_LIBTCL85 */
+
+/* Define to 1 if you have the `tcl8.0' library (-ltcl8.0). */
+/* #undef HAVE_LIBTCL8_0 */
+
+/* Define to 1 if you have the `tcl8.2' library (-ltcl8.2). */
+/* #undef HAVE_LIBTCL8_2 */
+
+/* Define to 1 if you have the `tcl8.3' library (-ltcl8.3). */
+/* #undef HAVE_LIBTCL8_3 */
+
+/* Define to 1 if you have the `tcl8.4' library (-ltcl8.4). */
+/* #undef HAVE_LIBTCL8_4 */
+
+/* Define to 1 if you have the `tcl8.5' library (-ltcl8.5). */
+#define HAVE_LIBTCL8_5 1
+
+/* Define to 1 if you have the `tk84' library (-ltk84). */
+/* #undef HAVE_LIBTK84 */
+
+/* Define to 1 if you have the `tk85' library (-ltk85). */
+/* #undef HAVE_LIBTK85 */
+
+/* Define to 1 if you have the `tk8.0' library (-ltk8.0). */
+/* #undef HAVE_LIBTK8_0 */
+
+/* Define to 1 if you have the `tk8.2' library (-ltk8.2). */
+/* #undef HAVE_LIBTK8_2 */
+
+/* Define to 1 if you have the `tk8.3' library (-ltk8.3). */
+/* #undef HAVE_LIBTK8_3 */
+
+/* Define to 1 if you have the `tk8.4' library (-ltk8.4). */
+/* #undef HAVE_LIBTK8_4 */
+
+/* Define to 1 if you have the `tk8.5' library (-ltk8.5). */
+#define HAVE_LIBTK8_5 1
+
+/* Define to 1 if you have the <limits.h> header file. */
+#define HAVE_LIMITS_H 1
+
+/* Define this to indicate the ${LOGF_DESCRIP} library */
+#define HAVE_LOGF 1
+
+/* Define to indicate the ${LOGF_DESCRIP} library version */
+#define HAVE_LOGF_VERSION /**/
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#define HAVE_MALLOC_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define this to indicate the ${POWF_DESCRIP} library */
+#define HAVE_POWF 1
+
+/* Define to indicate the ${POWF_DESCRIP} library version */
+#define HAVE_POWF_VERSION /**/
+
+/* Define to 1 if you have the `select' function. */
+#define HAVE_SELECT 1
+
+/* Define this to indicate the ${SINF_DESCRIP} library */
+#define HAVE_SINF 1
+
+/* Define to indicate the ${SINF_DESCRIP} library version */
+#define HAVE_SINF_VERSION /**/
+
+/* Define to 1 if you have the `socket' function. */
+#define HAVE_SOCKET 1
+
+/* Define this to indicate the ${SQRTF_DESCRIP} library */
+#define HAVE_SQRTF 1
+
+/* Define to indicate the ${SQRTF_DESCRIP} library version */
+#define HAVE_SQRTF_VERSION /**/
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the `strerror' function. */
+#define HAVE_STRERROR 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `vprintf' function. */
+#define HAVE_VPRINTF 1
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME ""
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING ""
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION ""
+
+/* Define as the return type of signal handlers (`int' or `void'). */
+#define RETSIGTYPE void
+
+/* If using the C implementation of alloca, define if you know the
+   direction of stack growth for your system; otherwise it will be
+   automatically deduced at runtime.
+	STACK_DIRECTION > 0 => grows toward higher addresses
+	STACK_DIRECTION < 0 => grows toward lower addresses
+	STACK_DIRECTION = 0 => direction of growth unknown */
+/* #undef STACK_DIRECTION */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define TIME_WITH_SYS_TIME 1
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#define _FILE_OFFSET_BITS 64
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
diff --git a/src/configure b/src/configure
new file mode 100755
index 000000000..0ccf95f94
--- /dev/null
+++ b/src/configure
@@ -0,0 +1,7980 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.64.
+#
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software
+# Foundation, Inc.
+#
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # 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
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+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
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+if test "x$CONFIG_SHELL" = x; then
+  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # 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
+fi
+"
+  as_required="as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=0
+as_fn_success || { exitcode=1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+
+else
+  exitcode=1; echo positional parameters were not saved.
+fi
+test x\$exitcode = x0 || exit 1"
+  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
+  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
+test \$(( 1 + 1 )) = 2 || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+as_found=false
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  as_found=:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  CONFIG_SHELL=$as_shell as_have_required=yes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=false
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi; }
+IFS=$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" != x; then :
+  # We cannot yet assume a decent shell, so we have to provide a
+	# neutralization value for shells without unset; and this also
+	# works around shells that cannot unset nonexistent variables.
+	BASH_ENV=/dev/null
+	ENV=/dev/null
+	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+	export CONFIG_SHELL
+	exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+    if test x$as_have_required = xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} = xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+  else
+    $as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
+$0: including any error possibly output before this
+$0: message. Then install a modern shell, or manually run
+$0: the script under such a shell if you do have one."
+  fi
+  exit 1
+fi
+fi
+fi
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error ERROR [LINENO LOG_FD]
+# ---------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with status $?, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$?; test $as_status -eq 0 && as_status=1
+  if test "$3"; then
+    as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3
+  fi
+  $as_echo "$as_me: error: $1" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+
+  as_lineno_1=$LINENO as_lineno_1a=$LINENO
+  as_lineno_2=$LINENO as_lineno_2a=$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -p'
+  fi
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 7<&0 </dev/null 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+
+# Identity of this package.
+PACKAGE_NAME=
+PACKAGE_TARNAME=
+PACKAGE_VERSION=
+PACKAGE_STRING=
+PACKAGE_BUGREPORT=
+PACKAGE_URL=
+
+ac_unique_file="d_arithmetic.c"
+# Factoring default headers for most tests.
+ac_includes_default="\
+#include <stdio.h>
+#ifdef HAVE_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+# include <sys/stat.h>
+#endif
+#ifdef STDC_HEADERS
+# include <stdlib.h>
+# include <stddef.h>
+#else
+# ifdef HAVE_STDLIB_H
+#  include <stdlib.h>
+# endif
+#endif
+#ifdef HAVE_STRING_H
+# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
+#  include <memory.h>
+# endif
+# include <string.h>
+#endif
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif
+#ifdef HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+#ifdef HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#ifdef HAVE_UNISTD_H
+# include <unistd.h>
+#endif"
+
+ac_subst_vars='LTLIBOBJS
+LIBOBJS
+ALLOCA
+EGREP
+GREP
+CPP
+SET_MAKE
+INSTALL_DATA
+INSTALL_SCRIPT
+INSTALL_PROGRAM
+OBJEXT
+EXEEXT
+ac_ct_CC
+LDFLAGS
+CFLAGS
+CC
+PDEXEC
+GUISRC
+ASIOSRC
+EXTERNTARGET
+OSNUMBER
+GUIFLAGS
+GUINAME
+STRIPFLAG
+TCLTK_FRAMEWORKS_PATH
+SYSSRC
+USE_DEBUG_CFLAGS
+EXT
+MORECFLAGS
+CPPFLAGS
+PDLIB
+tk
+fftw
+binarymode
+portmidi
+portaudio
+jack
+alsa
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
+PATH_SEPARATOR
+SHELL'
+ac_subst_files=''
+ac_user_opts='
+enable_option_checking
+enable_alsa
+enable_jack
+enable_portaudio
+enable_portmidi
+enable_debug
+enable_static
+enable_setuid
+enable_fftw
+enable_fat
+enable_largefile
+'
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP'
+
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+ac_unrecognized_opts=
+ac_unrecognized_sep=
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
+
+ac_prev=
+ac_dashdash=
+for ac_option
+do
+  # If the previous option needs an argument, assign it.
+  if test -n "$ac_prev"; then
+    eval $ac_prev=\$ac_option
+    ac_prev=
+    continue
+  fi
+
+  case $ac_option in
+  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *)	ac_optarg=yes ;;
+  esac
+
+  # Accept the important Cygnus configure options, so we can diagnose typos.
+
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
+
+  -bindir | --bindir | --bindi | --bind | --bin | --bi)
+    ac_prev=bindir ;;
+  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+    bindir=$ac_optarg ;;
+
+  -build | --build | --buil | --bui | --bu)
+    ac_prev=build_alias ;;
+  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+    build_alias=$ac_optarg ;;
+
+  -cache-file | --cache-file | --cache-fil | --cache-fi \
+  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+    ac_prev=cache_file ;;
+  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
+    ac_prev=datadir ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
+  -disable-* | --disable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
+
+  -enable-* | --enable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=\$ac_optarg ;;
+
+  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+  | --exec | --exe | --ex)
+    ac_prev=exec_prefix ;;
+  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+  | --exec=* | --exe=* | --ex=*)
+    exec_prefix=$ac_optarg ;;
+
+  -gas | --gas | --ga | --g)
+    # Obsolete; use --with-gas.
+    with_gas=yes ;;
+
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
+
+  -host | --host | --hos | --ho)
+    ac_prev=host_alias ;;
+  -host=* | --host=* | --hos=* | --ho=*)
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
+  -includedir | --includedir | --includedi | --included | --include \
+  | --includ | --inclu | --incl | --inc)
+    ac_prev=includedir ;;
+  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+  | --includ=* | --inclu=* | --incl=* | --inc=*)
+    includedir=$ac_optarg ;;
+
+  -infodir | --infodir | --infodi | --infod | --info | --inf)
+    ac_prev=infodir ;;
+  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+    infodir=$ac_optarg ;;
+
+  -libdir | --libdir | --libdi | --libd)
+    ac_prev=libdir ;;
+  -libdir=* | --libdir=* | --libdi=* | --libd=*)
+    libdir=$ac_optarg ;;
+
+  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+  | --libexe | --libex | --libe)
+    ac_prev=libexecdir ;;
+  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+  | --libexe=* | --libex=* | --libe=*)
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
+  -localstatedir | --localstatedir | --localstatedi | --localstated \
+  | --localstate | --localstat | --localsta | --localst | --locals)
+    ac_prev=localstatedir ;;
+  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
+
+  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+    ac_prev=mandir ;;
+  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+    mandir=$ac_optarg ;;
+
+  -nfp | --nfp | --nf)
+    # Obsolete; use --without-fp.
+    with_fp=no ;;
+
+  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+  | --no-cr | --no-c | -n)
+    no_create=yes ;;
+
+  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+    no_recursion=yes ;;
+
+  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+  | --oldin | --oldi | --old | --ol | --o)
+    ac_prev=oldincludedir ;;
+  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+    oldincludedir=$ac_optarg ;;
+
+  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+    ac_prev=prefix ;;
+  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+    prefix=$ac_optarg ;;
+
+  -program-prefix | --program-prefix | --program-prefi | --program-pref \
+  | --program-pre | --program-pr | --program-p)
+    ac_prev=program_prefix ;;
+  -program-prefix=* | --program-prefix=* | --program-prefi=* \
+  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+    program_prefix=$ac_optarg ;;
+
+  -program-suffix | --program-suffix | --program-suffi | --program-suff \
+  | --program-suf | --program-su | --program-s)
+    ac_prev=program_suffix ;;
+  -program-suffix=* | --program-suffix=* | --program-suffi=* \
+  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+    program_suffix=$ac_optarg ;;
+
+  -program-transform-name | --program-transform-name \
+  | --program-transform-nam | --program-transform-na \
+  | --program-transform-n | --program-transform- \
+  | --program-transform | --program-transfor \
+  | --program-transfo | --program-transf \
+  | --program-trans | --program-tran \
+  | --progr-tra | --program-tr | --program-t)
+    ac_prev=program_transform_name ;;
+  -program-transform-name=* | --program-transform-name=* \
+  | --program-transform-nam=* | --program-transform-na=* \
+  | --program-transform-n=* | --program-transform-=* \
+  | --program-transform=* | --program-transfor=* \
+  | --program-transfo=* | --program-transf=* \
+  | --program-trans=* | --program-tran=* \
+  | --progr-tra=* | --program-tr=* | --program-t=*)
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil)
+    silent=yes ;;
+
+  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+    ac_prev=sbindir ;;
+  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+  | --sbi=* | --sb=*)
+    sbindir=$ac_optarg ;;
+
+  -sharedstatedir | --sharedstatedir | --sharedstatedi \
+  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+  | --sharedst | --shareds | --shared | --share | --shar \
+  | --sha | --sh)
+    ac_prev=sharedstatedir ;;
+  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+  | --sha=* | --sh=*)
+    sharedstatedir=$ac_optarg ;;
+
+  -site | --site | --sit)
+    ac_prev=site ;;
+  -site=* | --site=* | --sit=*)
+    site=$ac_optarg ;;
+
+  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+    ac_prev=srcdir ;;
+  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+    srcdir=$ac_optarg ;;
+
+  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+  | --syscon | --sysco | --sysc | --sys | --sy)
+    ac_prev=sysconfdir ;;
+  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+    sysconfdir=$ac_optarg ;;
+
+  -target | --target | --targe | --targ | --tar | --ta | --t)
+    ac_prev=target_alias ;;
+  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+    target_alias=$ac_optarg ;;
+
+  -v | -verbose | --verbose | --verbos | --verbo | --verb)
+    verbose=yes ;;
+
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
+
+  -with-* | --with-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=\$ac_optarg ;;
+
+  -without-* | --without-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=no ;;
+
+  --x)
+    # Obsolete; use --with-x.
+    with_x=yes ;;
+
+  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+  | --x-incl | --x-inc | --x-in | --x-i)
+    ac_prev=x_includes ;;
+  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+    x_includes=$ac_optarg ;;
+
+  -x-libraries | --x-libraries | --x-librarie | --x-librari \
+  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+    ac_prev=x_libraries ;;
+  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+    x_libraries=$ac_optarg ;;
+
+  -*) as_fn_error "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information."
+    ;;
+
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error "invalid variable name: \`$ac_envvar'" ;;
+    esac
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
+  *)
+    # FIXME: should be removed in autoconf 3.0.
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
+    ;;
+
+  esac
+done
+
+if test -n "$ac_prev"; then
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  as_fn_error "missing argument to $ac_option"
+fi
+
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
+  esac
+fi
+
+# Check all directory arguments for consistency.
+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
+do
+  eval ac_val=\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  as_fn_error "expected an absolute directory name for --$ac_var: $ac_val"
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+    $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used." >&2
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  as_fn_error "working directory cannot be determined"
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  as_fn_error "pwd does not report name of working directory"
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+  ac_srcdir_defaulted=yes
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  srcdir=$ac_confdir
+  if test ! -r "$srcdir/$ac_unique_file"; then
+    srcdir=..
+  fi
+else
+  ac_srcdir_defaulted=no
+fi
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  as_fn_error "cannot find sources ($ac_unique_file) in $srcdir"
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg"
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+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 this package to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+                          [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+                          [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR            user executables [EPREFIX/bin]
+  --sbindir=DIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR        program executables [EPREFIX/libexec]
+  --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]
+  --libdir=DIR            object code libraries [EPREFIX/lib]
+  --includedir=DIR        C header files [PREFIX/include]
+  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
+  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR           info documentation [DATAROOTDIR/info]
+  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR            man documentation [DATAROOTDIR/man]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR           html documentation [DOCDIR]
+  --dvidir=DIR            dvi documentation [DOCDIR]
+  --pdfdir=DIR            pdf documentation [DOCDIR]
+  --psdir=DIR             ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+
+  cat <<\_ACEOF
+
+Optional Features:
+  --disable-option-checking  ignore unrecognized --enable/--with options
+  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
+  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
+  --enable-alsa           alsa audio driver
+  --enable-jack           jack audio server
+  --enable-portaudio      portaudio
+  --enable-portmidi       portmidi
+  --enable-debug          debugging support
+  --enable-static         link statically
+  --enable-setuid         install as setuid (linux)
+  --enable-fftw           use FFTW package
+  --disable-fat    build fat binary on Mac OS X
+  --disable-largefile     omit support for large files
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    C/C++/Objective C preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+Report bugs to the package provider.
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
+      continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.64
+
+Copyright (C) 2009 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
+
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+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_compile") 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; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; 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; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  return $ac_retval
+
+} # 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; } >/dev/null && {
+	 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; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  return $ac_retval
+
+} # ac_fn_c_try_cpp
+
+# ac_fn_c_check_type LINENO TYPE VAR INCLUDES
+# -------------------------------------------
+# Tests whether TYPE exists after having included INCLUDES, setting cache
+# variable VAR accordingly.
+ac_fn_c_check_type ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  eval "$3=no"
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+int
+main ()
+{
+if (sizeof ($2))
+	 return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+int
+main ()
+{
+if (sizeof (($2)))
+	    return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  eval "$3=yes"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+
+} # ac_fn_c_check_type
+
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_link"
+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_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
+  { { 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_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  return $ac_retval
+
+} # ac_fn_c_try_run
+
+# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists and can be compiled using the include files in
+# INCLUDES, setting the cache variable VAR accordingly.
+ac_fn_c_check_header_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+
+} # ac_fn_c_check_header_compile
+
+# 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 { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; 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.$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;}
+    ;;
+esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; 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; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+
+} # ac_fn_c_check_header_mongrel
+
+# ac_fn_c_try_link LINENO
+# -----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_link ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try="$ac_link"
+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_link") 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; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 $as_test_x conftest$ac_exeext
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the actions.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  return $ac_retval
+
+} # ac_fn_c_try_link
+
+# ac_fn_c_check_func LINENO FUNC VAR
+# ----------------------------------
+# Tests whether FUNC exists, setting the cache variable VAR accordingly
+ac_fn_c_check_func ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define $2 innocuous_$2
+
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char $2 (); below.
+    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+    <limits.h> exists even on freestanding compilers.  */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $2
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char $2 ();
+/* The GNU C library defines this for functions which it implements
+    to always fail with ENOSYS.  Some functions are actually named
+    something starting with __ and the normal name is an alias.  */
+#if defined __stub_$2 || defined __stub___$2
+choke me
+#endif
+
+int
+main ()
+{
+return $2 ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+
+} # ac_fn_c_check_func
+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 $as_me, which was
+generated by GNU Autoconf 2.64.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    $as_echo "PATH: $as_dir"
+  done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
+    2)
+      as_fn_append ac_configure_args1 " '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      as_fn_append ac_configure_args " '$ac_arg'"
+      ;;
+    esac
+  done
+done
+{ ac_configure_args0=; unset ac_configure_args0;}
+{ ac_configure_args1=; unset ac_configure_args1;}
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      $as_echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      cat <<\_ASBOX
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
+_ASBOX
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	$as_echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+$as_echo "/* confdefs.h */" > confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=NONE
+ac_site_file2=NONE
+if test -n "$CONFIG_SITE"; then
+  ac_site_file1=$CONFIG_SITE
+elif test "x$prefix" != xNONE; then
+  ac_site_file1=$prefix/share/config.site
+  ac_site_file2=$prefix/etc/config.site
+else
+  ac_site_file1=$ac_default_prefix/share/config.site
+  ac_site_file2=$ac_default_prefix/etc/config.site
+fi
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" = xNONE && continue
+  if test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
+    . "$ac_site_file"
+  fi
+done
+
+if test -r "$cache_file"; then
+  # Some versions of bash will fail to source /dev/null (special
+  # files actually), so we avoid doing that.
+  if test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=`echo x $ac_old_val`
+	ac_new_val_w=`echo x $ac_new_val`
+	if test "$ac_old_val_w" != "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	  ac_cache_corrupted=:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+	  eval $ac_var=\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
+fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
+
+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
+
+
+
+ac_config_headers="$ac_config_headers config.h"
+
+
+alsa=yes
+
+jack=no
+
+portaudio=no
+
+portmidi=no
+
+binarymode=-m755
+
+fftw=no
+
+tk=yes
+
+
+
+
+
+USE_DEBUG_CFLAGS=no
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# Check whether --enable-alsa was given.
+if test "${enable_alsa+set}" = set; then :
+  enableval=$enable_alsa; alsa=$enableval
+fi
+
+# Check whether --enable-jack was given.
+if test "${enable_jack+set}" = set; then :
+  enableval=$enable_jack; jack=$enableval
+fi
+
+# Check whether --enable-portaudio was given.
+if test "${enable_portaudio+set}" = set; then :
+  enableval=$enable_portaudio; portaudio=$enableval
+fi
+
+# Check whether --enable-portmidi was given.
+if test "${enable_portmidi+set}" = set; then :
+  enableval=$enable_portmidi; portmidi=$enableval
+fi
+
+# Check whether --enable-debug was given.
+if test "${enable_debug+set}" = set; then :
+  enableval=$enable_debug; USE_DEBUG_CFLAGS=$enableval
+fi
+
+# Check whether --enable-static was given.
+if test "${enable_static+set}" = set; then :
+  enableval=$enable_static; static=$enableval
+fi
+
+# Check whether --enable-setuid was given.
+if test "${enable_setuid+set}" = set; then :
+  enableval=$enable_setuid; setuid=$enableval
+fi
+
+# Check whether --enable-fftw was given.
+if test "${enable_fftw+set}" = set; then :
+  enableval=$enable_fftw; fftw=$enableval
+fi
+
+# Check whether --enable-fat was given.
+if test "${enable_fat+set}" = set; then :
+  enableval=$enable_fat; fat=$enableval
+else
+  fat="yes"
+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
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # 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 { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $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
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # 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 { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $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
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  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
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # 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 { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $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
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+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 { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $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
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$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 test "${ac_cv_prog_CC+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # 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 { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="$ac_tool_prefix$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
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+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 test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # 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 { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="$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
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  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
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "no acceptable C compiler found in \$PATH
+See \`config.log' for more details." "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+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_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    rm -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f = fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) != 0;
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out conftest.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try="$ac_link_default"
+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_link_default") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
+if test -z "$ac_file"; then :
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+{ as_fn_set_status 77
+as_fn_error "C compiler cannot create executables
+See \`config.log' for more details." "$LINENO" 5; }; }
+fi
+ac_exeext=$ac_cv_exeext
+
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+# If not cross compiling, check that we can run a simple program.
+if test "$cross_compiling" != yes; then
+  if { ac_try='./$ac_file'
+  { { 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_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    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 "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out conftest.out
+ac_clean_files=$ac_clean_files_save
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try="$ac_link"
+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_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+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 "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." "$LINENO" 5; }
+fi
+rm -f conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if test "${ac_cv_objext+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { { ac_try="$ac_compile"
+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_compile") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." "$LINENO" 5; }
+fi
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if test "${ac_cv_c_compiler_gnu+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if test "${ac_cv_prog_cc_g+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if test "${ac_cv_prog_cc_c89+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+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
+
+ac_aux_dir=
+for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
+  for ac_t in install-sh install.sh shtool; do
+    if test -f "$ac_dir/$ac_t"; then
+      ac_aux_dir=$ac_dir
+      ac_install_sh="$ac_aux_dir/$ac_t -c"
+      break 2
+    fi
+  done
+done
+if test -z "$ac_aux_dir"; then
+  as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5
+fi
+
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
+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.
+
+
+# Find a good install program.  We prefer a C program (faster),
+# so one script is as good as another.  But avoid the broken or
+# incompatible versions:
+# SysV /etc/install, /usr/sbin/install
+# SunOS /usr/etc/install
+# IRIX /sbin/install
+# AIX /bin/install
+# AmigaOS /C/install, which installs bootblocks on floppy discs
+# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
+# AFS /usr/afsws/bin/install, which mishandles nonexistent args
+# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
+# OS/2's system install, which has a completely different semantic
+# ./install, which can be erroneously created by make from ./install.sh.
+# Reject install programs that cannot install multiple files.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5
+$as_echo_n "checking for a BSD-compatible install... " >&6; }
+if test -z "$INSTALL"; then
+if test "${ac_cv_path_install+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    # Account for people who put trailing slashes in PATH elements.
+case $as_dir/ in #((
+  ./ | .// | /[cC]/* | \
+  /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
+  ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \
+  /usr/ucb/* ) ;;
+  *)
+    # OSF1 and SCO ODT 3.0 have their own names for install.
+    # Don't use installbsd from OSF since it installs stuff as root
+    # by default.
+    for ac_prog in ginstall scoinst install; do
+      for ac_exec_ext in '' $ac_executable_extensions; do
+	if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then
+	  if test $ac_prog = install &&
+	    grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+	    # AIX install.  It has an incompatible calling convention.
+	    :
+	  elif test $ac_prog = install &&
+	    grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
+	    # program-specific install script used by HP pwplus--don't use.
+	    :
+	  else
+	    rm -rf conftest.one conftest.two conftest.dir
+	    echo one > conftest.one
+	    echo two > conftest.two
+	    mkdir conftest.dir
+	    if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" &&
+	      test -s conftest.one && test -s conftest.two &&
+	      test -s conftest.dir/conftest.one &&
+	      test -s conftest.dir/conftest.two
+	    then
+	      ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
+	      break 3
+	    fi
+	  fi
+	fi
+      done
+    done
+    ;;
+esac
+
+  done
+IFS=$as_save_IFS
+
+rm -rf conftest.one conftest.two conftest.dir
+
+fi
+  if test "${ac_cv_path_install+set}" = set; then
+    INSTALL=$ac_cv_path_install
+  else
+    # As a last resort, use the slow shell script.  Don't cache a
+    # value for INSTALL within a source directory, because that will
+    # break other packages using the cache if that directory is
+    # removed, or if the value is a relative name.
+    INSTALL=$ac_install_sh
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5
+$as_echo "$INSTALL" >&6; }
+
+# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
+# It thinks the first close brace ends the variable substitution.
+test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
+
+test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
+
+test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; }
+set x ${MAKE-make}
+ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat >conftest.make <<\_ACEOF
+SHELL = /bin/sh
+all:
+	@echo '@@@%%%=$(MAKE)=@@@%%%'
+_ACEOF
+# GNU make sometimes prints "make[1]: Entering...", which would confuse us.
+case `${MAKE-make} -f conftest.make 2>/dev/null` in
+  *@@@%%%=?*=@@@%%%*)
+    eval ac_cv_prog_make_${ac_make}_set=yes;;
+  *)
+    eval ac_cv_prog_make_${ac_make}_set=no;;
+esac
+rm -f conftest.make
+fi
+if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+  SET_MAKE=
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+  SET_MAKE="MAKE=${MAKE-make}"
+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 test "${ac_cv_prog_CPP+set}" = set; 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.$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.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f 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.$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.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f 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 an ANSI C-conforming const" >&5
+$as_echo_n "checking for an ANSI C-conforming const... " >&6; }
+if test "${ac_cv_c_const+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+/* FIXME: Include the comments suggested by Paul. */
+#ifndef __cplusplus
+  /* Ultrix mips cc rejects this.  */
+  typedef int charset[2];
+  const charset cs;
+  /* SunOS 4.1.1 cc rejects this.  */
+  char const *const *pcpcc;
+  char **ppc;
+  /* NEC SVR4.0.2 mips cc rejects this.  */
+  struct point {int x, y;};
+  static struct point const zero = {0,0};
+  /* AIX XL C 1.02.0.0 rejects this.
+     It does not let you subtract one const X* pointer from another in
+     an arm of an if-expression whose if-part is not a constant
+     expression */
+  const char *g = "string";
+  pcpcc = &g + (g ? g-g : 0);
+  /* HPUX 7.0 cc rejects these. */
+  ++pcpcc;
+  ppc = (char**) pcpcc;
+  pcpcc = (char const *const *) ppc;
+  { /* SCO 3.2v4 cc rejects this.  */
+    char *t;
+    char const *s = 0 ? (char *) 0 : (char const *) 0;
+
+    *t++ = 0;
+    if (s) return 0;
+  }
+  { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
+    int x[] = {25, 17};
+    const int *foo = &x[0];
+    ++foo;
+  }
+  { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+    typedef const int *iptr;
+    iptr p = 0;
+    ++p;
+  }
+  { /* AIX XL C 1.02.0.0 rejects this saying
+       "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+    struct s { int j; const int *ap[3]; };
+    struct s *b; b->j = 5;
+  }
+  { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+    const int foo = 10;
+    if (!foo) return 0;
+  }
+  return !cs[0] && !zero.x;
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_c_const=yes
+else
+  ac_cv_c_const=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5
+$as_echo "$ac_cv_c_const" >&6; }
+if test $ac_cv_c_const = no; then
+
+$as_echo "#define const /**/" >>confdefs.h
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
+$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
+if test "${ac_cv_path_GREP+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$GREP"; then
+  ac_path_GREP_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$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in grep ggrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue
+# Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_GREP=$GREP
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+$as_echo "$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+$as_echo_n "checking for egrep... " >&6; }
+if test "${ac_cv_path_EGREP+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     if test -z "$EGREP"; then
+  ac_path_EGREP_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$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in egrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+      { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue
+# Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_EGREP=$EGREP
+fi
+
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+$as_echo "$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if test "${ac_cv_header_stdc+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
+# On IRIX 5.3, sys/types and inttypes.h are conflicting.
+for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
+		  inttypes.h stdint.h unistd.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
+"
+eval as_val=\$$as_ac_Header
+   if test "x$as_val" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default"
+if test "x$ac_cv_type_pid_t" = x""yes; then :
+
+else
+
+cat >>confdefs.h <<_ACEOF
+#define pid_t int
+_ACEOF
+
+fi
+
+ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default"
+if test "x$ac_cv_type_size_t" = x""yes; then :
+
+else
+
+cat >>confdefs.h <<_ACEOF
+#define size_t unsigned int
+_ACEOF
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5
+$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; }
+if test "${ac_cv_header_time+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+#include <sys/time.h>
+#include <time.h>
+
+int
+main ()
+{
+if ((struct tm *) 0)
+return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_time=yes
+else
+  ac_cv_header_time=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5
+$as_echo "$ac_cv_header_time" >&6; }
+if test $ac_cv_header_time = yes; then
+
+$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if test "${ac_cv_header_stdc+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
+for ac_header in fcntl.h limits.h malloc.h sys/ioctl.h sys/time.h unistd.h bstring.h io.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
+eval as_val=\$$as_ac_Header
+   if test "x$as_val" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+if test $ac_cv_c_compiler_gnu = yes; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC needs -traditional" >&5
+$as_echo_n "checking whether $CC needs -traditional... " >&6; }
+if test "${ac_cv_prog_gcc_traditional+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+    ac_pattern="Autoconf.*'x'"
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sgtty.h>
+Autoconf TIOCGETP
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "$ac_pattern" >/dev/null 2>&1; then :
+  ac_cv_prog_gcc_traditional=yes
+else
+  ac_cv_prog_gcc_traditional=no
+fi
+rm -f conftest*
+
+
+  if test $ac_cv_prog_gcc_traditional = no; then
+    cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <termio.h>
+Autoconf TCGETA
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "$ac_pattern" >/dev/null 2>&1; then :
+  ac_cv_prog_gcc_traditional=yes
+fi
+rm -f conftest*
+
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_gcc_traditional" >&5
+$as_echo "$ac_cv_prog_gcc_traditional" >&6; }
+  if test $ac_cv_prog_gcc_traditional = yes; then
+    CC="$CC -traditional"
+  fi
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking return type of signal handlers" >&5
+$as_echo_n "checking return type of signal handlers... " >&6; }
+if test "${ac_cv_type_signal+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <sys/types.h>
+#include <signal.h>
+
+int
+main ()
+{
+return *(signal (0, 0)) (0) == 1;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_type_signal=int
+else
+  ac_cv_type_signal=void
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_signal" >&5
+$as_echo "$ac_cv_type_signal" >&6; }
+
+cat >>confdefs.h <<_ACEOF
+#define RETSIGTYPE $ac_cv_type_signal
+_ACEOF
+
+
+for ac_func in vprintf
+do :
+  ac_fn_c_check_func "$LINENO" "vprintf" "ac_cv_func_vprintf"
+if test "x$ac_cv_func_vprintf" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_VPRINTF 1
+_ACEOF
+
+ac_fn_c_check_func "$LINENO" "_doprnt" "ac_cv_func__doprnt"
+if test "x$ac_cv_func__doprnt" = x""yes; then :
+
+$as_echo "#define HAVE_DOPRNT 1" >>confdefs.h
+
+fi
+
+fi
+done
+
+
+for ac_func in gettimeofday select socket strerror
+do :
+  as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=\$$as_ac_var
+   if test "x$as_val" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+done
+
+# The Ultrix 4.2 mips builtin alloca declared by alloca.h only works
+# for constant arguments.  Useless!
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working alloca.h" >&5
+$as_echo_n "checking for working alloca.h... " >&6; }
+if test "${ac_cv_working_alloca_h+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <alloca.h>
+int
+main ()
+{
+char *p = (char *) alloca (2 * sizeof (int));
+			  if (p) return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_working_alloca_h=yes
+else
+  ac_cv_working_alloca_h=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_working_alloca_h" >&5
+$as_echo "$ac_cv_working_alloca_h" >&6; }
+if test $ac_cv_working_alloca_h = yes; then
+
+$as_echo "#define HAVE_ALLOCA_H 1" >>confdefs.h
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for alloca" >&5
+$as_echo_n "checking for alloca... " >&6; }
+if test "${ac_cv_func_alloca_works+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __GNUC__
+# define alloca __builtin_alloca
+#else
+# ifdef _MSC_VER
+#  include <malloc.h>
+#  define alloca _alloca
+# else
+#  ifdef HAVE_ALLOCA_H
+#   include <alloca.h>
+#  else
+#   ifdef _AIX
+ #pragma alloca
+#   else
+#    ifndef alloca /* predefined by HP cc +Olibcalls */
+char *alloca ();
+#    endif
+#   endif
+#  endif
+# endif
+#endif
+
+int
+main ()
+{
+char *p = (char *) alloca (1);
+				    if (p) return 0;
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_func_alloca_works=yes
+else
+  ac_cv_func_alloca_works=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_alloca_works" >&5
+$as_echo "$ac_cv_func_alloca_works" >&6; }
+
+if test $ac_cv_func_alloca_works = yes; then
+
+$as_echo "#define HAVE_ALLOCA 1" >>confdefs.h
+
+else
+  # The SVR3 libPW and SVR4 libucb both contain incompatible functions
+# that cause trouble.  Some versions do not even contain alloca or
+# contain a buggy version.  If you still want to use their alloca,
+# use ar to extract alloca.o from them instead of compiling alloca.c.
+
+ALLOCA=\${LIBOBJDIR}alloca.$ac_objext
+
+$as_echo "#define C_ALLOCA 1" >>confdefs.h
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether \`alloca.c' needs Cray hooks" >&5
+$as_echo_n "checking whether \`alloca.c' needs Cray hooks... " >&6; }
+if test "${ac_cv_os_cray+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#if defined CRAY && ! defined CRAY2
+webecray
+#else
+wenotbecray
+#endif
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "webecray" >/dev/null 2>&1; then :
+  ac_cv_os_cray=yes
+else
+  ac_cv_os_cray=no
+fi
+rm -f conftest*
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_os_cray" >&5
+$as_echo "$ac_cv_os_cray" >&6; }
+if test $ac_cv_os_cray = yes; then
+  for ac_func in _getb67 GETB67 getb67; do
+    as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
+ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
+eval as_val=\$$as_ac_var
+   if test "x$as_val" = x""yes; then :
+
+cat >>confdefs.h <<_ACEOF
+#define CRAY_STACKSEG_END $ac_func
+_ACEOF
+
+    break
+fi
+
+  done
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking stack direction for C alloca" >&5
+$as_echo_n "checking stack direction for C alloca... " >&6; }
+if test "${ac_cv_c_stack_direction+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "$cross_compiling" = yes; then :
+  ac_cv_c_stack_direction=0
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$ac_includes_default
+int
+find_stack_direction ()
+{
+  static char *addr = 0;
+  auto char dummy;
+  if (addr == 0)
+    {
+      addr = &dummy;
+      return find_stack_direction ();
+    }
+  else
+    return (&dummy > addr) ? 1 : -1;
+}
+
+int
+main ()
+{
+  return find_stack_direction () < 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  ac_cv_c_stack_direction=1
+else
+  ac_cv_c_stack_direction=-1
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_stack_direction" >&5
+$as_echo "$ac_cv_c_stack_direction" >&6; }
+cat >>confdefs.h <<_ACEOF
+#define STACK_DIRECTION $ac_cv_c_stack_direction
+_ACEOF
+
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
+$as_echo_n "checking for dlopen in -ldl... " >&6; }
+if test "${ac_cv_lib_dl_dlopen+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ldl  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char dlopen ();
+int
+main ()
+{
+return dlopen ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_dl_dlopen=yes
+else
+  ac_cv_lib_dl_dlopen=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+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" = x""yes; then :
+  PDLIB="$PDLIB -ldl"
+else
+  echo "dynamic link support required" || exit 1
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sin in -lffm" >&5
+$as_echo_n "checking for sin in -lffm... " >&6; }
+if test "${ac_cv_lib_ffm_sin+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lffm  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char sin ();
+int
+main ()
+{
+return sin ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_ffm_sin=yes
+else
+  ac_cv_lib_ffm_sin=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ffm_sin" >&5
+$as_echo "$ac_cv_lib_ffm_sin" >&6; }
+if test "x$ac_cv_lib_ffm_sin" = x""yes; then :
+  PDLIB="$PDLIB -lffm"
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sin in -lm" >&5
+$as_echo_n "checking for sin in -lm... " >&6; }
+if test "${ac_cv_lib_m_sin+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char sin ();
+int
+main ()
+{
+return sin ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_m_sin=yes
+else
+  ac_cv_lib_m_sin=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_sin" >&5
+$as_echo "$ac_cv_lib_m_sin" >&6; }
+if test "x$ac_cv_lib_m_sin" = x""yes; then :
+  PDLIB="$PDLIB -lm"
+else
+  echo "math library required" || exit 1
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5
+$as_echo_n "checking for pthread_create in -lpthread... " >&6; }
+if test "${ac_cv_lib_pthread_pthread_create+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpthread  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_create ();
+int
+main ()
+{
+return pthread_create ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthread_pthread_create=yes
+else
+  ac_cv_lib_pthread_pthread_create=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5
+$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; }
+if test "x$ac_cv_lib_pthread_pthread_create" = x""yes; then :
+  PDLIB="$PDLIB -lpthread"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreadGC2" >&5
+$as_echo_n "checking for pthread_create in -lpthreadGC2... " >&6; }
+if test "${ac_cv_lib_pthreadGC2_pthread_create+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpthreadGC2  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_create ();
+int
+main ()
+{
+return pthread_create ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthreadGC2_pthread_create=yes
+else
+  ac_cv_lib_pthreadGC2_pthread_create=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreadGC2_pthread_create" >&5
+$as_echo "$ac_cv_lib_pthreadGC2_pthread_create" >&6; }
+if test "x$ac_cv_lib_pthreadGC2_pthread_create" = x""yes; then :
+  PDLIB="$PDLIB -lpthreadGC2"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreadGC1" >&5
+$as_echo_n "checking for pthread_create in -lpthreadGC1... " >&6; }
+if test "${ac_cv_lib_pthreadGC1_pthread_create+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpthreadGC1  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_create ();
+int
+main ()
+{
+return pthread_create ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthreadGC1_pthread_create=yes
+else
+  ac_cv_lib_pthreadGC1_pthread_create=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreadGC1_pthread_create" >&5
+$as_echo "$ac_cv_lib_pthreadGC1_pthread_create" >&6; }
+if test "x$ac_cv_lib_pthreadGC1_pthread_create" = x""yes; then :
+  PDLIB="$PDLIB -lpthreadGC1"
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthreadGC" >&5
+$as_echo_n "checking for pthread_create in -lpthreadGC... " >&6; }
+if test "${ac_cv_lib_pthreadGC_pthread_create+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpthreadGC  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char pthread_create ();
+int
+main ()
+{
+return pthread_create ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_pthreadGC_pthread_create=yes
+else
+  ac_cv_lib_pthreadGC_pthread_create=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthreadGC_pthread_create" >&5
+$as_echo "$ac_cv_lib_pthreadGC_pthread_create" >&6; }
+if test "x$ac_cv_lib_pthreadGC_pthread_create" = x""yes; then :
+  PDLIB="$PDLIB -lpthreadGC"
+else
+  echo "pthreads required"; exit 1
+fi
+
+fi
+
+fi
+
+fi
+
+
+if test x$fftw = "xyes";
+then
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for fftw_one in -lfftw" >&5
+$as_echo_n "checking for fftw_one in -lfftw... " >&6; }
+if test "${ac_cv_lib_fftw_fftw_one+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lfftw  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char fftw_one ();
+int
+main ()
+{
+return fftw_one ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_fftw_fftw_one=yes
+else
+  ac_cv_lib_fftw_fftw_one=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_fftw_fftw_one" >&5
+$as_echo "$ac_cv_lib_fftw_fftw_one" >&6; }
+if test "x$ac_cv_lib_fftw_fftw_one" = x""yes; then :
+  PDLIB="$PDLIB -lfftw"
+else
+  echo "fftw package not found - using built-in FFT"; fftw=no
+fi
+
+fi
+
+
+foundit=no
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl.h" "ac_cv_header_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl_h" = x""yes; then :
+  foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.7/tcl.h" "ac_cv_header_tcl8_7_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_7_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/include/tcl8.7";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.6/tcl.h" "ac_cv_header_tcl8_6_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_6_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/include/tcl8.6";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.5/tcl.h" "ac_cv_header_tcl8_5_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_5_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/include/tcl8.5";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.4/tcl.h" "ac_cv_header_tcl8_4_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_4_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/include/tcl8.4";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.4/tcl.h" "ac_cv_header_tcl8_4_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_4_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/local/include/tcl8.4";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.3/tcl.h" "ac_cv_header_tcl8_3_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_3_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/include/tcl8.3";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    ac_fn_c_check_header_mongrel "$LINENO" "tcl8.2/tcl.h" "ac_cv_header_tcl8_2_tcl_h" "$ac_includes_default"
+if test "x$ac_cv_header_tcl8_2_tcl_h" = x""yes; then :
+  GUIFLAGS="$GUIFLAGS -I/usr/include/tcl8.2";foundit=yes
+fi
+
+
+fi
+if test $foundit = "no";
+then
+    echo no tcl header found
+         echo bolding trying without...
+#    exit -1
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl85" >&5
+$as_echo_n "checking for main in -ltcl85... " >&6; }
+if test "${ac_cv_lib_tcl85_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl85  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl85_main=yes
+else
+  ac_cv_lib_tcl85_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl85_main" >&5
+$as_echo "$ac_cv_lib_tcl85_main" >&6; }
+if test "x$ac_cv_lib_tcl85_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL85 1
+_ACEOF
+
+  LIBS="-ltcl85 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl8.5" >&5
+$as_echo_n "checking for main in -ltcl8.5... " >&6; }
+if test "${ac_cv_lib_tcl8_5_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl8.5  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl8_5_main=yes
+else
+  ac_cv_lib_tcl8_5_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl8_5_main" >&5
+$as_echo "$ac_cv_lib_tcl8_5_main" >&6; }
+if test "x$ac_cv_lib_tcl8_5_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL8_5 1
+_ACEOF
+
+  LIBS="-ltcl8.5 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl84" >&5
+$as_echo_n "checking for main in -ltcl84... " >&6; }
+if test "${ac_cv_lib_tcl84_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl84  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl84_main=yes
+else
+  ac_cv_lib_tcl84_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl84_main" >&5
+$as_echo "$ac_cv_lib_tcl84_main" >&6; }
+if test "x$ac_cv_lib_tcl84_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL84 1
+_ACEOF
+
+  LIBS="-ltcl84 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl8.4" >&5
+$as_echo_n "checking for main in -ltcl8.4... " >&6; }
+if test "${ac_cv_lib_tcl8_4_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl8.4  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl8_4_main=yes
+else
+  ac_cv_lib_tcl8_4_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl8_4_main" >&5
+$as_echo "$ac_cv_lib_tcl8_4_main" >&6; }
+if test "x$ac_cv_lib_tcl8_4_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL8_4 1
+_ACEOF
+
+  LIBS="-ltcl8.4 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl8.3" >&5
+$as_echo_n "checking for main in -ltcl8.3... " >&6; }
+if test "${ac_cv_lib_tcl8_3_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl8.3  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl8_3_main=yes
+else
+  ac_cv_lib_tcl8_3_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl8_3_main" >&5
+$as_echo "$ac_cv_lib_tcl8_3_main" >&6; }
+if test "x$ac_cv_lib_tcl8_3_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL8_3 1
+_ACEOF
+
+  LIBS="-ltcl8.3 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl8.2" >&5
+$as_echo_n "checking for main in -ltcl8.2... " >&6; }
+if test "${ac_cv_lib_tcl8_2_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl8.2  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl8_2_main=yes
+else
+  ac_cv_lib_tcl8_2_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl8_2_main" >&5
+$as_echo "$ac_cv_lib_tcl8_2_main" >&6; }
+if test "x$ac_cv_lib_tcl8_2_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL8_2 1
+_ACEOF
+
+  LIBS="-ltcl8.2 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltcl8.0" >&5
+$as_echo_n "checking for main in -ltcl8.0... " >&6; }
+if test "${ac_cv_lib_tcl8_0_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltcl8.0  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tcl8_0_main=yes
+else
+  ac_cv_lib_tcl8_0_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tcl8_0_main" >&5
+$as_echo "$ac_cv_lib_tcl8_0_main" >&6; }
+if test "x$ac_cv_lib_tcl8_0_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTCL8_0 1
+_ACEOF
+
+  LIBS="-ltcl8.0 $LIBS"
+
+else
+  echo no tcl library found; exit 1
+fi
+
+fi
+
+fi
+
+fi
+
+fi
+
+fi
+
+fi
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk85" >&5
+$as_echo_n "checking for main in -ltk85... " >&6; }
+if test "${ac_cv_lib_tk85_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk85  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk85_main=yes
+else
+  ac_cv_lib_tk85_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk85_main" >&5
+$as_echo "$ac_cv_lib_tk85_main" >&6; }
+if test "x$ac_cv_lib_tk85_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK85 1
+_ACEOF
+
+  LIBS="-ltk85 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk8.5" >&5
+$as_echo_n "checking for main in -ltk8.5... " >&6; }
+if test "${ac_cv_lib_tk8_5_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk8.5  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk8_5_main=yes
+else
+  ac_cv_lib_tk8_5_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk8_5_main" >&5
+$as_echo "$ac_cv_lib_tk8_5_main" >&6; }
+if test "x$ac_cv_lib_tk8_5_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK8_5 1
+_ACEOF
+
+  LIBS="-ltk8.5 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk84" >&5
+$as_echo_n "checking for main in -ltk84... " >&6; }
+if test "${ac_cv_lib_tk84_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk84  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk84_main=yes
+else
+  ac_cv_lib_tk84_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk84_main" >&5
+$as_echo "$ac_cv_lib_tk84_main" >&6; }
+if test "x$ac_cv_lib_tk84_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK84 1
+_ACEOF
+
+  LIBS="-ltk84 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk8.4" >&5
+$as_echo_n "checking for main in -ltk8.4... " >&6; }
+if test "${ac_cv_lib_tk8_4_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk8.4  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk8_4_main=yes
+else
+  ac_cv_lib_tk8_4_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk8_4_main" >&5
+$as_echo "$ac_cv_lib_tk8_4_main" >&6; }
+if test "x$ac_cv_lib_tk8_4_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK8_4 1
+_ACEOF
+
+  LIBS="-ltk8.4 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk8.3" >&5
+$as_echo_n "checking for main in -ltk8.3... " >&6; }
+if test "${ac_cv_lib_tk8_3_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk8.3  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk8_3_main=yes
+else
+  ac_cv_lib_tk8_3_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk8_3_main" >&5
+$as_echo "$ac_cv_lib_tk8_3_main" >&6; }
+if test "x$ac_cv_lib_tk8_3_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK8_3 1
+_ACEOF
+
+  LIBS="-ltk8.3 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk8.2" >&5
+$as_echo_n "checking for main in -ltk8.2... " >&6; }
+if test "${ac_cv_lib_tk8_2_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk8.2  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk8_2_main=yes
+else
+  ac_cv_lib_tk8_2_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk8_2_main" >&5
+$as_echo "$ac_cv_lib_tk8_2_main" >&6; }
+if test "x$ac_cv_lib_tk8_2_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK8_2 1
+_ACEOF
+
+  LIBS="-ltk8.2 $LIBS"
+
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ltk8.0" >&5
+$as_echo_n "checking for main in -ltk8.0... " >&6; }
+if test "${ac_cv_lib_tk8_0_main+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ltk8.0  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+
+int
+main ()
+{
+return main ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_tk8_0_main=yes
+else
+  ac_cv_lib_tk8_0_main=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_tk8_0_main" >&5
+$as_echo "$ac_cv_lib_tk8_0_main" >&6; }
+if test "x$ac_cv_lib_tk8_0_main" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBTK8_0 1
+_ACEOF
+
+  LIBS="-ltk8.0 $LIBS"
+
+else
+  echo no tk library found; exit 1
+fi
+
+fi
+
+fi
+
+fi
+
+fi
+
+fi
+
+fi
+
+
+
+if test x$tk != "xno"; then
+GUISRC="t_main.c t_tkcmd.c"
+else
+GUISRC=
+fi
+
+# leave the executable as 'pd' on Mac OS X and Windows, but call it
+# 'pdl2ork' on GNU/Linux
+PDEXEC=pd
+
+if test `uname -s` = Linux;
+then
+    PDEXEC=pd-l2ork
+        echo .................... alsa= $alsa
+    if test x$alsa = xyes; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for snd_pcm_info in -lasound" >&5
+$as_echo_n "checking for snd_pcm_info in -lasound... " >&6; }
+if test "${ac_cv_lib_asound_snd_pcm_info+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lasound  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char snd_pcm_info ();
+int
+main ()
+{
+return snd_pcm_info ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_asound_snd_pcm_info=yes
+else
+  ac_cv_lib_asound_snd_pcm_info=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_asound_snd_pcm_info" >&5
+$as_echo "$ac_cv_lib_asound_snd_pcm_info" >&6; }
+if test "x$ac_cv_lib_asound_snd_pcm_info" = x""yes; then :
+  PDLIB="$PDLIB -lasound" ; alsa="yes"
+else
+  alsa="no"
+fi
+
+    fi
+
+
+    if test x$jack = xyes; then
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shm_open in -lrt" >&5
+$as_echo_n "checking for shm_open in -lrt... " >&6; }
+if test "${ac_cv_lib_rt_shm_open+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lrt  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char shm_open ();
+int
+main ()
+{
+return shm_open ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_rt_shm_open=yes
+else
+  ac_cv_lib_rt_shm_open=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_shm_open" >&5
+$as_echo "$ac_cv_lib_rt_shm_open" >&6; }
+if test "x$ac_cv_lib_rt_shm_open" = x""yes; then :
+  LIBS="$LIBS -lrt"
+fi
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for jack_set_xrun_callback in -ljack" >&5
+$as_echo_n "checking for jack_set_xrun_callback in -ljack... " >&6; }
+if test "${ac_cv_lib_jack_jack_set_xrun_callback+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ljack  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char jack_set_xrun_callback ();
+int
+main ()
+{
+return jack_set_xrun_callback ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_jack_jack_set_xrun_callback=yes
+else
+  ac_cv_lib_jack_jack_set_xrun_callback=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jack_jack_set_xrun_callback" >&5
+$as_echo "$ac_cv_lib_jack_jack_set_xrun_callback" >&6; }
+if test "x$ac_cv_lib_jack_jack_set_xrun_callback" = x""yes; then :
+  LIBS="$LIBS -ljack";jack=xrun
+else
+  jack=no
+fi
+
+        { $as_echo "$as_me:${as_lineno-$LINENO}: checking for jack_set_error_function in -ljack" >&5
+$as_echo_n "checking for jack_set_error_function in -ljack... " >&6; }
+if test "${ac_cv_lib_jack_jack_set_error_function+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-ljack  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char jack_set_error_function ();
+int
+main ()
+{
+return jack_set_error_function ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_jack_jack_set_error_function=yes
+else
+  ac_cv_lib_jack_jack_set_error_function=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jack_jack_set_error_function" >&5
+$as_echo "$ac_cv_lib_jack_jack_set_error_function" >&6; }
+if test "x$ac_cv_lib_jack_jack_set_error_function" = x""yes; then :
+  LIBS="$LIBS -ljack";jack=yes
+else
+  jack=no
+fi
+
+    fi
+
+    LDFLAGS="-Wl,-export-dynamic"
+    if test "$static" = "yes"; then
+      LDFLAGS="$LDFLAGS -static"
+    fi
+    EXT=pd_linux
+    CPPFLAGS="-DDL_OPEN -DPA_USE_OSS -DUNIX -DUNISTD\
+        -DUSEAPI_OSS \
+        -fno-strict-aliasing"
+    SYSSRC="s_midi_oss.c s_audio_oss.c"
+    if test x$alsa = "xyes";
+    then
+        SYSSRC=$SYSSRC" s_audio_alsa.c s_audio_alsamm.c s_midi_alsa.c"
+        CPPFLAGS=$CPPFLAGS" -DPA_USE_ALSA -DUSEAPI_ALSA"
+        LDFLAGS=$LDFLAGS" -lasound"
+    fi
+
+    if test x$portaudio = "xyes";
+    then
+        CPPFLAGS=$CPPFLAGS" -DUSEAPI_PORTAUDIO -DHAVE_SYS_SOUNDCARD_H \
+        -Wno-error \
+        -I../portaudio/include -I../portaudio/src/common \
+        -I../portaudio/src/os/unix/ \
+        -I../portmidi/pm_common \
+        -I../portmidi/pm_linux"
+        SYSSRC="s_audio_pa.c \
+        s_audio_pablio.c     \
+        s_audio_paring.c     \
+        ../portaudio/src/common/pa_allocation.c  \
+        ../portaudio/src/common/pa_converters.c  \
+        ../portaudio/src/common/pa_cpuload.c     \
+        ../portaudio/src/common/pa_dither.c      \
+        ../portaudio/src/common/pa_front.c       \
+        ../portaudio/src/common/pa_process.c     \
+        ../portaudio/src/common/pa_skeleton.c    \
+        ../portaudio/src/common/pa_stream.c      \
+        ../portaudio/src/common/pa_trace.c       \
+        ../portaudio/src/common/pa_debugprint.c  \
+        ../portaudio/src/common/pa_ringbuffer.c  \
+        ../portaudio/src/os/unix/pa_unix_hostapis.c \
+        ../portaudio/src/os/unix/pa_unix_util.c     \
+        ../portaudio/src/hostapi/oss/pa_unix_oss.c "$SYSSRC
+        if test x$alsa = "xyes";
+        then
+            SYSSRC="../portaudio/src/hostapi/alsa/pa_linux_alsa.c "$SYSSRC
+            CPPFLAGS=$CPPFLAGS" -DPA_USE_ALSA"
+        fi
+        if test x$jack = "xyes";
+        then
+            SYSSRC="../portaudio/src/hostapi/jack/pa_jack.c "$SYSSRC
+            CPPFLAGS=$CPPFLAGS" -DPA_USE_JACK"
+        fi
+    fi
+    if test x$setuid = "xyes";
+    then
+        binarymode="-m4755"
+    fi
+    STRIPFLAG=-s
+    GUINAME="pd-gui"
+    if test x$USE_DEBUG_CFLAGS = "xyes";
+    then
+        MORECFLAGS=$MORECFLAGS" -g"
+    else
+        MORECFLAGS=$MORECFLAGS" -O6 -funroll-loops -fomit-frame-pointer"
+    fi
+    if test x$jack = "xyes";
+    then
+        LDFLAGS=$LDFLAGS" -lrt -ljack"
+    fi
+    if test x$jack = "xrun";
+    then
+        LDFLAGS=$LDFLAGS" -lrt -ljack"
+    fi
+
+    OSNUMBER=0
+
+fi
+
+if test `uname -s` = Darwin;
+then
+    LDFLAGS="-Wl -framework CoreAudio \
+        -framework AudioUnit -framework AudioToolbox \
+        -framework Carbon -framework CoreMIDI"
+    EXT=pd_darwin
+    CPPFLAGS="-DDL_OPEN -DMACOSX -DUNISTD -I/usr/X11R6/include \
+        -I../portaudio/include -I../portaudio/src/common \
+        -I../portaudio/src/os/mac_osx/ \
+        -I../portmidi/pm_common -I../portmidi/pm_mac \
+        -I../portmidi/porttime \
+        -DUSEAPI_PORTAUDIO -DPA19 -DPA_USE_COREAUDIO -DNEWBUFFER"
+        if test `uname -r` = 7.9.0;
+    then
+        fat="no"
+    fi
+    if test "x$fat" == "xyes";
+    then
+        MORECFLAGS="-isysroot /Developer/SDKs/MacOSX10.4u.sdk \
+            -arch i386 -arch ppc -Wno-error"
+        EXTERNTARGET=d_fat
+        LDFLAGS=$LDFLAGS" -arch i386 -arch ppc"
+    else
+        MORECFLAGS="-DMACOSX3 -DPA_BIG_ENDIAN -Wno-error"
+        EXTERNTARGET=d_ppc
+    fi
+    SYSSRC="s_midi_pm.c s_audio_pa.c \
+        s_audio_pablio.c     \
+        s_audio_paring.c     \
+        ../portaudio/src/common/pa_allocation.c  \
+        ../portaudio/src/common/pa_converters.c  \
+        ../portaudio/src/common/pa_cpuload.c     \
+        ../portaudio/src/common/pa_dither.c      \
+        ../portaudio/src/common/pa_front.c       \
+        ../portaudio/src/common/pa_process.c     \
+        ../portaudio/src/common/pa_skeleton.c    \
+        ../portaudio/src/common/pa_stream.c      \
+        ../portaudio/src/common/pa_trace.c       \
+        ../portaudio/src/common/pa_debugprint.c       \
+        ../portaudio/src/common/pa_ringbuffer.c  \
+        ../portaudio/src/os/unix/pa_unix_util.c     \
+        ../portaudio/src/os/mac_osx/pa_mac_hostapis.c   \
+        ../portaudio/src/hostapi/coreaudio/pa_mac_core.c  \
+        ../portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c  \
+        ../portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c  \
+        ../portmidi/pm_mac/pmmac.c \
+        ../portmidi/pm_mac/pmmacosxcm.c \
+        ../portmidi/pm_mac/finddefault.c \
+        ../portmidi/pm_mac/readbinaryplist.c \
+        ../portmidi/pm_common/pmutil.c \
+        ../portmidi/pm_common/portmidi.c \
+        ../portmidi/porttime/ptmacosx_cf.c "
+    STRIPFLAG=""
+    GUINAME="libPdTcl.dylib"
+
+# find the Tcl/Tk Frameworks
+         if test -d "../../Frameworks";
+    then
+        # Miller's location
+        TCLTK_FRAMEWORKS_PATH="../../Frameworks"
+         elif test -d "/Library/Frameworks";
+         then
+        # get it from the default install location
+        TCLTK_FRAMEWORKS_PATH="/Library/Frameworks"
+    else
+        # Panther has Tcl here; Tiger has Tcl and Tk here
+        TCLTK_FRAMEWORKS_PATH="/System/Library/Frameworks"
+    fi
+    GUIFLAGS="-F$TCLTK_FRAMEWORKS_PATH -framework Tcl -framework Tk \
+        -I$TCLTK_FRAMEWORKS_PATH/Tk.framework/Versions/Current/Headers \
+        -I$TCLTK_FRAMEWORKS_PATH/Tcl.framework/Versions/Current/Headers \
+        -I$TCLTK_FRAMEWORKS_PATH/Tcl.framework/Versions/8.4/PrivateHeaders"
+    if test x$USE_DEBUG_CFLAGS = "xyes";
+    then
+        MORECFLAGS=$MORECFLAGS" -g"
+    else
+        MORECFLAGS=$MORECFLAGS" -O2"
+    fi
+    OSNUMBER=2
+    if test x$jack = "xyes";
+    then
+    	LDFLAGS=$LDFLAGS" -weak_framework Jackmp"
+    fi
+    if test x$jack = "xrun";
+    then
+        LDFLAGS=$LDFLAGS" -weak_framework Jackmp"
+    fi
+fi
+
+# only Windows uses ASIO, for the rest, set to blank
+ASIOSRC=
+
+if test `uname -s` = MINGW32_NT-5.0;
+then
+    EXT=dll
+    MORECFLAGS="-DUSEAPI_PORTAUDIO -DPA19 -DMSW -DPA_NO_DS -DPD_INTERNAL \
+        -I../portaudio/include -I../portaudio/src/common \
+        -I../portaudio/src/os/win/ \
+        -mwindows -mms-bitfields "$MORECFLAGS
+    PDLIB=$PDLIB" -lwsock32 -lwinmm -lole32 -lstdc++"
+
+    SYSSRC="s_audio_pa.c s_audio_pablio.c s_audio_paring.c \
+        s_audio_mmio.c s_midi_mmio.c \
+        ../portaudio/src/common/pa_allocation.c  \
+        ../portaudio/src/common/pa_converters.c  \
+        ../portaudio/src/common/pa_cpuload.c     \
+        ../portaudio/src/common/pa_dither.c      \
+        ../portaudio/src/common/pa_front.c       \
+        ../portaudio/src/common/pa_process.c     \
+        ../portaudio/src/common/pa_skeleton.c    \
+        ../portaudio/src/common/pa_stream.c      \
+        ../portaudio/src/common/pa_trace.c       \
+        ../portaudio/src/common/pa_debugprint.c       \
+        ../portaudio/src/common/pa_ringbuffer.c  \
+        ../portaudio/src/os/win/pa_win_util.c       \
+        ../portaudio/src/os/win/pa_win_hostapis.c   \
+        ../portaudio/src/os/win/pa_x86_plain_converters.c   \
+        ../portaudio/src/hostapi/wmme/pa_win_wmme.c"
+         ASIOSRC="../portaudio/src/hostapi/asio/iasiothiscallresolver.cpp \
+         ../portaudio/src/hostapi/pa_asio/asio.cpp ../asio/asio.cpp \
+         ../asio/asiodrivers.cpp ../asio/asiolist.cpp"
+    STRIPFLAG="--strip-unneeded"
+    GUINAME="pdtcl.dll"
+    GUIFLAGS=
+fi
+
+# support for jack, on either linux or darwin:
+
+if test x$jack = "xyes";
+then
+    MORECFLAGS=$MORECFLAGS" -DUSEAPI_JACK"
+    SYSSRC=$SYSSRC" s_audio_jack.c"
+fi
+if test x$jack = "xrun";
+then
+    MORECFLAGS=$MORECFLAGS" -DUSEAPI_JACK -DJACK_XRUN"
+    SYSSRC=$SYSSRC" s_audio_jack.c"
+fi
+
+if test x$fftw = "xyes";
+then
+    SYSSRC=$SYSSRC" d_fft_fftw.c d_fftroutine.c"
+    LDFLAGS=$LDFLAGS" -lfftw"
+else
+    SYSSRC=$SYSSRC" d_fft_mayer.c d_fftroutine.c"
+fi
+
+## JMZ{
+##  this does not do very much, but i guess it is a good idea to use it...
+# 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 test "${ac_cv_sys_largefile_CC+set}" = set; 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 << 62) - 1 + ((off_t) 1 << 62))
+  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 test "${ac_cv_sys_file_offset_bits+set}" = set; 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 << 62) - 1 + ((off_t) 1 << 62))
+  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 << 62) - 1 + ((off_t) 1 << 62))
+  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 test "${ac_cv_sys_large_files+set}" = set; 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 << 62) - 1 + ((off_t) 1 << 62))
+  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 << 62) - 1 + ((off_t) 1 << 62))
+  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
+
+## test, whether we can use _LARGEFILE64_SOURCE to
+## enable large-file reading via "open64" (and lseek64");
+if test "x$enable_largefile" != "xno"; then
+## the following should run on autoconf>2.54 (which pd is not using)
+## and this is for autoconf<2.50
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+                                        #define _LARGEFILE64_SOURCE
+                                        #include <sys/types.h>
+                                        #include <sys/stat.h>
+                                        #include <fcntl.h>
+
+int
+main ()
+{
+ open64(0,0);
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+   MORECFLAGS=$MORECFLAGS" -D_LARGEFILE64_SOURCE"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi
+## }JMZ: end of large-file support section
+
+if test -d ../obj
+then echo -n
+else mkdir ../obj
+fi
+
+if test -d ../bin
+then echo -n
+else mkdir ../bin
+fi
+
+
+if test "x${PBX_SINF}" != "x1" -a "${USE_SINF}" != "no"; then
+   pbxlibdir=""
+   # if --with-SINF=DIR has been specified, use it.
+   if test "x${SINF_DIR}" != "x"; then
+      if test -d ${SINF_DIR}/lib; then
+      	 pbxlibdir="-L${SINF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${SINF_DIR}"
+      fi
+   fi
+   pbxfuncname="sinf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_SINF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_SINF_FOUND=yes
+else
+  AST_SINF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_SINF_FOUND}" = "yes"; then
+      SINF_LIB="${pbxlibdir} -lm "
+      # if --with-SINF=DIR has been specified, use it.
+      if test "x${SINF_DIR}" != "x"; then
+	 SINF_INCLUDE="-I${SINF_DIR}/include"
+      fi
+      SINF_INCLUDE="${SINF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         SINF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${SINF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  SINF_HEADER_FOUND=1
+else
+  SINF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${SINF_HEADER_FOUND}" = "x0" ; then
+         SINF_LIB=""
+         SINF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    SINF_LIB=""
+	 fi
+         PBX_SINF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_SINF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_SINF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_COSF}" != "x1" -a "${USE_COSF}" != "no"; then
+   pbxlibdir=""
+   # if --with-COSF=DIR has been specified, use it.
+   if test "x${COSF_DIR}" != "x"; then
+      if test -d ${COSF_DIR}/lib; then
+      	 pbxlibdir="-L${COSF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${COSF_DIR}"
+      fi
+   fi
+   pbxfuncname="cosf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_COSF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_COSF_FOUND=yes
+else
+  AST_COSF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_COSF_FOUND}" = "yes"; then
+      COSF_LIB="${pbxlibdir} -lm "
+      # if --with-COSF=DIR has been specified, use it.
+      if test "x${COSF_DIR}" != "x"; then
+	 COSF_INCLUDE="-I${COSF_DIR}/include"
+      fi
+      COSF_INCLUDE="${COSF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         COSF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${COSF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  COSF_HEADER_FOUND=1
+else
+  COSF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${COSF_HEADER_FOUND}" = "x0" ; then
+         COSF_LIB=""
+         COSF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    COSF_LIB=""
+	 fi
+         PBX_COSF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_COSF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_COSF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_ATANF}" != "x1" -a "${USE_ATANF}" != "no"; then
+   pbxlibdir=""
+   # if --with-ATANF=DIR has been specified, use it.
+   if test "x${ATANF_DIR}" != "x"; then
+      if test -d ${ATANF_DIR}/lib; then
+      	 pbxlibdir="-L${ATANF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${ATANF_DIR}"
+      fi
+   fi
+   pbxfuncname="atanf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_ATANF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_ATANF_FOUND=yes
+else
+  AST_ATANF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_ATANF_FOUND}" = "yes"; then
+      ATANF_LIB="${pbxlibdir} -lm "
+      # if --with-ATANF=DIR has been specified, use it.
+      if test "x${ATANF_DIR}" != "x"; then
+	 ATANF_INCLUDE="-I${ATANF_DIR}/include"
+      fi
+      ATANF_INCLUDE="${ATANF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         ATANF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${ATANF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  ATANF_HEADER_FOUND=1
+else
+  ATANF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${ATANF_HEADER_FOUND}" = "x0" ; then
+         ATANF_LIB=""
+         ATANF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    ATANF_LIB=""
+	 fi
+         PBX_ATANF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_ATANF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_ATANF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_ATAN2F}" != "x1" -a "${USE_ATAN2F}" != "no"; then
+   pbxlibdir=""
+   # if --with-ATAN2F=DIR has been specified, use it.
+   if test "x${ATAN2F_DIR}" != "x"; then
+      if test -d ${ATAN2F_DIR}/lib; then
+      	 pbxlibdir="-L${ATAN2F_DIR}/lib"
+      else
+      	 pbxlibdir="-L${ATAN2F_DIR}"
+      fi
+   fi
+   pbxfuncname="atan2f"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_ATAN2F_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_ATAN2F_FOUND=yes
+else
+  AST_ATAN2F_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_ATAN2F_FOUND}" = "yes"; then
+      ATAN2F_LIB="${pbxlibdir} -lm "
+      # if --with-ATAN2F=DIR has been specified, use it.
+      if test "x${ATAN2F_DIR}" != "x"; then
+	 ATAN2F_INCLUDE="-I${ATAN2F_DIR}/include"
+      fi
+      ATAN2F_INCLUDE="${ATAN2F_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         ATAN2F_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${ATAN2F_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  ATAN2F_HEADER_FOUND=1
+else
+  ATAN2F_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${ATAN2F_HEADER_FOUND}" = "x0" ; then
+         ATAN2F_LIB=""
+         ATAN2F_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    ATAN2F_LIB=""
+	 fi
+         PBX_ATAN2F=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_ATAN2F 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_ATAN2F_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_SQRTF}" != "x1" -a "${USE_SQRTF}" != "no"; then
+   pbxlibdir=""
+   # if --with-SQRTF=DIR has been specified, use it.
+   if test "x${SQRTF_DIR}" != "x"; then
+      if test -d ${SQRTF_DIR}/lib; then
+      	 pbxlibdir="-L${SQRTF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${SQRTF_DIR}"
+      fi
+   fi
+   pbxfuncname="sqrtf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_SQRTF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_SQRTF_FOUND=yes
+else
+  AST_SQRTF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_SQRTF_FOUND}" = "yes"; then
+      SQRTF_LIB="${pbxlibdir} -lm "
+      # if --with-SQRTF=DIR has been specified, use it.
+      if test "x${SQRTF_DIR}" != "x"; then
+	 SQRTF_INCLUDE="-I${SQRTF_DIR}/include"
+      fi
+      SQRTF_INCLUDE="${SQRTF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         SQRTF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${SQRTF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  SQRTF_HEADER_FOUND=1
+else
+  SQRTF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${SQRTF_HEADER_FOUND}" = "x0" ; then
+         SQRTF_LIB=""
+         SQRTF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    SQRTF_LIB=""
+	 fi
+         PBX_SQRTF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_SQRTF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_SQRTF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_LOGF}" != "x1" -a "${USE_LOGF}" != "no"; then
+   pbxlibdir=""
+   # if --with-LOGF=DIR has been specified, use it.
+   if test "x${LOGF_DIR}" != "x"; then
+      if test -d ${LOGF_DIR}/lib; then
+      	 pbxlibdir="-L${LOGF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${LOGF_DIR}"
+      fi
+   fi
+   pbxfuncname="logf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_LOGF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_LOGF_FOUND=yes
+else
+  AST_LOGF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_LOGF_FOUND}" = "yes"; then
+      LOGF_LIB="${pbxlibdir} -lm "
+      # if --with-LOGF=DIR has been specified, use it.
+      if test "x${LOGF_DIR}" != "x"; then
+	 LOGF_INCLUDE="-I${LOGF_DIR}/include"
+      fi
+      LOGF_INCLUDE="${LOGF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         LOGF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${LOGF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  LOGF_HEADER_FOUND=1
+else
+  LOGF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${LOGF_HEADER_FOUND}" = "x0" ; then
+         LOGF_LIB=""
+         LOGF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    LOGF_LIB=""
+	 fi
+         PBX_LOGF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_LOGF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_LOGF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_EXPF}" != "x1" -a "${USE_EXPF}" != "no"; then
+   pbxlibdir=""
+   # if --with-EXPF=DIR has been specified, use it.
+   if test "x${EXPF_DIR}" != "x"; then
+      if test -d ${EXPF_DIR}/lib; then
+      	 pbxlibdir="-L${EXPF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${EXPF_DIR}"
+      fi
+   fi
+   pbxfuncname="expf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_EXPF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_EXPF_FOUND=yes
+else
+  AST_EXPF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_EXPF_FOUND}" = "yes"; then
+      EXPF_LIB="${pbxlibdir} -lm "
+      # if --with-EXPF=DIR has been specified, use it.
+      if test "x${EXPF_DIR}" != "x"; then
+	 EXPF_INCLUDE="-I${EXPF_DIR}/include"
+      fi
+      EXPF_INCLUDE="${EXPF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         EXPF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${EXPF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  EXPF_HEADER_FOUND=1
+else
+  EXPF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${EXPF_HEADER_FOUND}" = "x0" ; then
+         EXPF_LIB=""
+         EXPF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    EXPF_LIB=""
+	 fi
+         PBX_EXPF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_EXPF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_EXPF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_FABSF}" != "x1" -a "${USE_FABSF}" != "no"; then
+   pbxlibdir=""
+   # if --with-FABSF=DIR has been specified, use it.
+   if test "x${FABSF_DIR}" != "x"; then
+      if test -d ${FABSF_DIR}/lib; then
+      	 pbxlibdir="-L${FABSF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${FABSF_DIR}"
+      fi
+   fi
+   pbxfuncname="fabsf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_FABSF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_FABSF_FOUND=yes
+else
+  AST_FABSF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_FABSF_FOUND}" = "yes"; then
+      FABSF_LIB="${pbxlibdir} -lm "
+      # if --with-FABSF=DIR has been specified, use it.
+      if test "x${FABSF_DIR}" != "x"; then
+	 FABSF_INCLUDE="-I${FABSF_DIR}/include"
+      fi
+      FABSF_INCLUDE="${FABSF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         FABSF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${FABSF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  FABSF_HEADER_FOUND=1
+else
+  FABSF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${FABSF_HEADER_FOUND}" = "x0" ; then
+         FABSF_LIB=""
+         FABSF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    FABSF_LIB=""
+	 fi
+         PBX_FABSF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_FABSF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_FABSF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+if test "x${PBX_POWF}" != "x1" -a "${USE_POWF}" != "no"; then
+   pbxlibdir=""
+   # if --with-POWF=DIR has been specified, use it.
+   if test "x${POWF_DIR}" != "x"; then
+      if test -d ${POWF_DIR}/lib; then
+      	 pbxlibdir="-L${POWF_DIR}/lib"
+      else
+      	 pbxlibdir="-L${POWF_DIR}"
+      fi
+   fi
+   pbxfuncname="powf"
+   if test "x${pbxfuncname}" = "x" ; then   # empty lib, assume only headers
+      AST_POWF_FOUND=yes
+   else
+      as_ac_Lib=`$as_echo "ac_cv_lib_m_${pbxfuncname}" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${pbxfuncname} in -lm" >&5
+$as_echo_n "checking for ${pbxfuncname} in -lm... " >&6; }
+if { as_var=$as_ac_Lib; eval "test \"\${$as_var+set}\" = set"; }; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm ${pbxlibdir}  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char ${pbxfuncname} ();
+int
+main ()
+{
+return ${pbxfuncname} ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+eval as_val=\$$as_ac_Lib
+   if test "x$as_val" = x""yes; then :
+  AST_POWF_FOUND=yes
+else
+  AST_POWF_FOUND=no
+fi
+
+   fi
+
+   # now check for the header.
+   if test "${AST_POWF_FOUND}" = "yes"; then
+      POWF_LIB="${pbxlibdir} -lm "
+      # if --with-POWF=DIR has been specified, use it.
+      if test "x${POWF_DIR}" != "x"; then
+	 POWF_INCLUDE="-I${POWF_DIR}/include"
+      fi
+      POWF_INCLUDE="${POWF_INCLUDE} "
+      if test "x" = "x" ; then	# no header, assume found
+         POWF_HEADER_FOUND="1"
+      else				# check for the header
+         saved_cppflags="${CPPFLAGS}"
+         CPPFLAGS="${CPPFLAGS} ${POWF_INCLUDE} "
+	 ac_fn_c_check_header_mongrel "$LINENO" "" "ac_cv_header_" "$ac_includes_default"
+if test "x$ac_cv_header_" = x""yes; then :
+  POWF_HEADER_FOUND=1
+else
+  POWF_HEADER_FOUND=0
+fi
+
+
+         CPPFLAGS="${saved_cppflags}"
+      fi
+      if test "x${POWF_HEADER_FOUND}" = "x0" ; then
+         POWF_LIB=""
+         POWF_INCLUDE=""
+      else
+         if test "x${pbxfuncname}" = "x" ; then		# only checking headers -> no library
+	    POWF_LIB=""
+	 fi
+         PBX_POWF=1
+         # XXX don't know how to evaluate the description (third argument) in AC_DEFINE_UNQUOTED
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_POWF 1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define HAVE_POWF_VERSION /**/
+_ACEOF
+
+      fi
+   fi
+fi
+
+
+ac_config_files="$ac_config_files makefile"
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems.  If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    test "x$cache_file" != "x/dev/null" &&
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
+    cat confcache >$cache_file
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+  fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+DEFS=-DHAVE_CONFIG_H
+
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
+: ${CONFIG_STATUS=./config.status}
+ac_write_fail=0
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # 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
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+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
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error ERROR [LINENO LOG_FD]
+# ---------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with status $?, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$?; test $as_status -eq 0 && as_status=1
+  if test "$3"; then
+    as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3
+  fi
+  $as_echo "$as_me: error: $1" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -p'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -p'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -p'
+  fi
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+	test -d "$1/.";
+      else
+	case $1 in #(
+	-*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.64.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=$*;;
+esac
+
+case $ac_config_headers in *"
+"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
+esac
+
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+# Files that config.status was made for.
+config_files="$ac_config_files"
+config_headers="$ac_config_headers"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+      --header=FILE[:TEMPLATE]
+                   instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Report bugs to the package provider."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.64,
+  with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2009 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+INSTALL='$INSTALL'
+test -n "\$AWK" || AWK=awk
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --header | --heade | --head | --hea )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    as_fn_append CONFIG_HEADERS " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h)
+    # Conflict between --help and --header
+    as_fn_error "ambiguous option: \`$1'
+Try \`$0 --help' for more information.";;
+  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) as_fn_error "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+if \$ac_cs_recheck; then
+  set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  CONFIG_SHELL='$SHELL'
+  export CONFIG_SHELL
+  exec "\$@"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
+    "makefile") CONFIG_FILES="$CONFIG_FILES makefile" ;;
+
+  *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp=
+  trap 'exit_status=$?
+  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -n "$tmp" && test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
+
+
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
+
+echo 'BEGIN {' >"$tmp/subs1.awk" &&
+_ACEOF
+
+
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'`
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  . ./conf$$subs.sh ||
+    as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n = $ac_delim_num; then
+    break
+  elif $ac_last_try; then
+    as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+rm -f conf$$subs.sh
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+cat >>"\$tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\).*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\).*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACAWK
+cat >>"\$tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
+
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \
+  || as_fn_error "could not setup config files machinery" "$LINENO" 5
+_ACEOF
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[	 ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+fi # test -n "$CONFIG_FILES"
+
+# Set up the scripts for CONFIG_HEADERS section.
+# No need to generate them if there are no CONFIG_HEADERS.
+# This happens for instance with `./config.status Makefile'.
+if test -n "$CONFIG_HEADERS"; then
+cat >"$tmp/defines.awk" <<\_ACAWK ||
+BEGIN {
+_ACEOF
+
+# Transform confdefs.h into an awk script `defines.awk', embedded as
+# here-document in config.status, that substitutes the proper values into
+# config.h.in to produce config.h.
+
+# Create a delimiter string that does not exist in confdefs.h, to ease
+# handling of long lines.
+ac_delim='%!_!# '
+for ac_last_try in false false :; do
+  ac_t=`sed -n "/$ac_delim/p" confdefs.h`
+  if test -z "$ac_t"; then
+    break
+  elif $ac_last_try; then
+    as_fn_error "could not make $CONFIG_HEADERS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+
+# For the awk script, D is an array of macro values keyed by name,
+# likewise P contains macro parameters if any.  Preserve backslash
+# newline sequences.
+
+ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
+sed -n '
+s/.\{148\}/&'"$ac_delim"'/g
+t rset
+:rset
+s/^[	 ]*#[	 ]*define[	 ][	 ]*/ /
+t def
+d
+:def
+s/\\$//
+t bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
+D["\1"]=" \3"/p
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2"/p
+d
+:bsnl
+s/["\\]/\\&/g
+s/^ \('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/P["\1"]="\2"\
+D["\1"]=" \3\\\\\\n"\\/p
+t cont
+s/^ \('"$ac_word_re"'\)[	 ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
+t cont
+d
+:cont
+n
+s/.\{148\}/&'"$ac_delim"'/g
+t clear
+:clear
+s/\\$//
+t bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/"/p
+d
+:bsnlc
+s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
+b cont
+' <confdefs.h | sed '
+s/'"$ac_delim"'/"\\\
+"/g' >>$CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  for (key in D) D_is_set[key] = 1
+  FS = ""
+}
+/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
+  line = \$ 0
+  split(line, arg, " ")
+  if (arg[1] == "#") {
+    defundef = arg[2]
+    mac1 = arg[3]
+  } else {
+    defundef = substr(arg[1], 2)
+    mac1 = arg[2]
+  }
+  split(mac1, mac2, "(") #)
+  macro = mac2[1]
+  prefix = substr(line, 1, index(line, defundef) - 1)
+  if (D_is_set[macro]) {
+    # Preserve the white space surrounding the "#".
+    print prefix "define", macro P[macro] D[macro]
+    next
+  } else {
+    # Replace #undef with comments.  This is necessary, for example,
+    # in the case of _POSIX_SOURCE, which is predefined and required
+    # on some systems where configure will not decide to define it.
+    if (defundef == "undef") {
+      print "/*", prefix defundef, macro, "*/"
+      next
+    }
+  }
+}
+{ print }
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+  as_fn_error "could not setup config headers machinery" "$LINENO" 5
+fi # test -n "$CONFIG_HEADERS"
+
+
+eval set X "  :F $CONFIG_FILES  :H $CONFIG_HEADERS    "
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$tmp/stdin" \
+      || as_fn_error "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
+
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+  case $INSTALL in
+  [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
+  *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
+  esac
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+  s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_sed_extra="$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+s&@INSTALL@&$ac_INSTALL&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \
+  || as_fn_error "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&2;}
+
+  rm -f "$tmp/stdin"
+  case $ac_file in
+  -) cat "$tmp/out" && rm -f "$tmp/out";;
+  *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error "could not create $ac_file" "$LINENO" 5
+ ;;
+  :H)
+  #
+  # CONFIG_HEADER
+  #
+  if test x"$ac_file" != x-; then
+    {
+      $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs"
+    } >"$tmp/config.h" \
+      || as_fn_error "could not create $ac_file" "$LINENO" 5
+    if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
+$as_echo "$as_me: $ac_file is unchanged" >&6;}
+    else
+      rm -f "$ac_file"
+      mv "$tmp/config.h" "$ac_file" \
+	|| as_fn_error "could not create $ac_file" "$LINENO" 5
+    fi
+  else
+    $as_echo "/* $configure_input  */" \
+      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \
+      || as_fn_error "could not create -" "$LINENO" 5
+  fi
+ ;;
+
+
+  esac
+
+done # for ac_tag
+
+
+as_fn_exit 0
+_ACEOF
+ac_clean_files=$ac_clean_files_save
+
+test $ac_write_fail = 0 ||
+  as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || as_fn_exit $?
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+fi
+
+
diff --git a/src/configure.in b/src/configure.in
index 9dd608734..369d0d9df 100644
--- a/src/configure.in
+++ b/src/configure.in
@@ -175,12 +175,12 @@ GUISRC=
 fi
 
 # leave the executable as 'pd' on Mac OS X and Windows, but call it
-# 'pdextended' on GNU/Linux
+# 'pdl2ork' on GNU/Linux
 PDEXEC=pd
 
 if test `uname -s` = Linux;
 then
-    PDEXEC=pdextended
+    PDEXEC=pd-l2ork
     dnl Ckecking for ALSA
     echo .................... alsa= $alsa
 dnl This should be fixed so Pd can use ALSA shared libraries where appropriate.
diff --git a/src/d_delay.c b/src/d_delay.c
index d36f349dc..98cc1149a 100644
--- a/src/d_delay.c
+++ b/src/d_delay.c
@@ -24,7 +24,6 @@ typedef struct _sigdelwrite
 {
     t_object x_obj;
     t_symbol *x_sym;
-    t_float x_deltime;  /* delay in msec (added by Mathieu Bouchard) */
     t_delwritectl x_cspace;
     int x_sortno;   /* DSP sort number at which this was last put on chain */
     int x_rsortno;  /* DSP sort # for first delread or write in chain */
@@ -35,21 +34,6 @@ typedef struct _sigdelwrite
 #define XTRASAMPS 4
 #define SAMPBLK 4
 
-static void sigdelwrite_updatesr (t_sigdelwrite *x, t_float sr) /* added by Mathieu Bouchard */
-{
-    int nsamps = x->x_deltime * sr * (t_float)(0.001f);
-    if (nsamps < 1) nsamps = 1;
-    nsamps += ((- nsamps) & (SAMPBLK - 1));
-    nsamps += DEFDELVS;
-    if (x->x_cspace.c_n != nsamps) {
-      x->x_cspace.c_vec = (t_sample *)resizebytes(x->x_cspace.c_vec,
-        (x->x_cspace.c_n + XTRASAMPS) * sizeof(t_sample),
-        (         nsamps + XTRASAMPS) * sizeof(t_sample));
-      x->x_cspace.c_n = nsamps;
-      x->x_cspace.c_phase = XTRASAMPS;
-    }
-}
-
     /* routine to check that all delwrites/delreads/vds have same vecsize */
 static void sigdelwrite_checkvecsize(t_sigdelwrite *x, int vecsize)
 {
@@ -70,13 +54,19 @@ static void sigdelwrite_checkvecsize(t_sigdelwrite *x, int vecsize)
 
 static void *sigdelwrite_new(t_symbol *s, t_floatarg msec)
 {
+    int nsamps;
     t_sigdelwrite *x = (t_sigdelwrite *)pd_new(sigdelwrite_class);
     if (!*s->s_name) s = gensym("delwrite~");
     pd_bind(&x->x_obj.ob_pd, s);
     x->x_sym = s;
-    x->x_deltime = msec;
-    x->x_cspace.c_n = 0;
-    x->x_cspace.c_vec = getbytes(XTRASAMPS * sizeof(t_sample));
+    nsamps = msec * sys_getsr() * (t_float)(0.001f);
+    if (nsamps < 1) nsamps = 1;
+    nsamps += ((- nsamps) & (SAMPBLK - 1));
+    nsamps += DEFDELVS;
+    x->x_cspace.c_n = nsamps;
+    x->x_cspace.c_vec =
+        (t_sample *)getbytes((nsamps + XTRASAMPS) * sizeof(t_sample));
+    x->x_cspace.c_phase = XTRASAMPS;
     x->x_sortno = 0;
     x->x_vecsize = 0;
     x->x_f = 0;
@@ -119,7 +109,6 @@ static void sigdelwrite_dsp(t_sigdelwrite *x, t_signal **sp)
     dsp_add(sigdelwrite_perform, 3, sp[0]->s_vec, &x->x_cspace, sp[0]->s_n);
     x->x_sortno = ugen_getsortno();
     sigdelwrite_checkvecsize(x, sp[0]->s_n);
-    sigdelwrite_updatesr(x, sp[0]->s_sr);
 }
 
 static void sigdelwrite_free(t_sigdelwrite *x)
@@ -211,7 +200,6 @@ static void sigdelread_dsp(t_sigdelread *x, t_signal **sp)
     x->x_n = sp[0]->s_n;
     if (delwriter)
     {
-        sigdelwrite_updatesr(delwriter, sp[0]->s_sr);
         sigdelwrite_checkvecsize(delwriter, sp[0]->s_n);
         x->x_zerodel = (delwriter->x_sortno == ugen_getsortno() ?
             0 : delwriter->x_vecsize);
diff --git a/src/d_math.c b/src/d_math.c
index 10517a354..31c6c6552 100644
--- a/src/d_math.c
+++ b/src/d_math.c
@@ -569,8 +569,6 @@ static void *pow_tilde_new(t_symbol *s, int argc, t_atom *argv)
     t_pow_tilde *x = (t_pow_tilde *)pd_new(pow_tilde_class);
     inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
     outlet_new(&x->x_obj, &s_signal);
-    pd_error(x, "A new incompatible [pow~] object was introduced in Pd 0.42.");
-    post("\tFor a backwards-compatible version, use [cyclone/pow~]");
     x->x_f = 0;
     return (x);
 }
diff --git a/src/d_ugen.c b/src/d_ugen.c
index af82e9559..fe49b7dee 100644
--- a/src/d_ugen.c
+++ b/src/d_ugen.c
@@ -219,11 +219,6 @@ static void block_float(t_block *x, t_floatarg f)
 
 static void block_bang(t_block *x)
 {
-    if (!dsp_chain) 
-    {
-        pd_error(x, "bang to block~ or switch~ with DSP off has no effect");
-        return;
-    }
     if (x->x_switched && !x->x_switchon)
     {
         t_int *ip;
diff --git a/src/g_all_guis.c b/src/g_all_guis.c
index 2adf4fecb..2aa2ecaa8 100644
--- a/src/g_all_guis.c
+++ b/src/g_all_guis.c
@@ -426,8 +426,8 @@ void iemgui_label_pos(void *x, t_iemgui *iemgui, t_symbol *s, int ac, t_atom *av
     iemgui->x_ldx = (int)atom_getintarg(0, ac, av);
     iemgui->x_ldy = (int)atom_getintarg(1, ac, av);
     if(glist_isvisible(iemgui->x_glist))
-        sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-                 glist_getcanvas(iemgui->x_glist), x,
+	    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+	             glist_getcanvas(iemgui->x_glist), x,
                  text_xpix((t_object *)x,iemgui->x_glist)+iemgui->x_ldx,
                  text_ypix((t_object *)x,iemgui->x_glist)+iemgui->x_ldy);
 }
@@ -502,13 +502,22 @@ void iemgui_color(void *x, t_iemgui *iemgui, t_symbol *s, int ac, t_atom *av)
 void iemgui_displace(t_gobj *z, t_glist *glist, int dx, int dy)
 {
     t_iemguidummy *x = (t_iemguidummy *)z;
-
     x->x_gui.x_obj.te_xpix += dx;
     x->x_gui.x_obj.te_ypix += dy;
     (*x->x_gui.x_draw)((void *)z, glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(glist), (t_text *)z);
 }
 
+void iemgui_displace_withtag(t_gobj *z, t_glist *glist, int dx, int dy)
+{
+    t_iemguidummy *x = (t_iemguidummy *)z;
+    x->x_gui.x_obj.te_xpix += dx;
+    x->x_gui.x_obj.te_ypix += dy;
+    //(*x->x_gui.x_draw)((void *)z, glist, IEM_GUI_DRAW_MODE_MOVE);
+    canvas_fixlinesfor(glist_getcanvas(glist), (t_text *)z);
+}
+
+
 void iemgui_select(t_gobj *z, t_glist *glist, int selected)
 {
     t_iemguidummy *x = (t_iemguidummy *)z;
diff --git a/src/g_all_guis.h b/src/g_all_guis.h
index b352fb9cd..f35210901 100644
--- a/src/g_all_guis.h
+++ b/src/g_all_guis.h
@@ -37,7 +37,11 @@
 #define IEM_GUI_COLNR_D_BLUE         28
 #define IEM_GUI_COLNR_D_MAGENTA      29
 
-#define IEM_GUI_COLOR_SELECTED       255
+/* deprecated in favor of the global iemgui_select var
+   left here for legacy externals that may rely upon this */
+#define IEM_GUI_COLOR_SELECTED       16749334
+/* end deprecated */
+
 #define IEM_GUI_COLOR_NORMAL         0
 
 #define IEM_GUI_MAX_COLOR            30
@@ -98,6 +102,28 @@
 #define IEM_GUI_COLOR_EDITED 16711680
 #define IEMGUI_MAX_NUM_LEN 32
 
+#define SCALE_BNG_MINWIDTH 8
+#define SCALE_BNG_MINHEIGHT 8
+#define SCALE_CNV_MINWIDTH 1
+#define SCALE_CNV_MINHEIGHT 1
+#define SCALE_HRDO_MINWIDTH 8
+#define SCALE_HRDO_MINHEIGHT 8
+#define SCALE_HSLD_MINWIDTH 2
+#define SCALE_HSLD_MINHEIGHT 8
+#define SCALE_NUM_MINWIDTH 1
+#define SCALE_NUM_MINHEIGHT 8
+#define SCALE_TGL_MINWIDTH 8
+#define SCALE_TGL_MINHEIGHT 8
+#define SCALE_VRDO_MINWIDTH 8
+#define SCALE_VRDO_MINHEIGHT 8
+#define SCALE_VSLD_MINWIDTH 8
+#define SCALE_VSLD_MINHEIGHT 2
+#define SCALE_VU_MINWIDTH 8
+#define SCALE_VU_MINHEIGHT 80
+
+#define SCALEHANDLE_WIDTH   10    /* item size is int */
+#define SCALEHANDLE_HEIGHT  10
+
 typedef struct _iem_fstyle_flags
 {
     unsigned int x_font_style:6;
@@ -135,11 +161,26 @@ typedef struct _iem_init_symargs
 
 typedef void (*t_iemfunptr)(void *x, t_glist *glist, int mode);
 
+typedef struct _scalehandle
+{
+    t_pd       h_pd;
+    t_gobj    *h_master;
+    t_symbol  *h_bindsym;
+    char       h_pathname[64];
+    char       h_outlinetag[64];
+    int        h_dragon;
+    int        h_dragx;
+    int        h_dragy;
+} t_scalehandle;
+
+static t_class *scalehandle_class;
+
 typedef struct _iemgui
 {
     t_object           x_obj;
     t_glist            *x_glist;
     t_iemfunptr        x_draw;
+    t_iemfunptr        x_draw_withtag;
     int                x_h;
     int                x_w;
     int                x_ldx;
@@ -159,6 +200,10 @@ typedef struct _iemgui
     t_symbol           *x_lab_unexpanded;
     int                x_binbufindex;       /* where in binbuf to find these */
     int                x_labelbindex;       /* where in binbuf to find label */
+	t_pd	   		   *x_handle;
+	int 			   scale_offset_x;
+	int				   scale_offset_y;
+	int				   scale_vis;
 } t_iemgui;
 
 typedef struct _iemguidummy
@@ -259,6 +304,9 @@ typedef struct _my_numbox
     int      x_lin0_log1;
     char     x_buf[IEMGUI_MAX_NUM_LEN];
     int      x_numwidth;
+    int      x_scalewidth; 		/* temporary value when resizing */
+	int		 x_scaleheight; 	/* temporary value when resizing */
+    int      x_tmpfontsize; 	/* temporary value when resizing */
     int      x_log_height;
 } t_my_numbox;
 
@@ -317,6 +365,7 @@ EXTERN void iemgui_pos(void *x, t_iemgui *iemgui, t_symbol *s, int ac, t_atom *a
 EXTERN void iemgui_color(void *x, t_iemgui *iemgui, t_symbol *s, int ac, t_atom *av);
 EXTERN int iemgui_list(void *x, t_iemgui *iemgui, t_symbol *s, int ac, t_atom *av);
 EXTERN void iemgui_displace(t_gobj *z, t_glist *glist, int dx, int dy);
+EXTERN void iemgui_displace_withtag(t_gobj *z, t_glist *glist, int dx, int dy);
 EXTERN void iemgui_select(t_gobj *z, t_glist *glist, int selected);
 EXTERN void iemgui_delete(t_gobj *z, t_glist *glist);
 EXTERN void iemgui_vis(t_gobj *z, t_glist *glist, int vis);
@@ -331,3 +380,5 @@ EXTERN void iem_inttosymargs(t_iem_init_symargs *symargp, int n);
 EXTERN int iem_symargstoint(t_iem_init_symargs *symargp);
 EXTERN void iem_inttofstyle(t_iem_fstyle_flags *fstylep, int n);
 EXTERN int iem_fstyletoint(t_iem_fstyle_flags *fstylep);
+
+EXTERN void canvas_apply_setundo(t_canvas *x, t_gobj *y);
diff --git a/src/g_array.c b/src/g_array.c
index f38c0e941..96f7044d0 100644
--- a/src/g_array.c
+++ b/src/g_array.c
@@ -345,12 +345,12 @@ void canvas_menuarray(t_glist *canvas)
 {
     t_glist *x = (t_glist *)canvas;
     char cmdbuf[200];
-    sprintf(cmdbuf, "pdtk_array_dialog %%s array%d 100 3 1\n", gcount+1);
+    sprintf(cmdbuf, "pdtk_array_dialog %%s array%d 100 3 1 .x%lx\n", gcount+1, (long unsigned int)canvas);
     gfxstub_new(&x->gl_pd, x, cmdbuf);
 }
 
     /* called from graph_dialog to set properties */
-void garray_properties(t_garray *x)
+void garray_properties(t_garray *x, t_glist *canvas)
 {
     char cmdbuf[200];
     t_array *a = garray_getarray(x);
@@ -363,19 +363,27 @@ void garray_properties(t_garray *x)
         properly; right now we just detect a leading '$' and escape
         it.  There should be a systematic way of doing this. */
     sprintf(cmdbuf, ((x->x_name->s_name[0] == '$') ?
-        "pdtk_array_dialog %%s \\%s %d %d 0\n" :
-        "pdtk_array_dialog %%s %s %d %d 0\n"),
+        "pdtk_array_dialog %%s \\%s %d %d 0 .x%lx\n" :
+        "pdtk_array_dialog %%s %s %d %d 0 .x%lx\n"),
             x->x_name->s_name, a->a_n, x->x_saveit + 
             2 * (int)(template_getfloat(template_findbyname(sc->sc_template),
-            gensym("style"), x->x_scalar->sc_vec, 1)));
+            gensym("style"), x->x_scalar->sc_vec, 1)), (long unsigned int)glist_getcanvas(canvas));
     gfxstub_new(&x->x_gobj.g_pd, x, cmdbuf);
 }
 
     /* this is called back from the dialog window to create a garray. 
     The otherflag requests that we find an existing graph to put it in. */
-void glist_arraydialog(t_glist *parent, t_symbol *name, t_floatarg size,
-    t_floatarg fflags, t_floatarg otherflag)
+void glist_arraydialog(t_glist *parent, t_symbol *s, int argc, t_atom *argv)
+//t_floatarg size, t_floatarg fflags, t_floatarg otherflag, float xdraw, float ydraw)
 {
+	t_float size, fflags, otherflag, xdraw, ydraw;
+	t_symbol *name = atom_getsymbolarg(0, argc, argv);
+	size = atom_getfloatarg(1, argc, argv);
+	fflags = atom_getfloatarg(2, argc, argv);
+	otherflag = atom_getfloatarg(3, argc, argv);
+	xdraw = atom_getfloatarg(4, argc, argv);
+	ydraw = atom_getfloatarg(5, argc, argv);
+
     t_glist *gl;
     t_garray *a;
     int flags = fflags;
@@ -383,9 +391,11 @@ void glist_arraydialog(t_glist *parent, t_symbol *name, t_floatarg size,
         size = 1;
     if (otherflag == 0 || (!(gl = glist_findgraph(parent))))
         gl = glist_addglist(parent, &s_, 0, 1,
-            (size > 1 ? size-1 : size), -1, 0, 0, 0, 0);
+            (size > 1 ? size-1 : size), -1, xdraw+30, ydraw+30, xdraw+30+GLIST_DEFGRAPHWIDTH, ydraw+30+GLIST_DEFGRAPHHEIGHT);
     a = graph_array(gl, sharptodollar(name), &s_float, size, flags);
     canvas_dirty(parent, 1);
+	canvas_redraw(glist_getcanvas(parent));
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)glist_getcanvas(parent));
 }
 
     /* this is called from the properties dialog window for an existing array */
@@ -1069,6 +1079,7 @@ t_widgetbehavior garray_widgetbehavior =
     garray_delete,
     garray_vis,
     garray_click,
+	NULL,
 };
 
 /* ----------------------- public functions -------------------- */
diff --git a/src/g_bang.c b/src/g_bang.c
index 8dd1127c6..aebd1d832 100644
--- a/src/g_bang.c
+++ b/src/g_bang.c
@@ -25,7 +25,9 @@
 #include <io.h>
 #endif
 
-
+extern int gfxstub_haveproperties(void *key);
+void bng_draw_select(t_bng* x, t_glist* glist);
+ 
 /* --------------- bng     gui-bang ------------------------- */
 
 t_widgetbehavior bng_widgetbehavior;
@@ -33,14 +35,8 @@ static t_class *bng_class;
 
 /*  widget helper functions  */
 
-
 void bng_draw_update(t_bng *x, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("bng_draw_update");
-        return;
-    }
     if(glist_isvisible(glist))
     {
         sys_vgui(".x%lx.c itemconfigure %lxBUT -fill #%6.6x\n", glist_getcanvas(glist), x,
@@ -54,30 +50,52 @@ void bng_draw_new(t_bng *x, t_glist *glist)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE\n",
-             canvas, xpos, ypos,
-             xpos + x->x_gui.x_w, ypos + x->x_gui.x_h,
-             x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create oval %d %d %d %d -fill #%6.6x -tags %lxBUT\n",
-             canvas, xpos+1, ypos+1,
-             xpos + x->x_gui.x_w-1, ypos + x->x_gui.x_h-1,
-             x->x_flashed?x->x_gui.x_fcol:x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xpos+x->x_gui.x_ldx,
-             ypos+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-			 x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xpos,
-             ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
-             ypos + x->x_gui.x_h, x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xpos, ypos,
-             xpos + IOWIDTH, ypos+1, x, 0);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE %lxBNG}\n",
+		         canvas, xpos, ypos,
+		         xpos + x->x_gui.x_w, ypos + x->x_gui.x_h,
+		         x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create oval %d %d %d %d -fill #%6.6x -tags {%lxBUT %lxBNG}\n",
+		         canvas, xpos+1, ypos+1,
+		         xpos + x->x_gui.x_w-1, ypos + x->x_gui.x_h-1,
+		         x->x_flashed?x->x_gui.x_fcol:x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxBNG}\n",
+		         canvas, xpos+x->x_gui.x_ldx,
+		         ypos+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+				 x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able) {
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxBNG}\n",
+		         canvas, xpos,
+		         ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
+		         ypos + x->x_gui.x_h, nlet_tag, 0, x);
+		}
+		if(!x->x_gui.x_fsf.x_rcv_able) {
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxBNG}\n",
+		         canvas, xpos, ypos,
+		         xpos + IOWIDTH, ypos+1, nlet_tag, 0, x);
+		}
+	//}
 }
 
 void bng_draw_move(t_bng *x, t_glist *glist)
@@ -86,47 +104,79 @@ void bng_draw_move(t_bng *x, t_glist *glist)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
-             canvas, x, xpos, ypos,
-             xpos + x->x_gui.x_w, ypos + x->x_gui.x_h);
-    sys_vgui(".x%lx.c coords %lxBUT %d %d %d %d\n",
-             canvas, x, xpos+1,ypos+1,
-             xpos + x->x_gui.x_w-1, ypos + x->x_gui.x_h-1);
-    sys_vgui(".x%lx.c itemconfigure %lxBUT -fill #%6.6x\n", canvas, x,
-             x->x_flashed?x->x_gui.x_fcol:x->x_gui.x_bcol);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0, xpos,
-             ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
-             ypos + x->x_gui.x_h);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0, xpos, ypos,
-             xpos + IOWIDTH, ypos+1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
+		         canvas, x, xpos, ypos,
+		         xpos + x->x_gui.x_w, ypos + x->x_gui.x_h);
+		sys_vgui(".x%lx.c coords %lxBUT %d %d %d %d\n",
+		         canvas, x, xpos+1,ypos+1,
+		         xpos + x->x_gui.x_w-1, ypos + x->x_gui.x_h-1);
+		sys_vgui(".x%lx.c itemconfigure %lxBUT -fill #%6.6x\n", canvas, x,
+		         x->x_flashed?x->x_gui.x_fcol:x->x_gui.x_bcol);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xpos,
+		         ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
+		         ypos + x->x_gui.x_h);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xpos, ypos,
+		         xpos + IOWIDTH, ypos+1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected)
+			bng_draw_select(x, x->x_gui.x_glist);
+	}
 }
 
 void bng_draw_erase(t_bng* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
-
+	sys_vgui(".x%lx.c delete %lxBNG\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxBNG\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+/*
     sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxBUT\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
     if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
+        sys_vgui(".x%lx.c delete %so%d\n", canvas, rtext_gettag(yy), 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+        sys_vgui(".x%lx.c delete %si%d\n", canvas, rtext_gettag(yy), 0);
+*/
 }
 
 void bng_draw_config(t_bng* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol);
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
     sys_vgui(".x%lx.c itemconfigure %lxBASE -fill #%6.6x\n", canvas, x, x->x_gui.x_bcol);
     sys_vgui(".x%lx.c itemconfigure %lxBUT -fill #%6.6x\n", canvas, x,
@@ -139,36 +189,196 @@ void bng_draw_io(t_bng* x, t_glist* glist, int old_snd_rcv_flags)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xpos,
-             ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
-             ypos + x->x_gui.x_h, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xpos, ypos,
-             xpos + IOWIDTH, ypos+1, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas, xpos,
+		         ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
+		         ypos + x->x_gui.x_h, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas, xpos, ypos,
+		         xpos + IOWIDTH, ypos+1, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+	}
 }
 
 void bng_draw_select(t_bng* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline $select_color\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxBUT -outline $select_color\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxBNG}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxBNG\n", canvas, x);
+		}
+		else
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
+		    sys_vgui(".x%lx.c itemconfigure %lxBUT -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+			sys_vgui(".x%lx.c dtag %lxBNG selected\n", canvas, x);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void bng__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_bng *x = (t_bng *)(sh->h_master);
 
-    if(x->x_gui.x_fsf.x_selected)
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxBUT -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			if (sh->h_dragx > sh->h_dragy)
+				sh->h_dragx = sh->h_dragy;
+			else sh->h_dragy = sh->h_dragx;
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_w < SCALE_BNG_MINWIDTH)
+				x->x_gui.x_w = SCALE_BNG_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_h < SCALE_BNG_MINHEIGHT)
+				x->x_gui.x_h = SCALE_BNG_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			bng_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
+    {
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + x->x_gui.x_w,
+					x->x_gui.x_obj.te_ypix + x->x_gui.x_h, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
+    }
+    sh->h_dragon = newstate;
+}
+
+static void bng__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
-        sys_vgui(".x%lx.c itemconfigure %lxBUT -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+		t_bng *x = (t_bng *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+
+		if (dx > dy) {
+			dx = dy;
+			x->x_gui.scale_offset_x = x->x_gui.scale_offset_y;
+		}
+		else {
+			dy = dx;
+			x->x_gui.scale_offset_y = x->x_gui.scale_offset_x;
+		}
+
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_w - x->x_gui.scale_offset_x + dx;
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h - x->x_gui.scale_offset_y + dy;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_BNG_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_BNG_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_BNG_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_BNG_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix, newx, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
     }
 }
 
@@ -325,6 +535,8 @@ static void bng_bang2(t_bng *x)/*wird immer gesendet, wenn moeglich*/
 
 static void bng_dialog(t_bng *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int a = (int)atom_getintarg(0, argc, argv);
     int fthold = (int)atom_getintarg(2, argc, argv);
@@ -338,6 +550,15 @@ static void bng_dialog(t_bng *x, t_symbol *s, int argc, t_atom *argv)
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_IO + sr_flags);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		bng_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void bng_click(t_bng *x, t_floatarg xpos, t_floatarg ypos, t_floatarg shift, t_floatarg ctrl, t_floatarg alt)
@@ -510,6 +731,21 @@ static void *bng_new(t_symbol *s, int argc, t_atom *argv)
     x->x_clock_brk = clock_new(x, (t_method)bng_tick_brk);
     x->x_clock_lck = clock_new(x, (t_method)bng_tick_lck);
     outlet_new(&x->x_gui.x_obj, &s_bang);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -521,6 +757,13 @@ static void bng_ff(t_bng *x)
     clock_free(x->x_clock_brk);
     clock_free(x->x_clock_hld);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_bang_setup(void)
@@ -549,6 +792,14 @@ void g_bang_setup(void)
     class_addmethod(bng_class, (t_method)bng_label_pos, gensym("label_pos"), A_GIMME, 0);
     class_addmethod(bng_class, (t_method)bng_label_font, gensym("label_font"), A_GIMME, 0);
     class_addmethod(bng_class, (t_method)bng_init, gensym("init"), A_FLOAT, 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)bng__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)bng__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     bng_widgetbehavior.w_getrectfn = bng_getrect;
     bng_widgetbehavior.w_displacefn = iemgui_displace;
     bng_widgetbehavior.w_selectfn = iemgui_select;
@@ -556,6 +807,7 @@ void g_bang_setup(void)
     bng_widgetbehavior.w_deletefn = iemgui_delete;
     bng_widgetbehavior.w_visfn = iemgui_vis;
     bng_widgetbehavior.w_clickfn = bng_newclick;
+    bng_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(bng_class, &bng_widgetbehavior);
     class_sethelpsymbol(bng_class, gensym("bng"));
     class_setsavefn(bng_class, bng_save);
diff --git a/src/g_canvas.c b/src/g_canvas.c
index 3386ef808..14101ec8a 100644
--- a/src/g_canvas.c
+++ b/src/g_canvas.c
@@ -13,6 +13,31 @@ to be different but are now unified except for some fossilized names.) */
 #include "g_canvas.h"
 #include <string.h>
 #include "g_all_guis.h"
+#include "g_magicglass.h"
+
+// jsarlo
+typedef struct _magicGlass
+{
+    t_object x_obj;
+    t_object *x_connectedObj;
+    int x_connectedOutno;
+    int x_visible;
+    char x_string[4096];
+    char x_old_string[4096];
+    int x_x;
+    int x_y;
+    int x_c;
+    float x_sigF;
+    int x_dspOn;
+    int x_viewOn;
+    float x_maxSample;
+    int x_sampleCount;
+    t_clock *x_clearClock;
+	t_clock *x_flashClock;
+	unsigned int x_maxSize;
+	unsigned int x_issignal;
+};
+// end jsarlo
 
     /* LATER consider adding font size to this struct (see glist_getfont()) */
 struct _canvasenvironment
@@ -314,7 +339,6 @@ t_outconnect *linetraverser_next(t_linetraverser *t)
         t->tr_x21 = t->tr_y21 = t->tr_x22 = t->tr_y22 = 0;
         t->tr_lx1 = t->tr_ly1 = t->tr_lx2 = t->tr_ly2 = 0;
     }
-    
     return (rval);
 }
 
@@ -348,7 +372,11 @@ t_canvas *canvas_new(void *dummy, t_symbol *sel, int argc, t_atom *argv)
     int vis = 0, width = GLIST_DEFCANVASWIDTH, height = GLIST_DEFCANVASHEIGHT;
     int xloc = 0, yloc = GLIST_DEFCANVASYLOC;
     int font = (owner ? owner->gl_font : sys_defaultfont);
+
     glist_init(x);
+    // jsarlo
+    x->gl_magic_glass = magicGlass_new((int)x);
+    // end jsarlo
     x->gl_obj.te_type = T_OBJECT;
     if (!owner)
         canvas_addtolist(x);
@@ -485,9 +513,12 @@ t_glist *glist_addglist(t_glist *g, t_symbol *sym,
     }
     if (x1 == x2 || y1 == y2)
         x1 = 0, x2 = 100, y1 = 1, y2 = -1;
+	if (px1 != 0 && px2 == 0) px2 = px1 + GLIST_DEFGRAPHWIDTH;
+	if (py1 != 0 && py2 == py1) py2 = py1 + GLIST_DEFGRAPHHEIGHT;
     if (px1 >= px2 || py1 >= py2)
         px1 = 100, py1 = 20, px2 = 100 + GLIST_DEFGRAPHWIDTH,
             py2 = 20 + GLIST_DEFGRAPHHEIGHT;
+
     x->gl_name = sym;
     x->gl_x1 = x1;
     x->gl_x2 = x2;
@@ -512,13 +543,16 @@ t_glist *glist_addglist(t_glist *g, t_symbol *sym,
     if (!menu)
         pd_pushsym(&x->gl_pd);
     glist_add(g, &x->gl_gobj);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)glist_getcanvas(g));
     return (x);
 }
 
     /* call glist_addglist from a Pd message */
 void glist_glist(t_glist *g, t_symbol *s, int argc, t_atom *argv)
 {
-    t_symbol *sym = atom_getsymbolarg(0, argc, argv);   
+    t_symbol *sym = atom_getsymbolarg(0, argc, argv);
+	/* if we wish to put a graph where the mouse is we need to replace bogus name */
+	if (!strcmp(sym->s_name, "NULL")) sym = &s_;  
     t_float x1 = atom_getfloatarg(1, argc, argv);  
     t_float y1 = atom_getfloatarg(2, argc, argv);  
     t_float x2 = atom_getfloatarg(3, argc, argv);  
@@ -602,8 +636,9 @@ void canvas_reflecttitle(t_canvas *x)
         x, x->gl_dirty, canvas_getdir(x)->s_name, x->gl_name->s_name);
     sys_vgui("wm title .x%lx {%s%s}\n", x, x->gl_name->s_name, namebuf);
 #else
-    sys_vgui("wm title .x%lx {%s%c%s - %s}\n", 
-        x, x->gl_name->s_name, (x->gl_dirty? '*' : ' '), namebuf,
+	if(glist_istoplevel(x) || !x->gl_isgraph || x->gl_isgraph && x->gl_havewindow)
+	    sys_vgui("wm title .x%lx {%s%c%s - %s}\n", 
+	        x, x->gl_name->s_name, (x->gl_dirty? '*' : ' '), namebuf,
             canvas_getdir(x)->s_name);
 #endif
 }
@@ -669,6 +704,7 @@ void canvas_map(t_canvas *x, t_floatarg f)
         if (glist_isvisible(x))
         {
                 /* just clear out the whole canvas */
+			sys_vgui(".x%lx.c dtag all selected\n", x);
             sys_vgui(".x%lx.c delete all\n", x);
             x->gl_mapped = 0;
         }
@@ -681,6 +717,11 @@ void canvas_redraw(t_canvas *x)
     {
         canvas_map(x, 0);
         canvas_map(x, 1);
+		
+		/* now re-highlight our selection */
+	    t_selection *y;
+    	for (y = x->gl_editor->e_selection; y; y = y->sel_next)		
+			gobj_select(y->sel_what, x, 1);
     }
 }
 
@@ -734,6 +775,10 @@ void canvas_free(t_canvas *x)
 {
     t_gobj *y;
     int dspstate = canvas_suspend_dsp();
+    // jsarlo
+    if (x->gl_magic_glass)
+      magicGlass_free(x->gl_magic_glass);
+    // end jsarlo
     canvas_noundo(x);
     if (canvas_editing == x)
         canvas_editing = 0;
@@ -1158,6 +1203,12 @@ static void canvas_dodsp(t_canvas *x, int toplevel, t_signal **sp)
         obj_nsigoutlets(&x->gl_obj));
 
         /* find all the "dsp" boxes and add them to the graph */
+
+    // jsarlo
+    ob = &x->gl_magic_glass->x_obj;
+    if (ob)
+       ugen_add(dc, ob);  // this t_canvas could be an array, hence no gl_magic_glass
+    // end jsarlo
     
     for (y = x->gl_list; y; y = y->g_next)
         if ((ob = pd_checkobject(&y->g_pd)) && zgetfn(&y->g_pd, dspsym))
diff --git a/src/g_canvas.h b/src/g_canvas.h
index e36fb48b1..2501ebbd6 100644
--- a/src/g_canvas.h
+++ b/src/g_canvas.h
@@ -40,6 +40,7 @@ in future releases.  The public (stable) API is in m_pd.h. */
 extern "C" {
 #endif
 
+    
 /* --------------------- geometry ---------------------------- */
 #define IOWIDTH 7       /* width of an inlet/outlet in pixels */
 #define IOMIDDLE ((IOWIDTH-1)/2)
@@ -76,6 +77,11 @@ EXTERN_STRUCT _canvasenvironment;
 EXTERN_STRUCT _fielddesc;
 #define t_fielddesc struct _fielddesc
 
+// jsarlo
+EXTERN_STRUCT _magicGlass;
+#define t_magicGlass struct _magicGlass
+// end jsarlo
+
 typedef struct _selection
 {
     t_gobj *sel_what;
@@ -183,6 +189,10 @@ struct _glist
     unsigned int gl_goprect:1;      /* draw rectangle for graph-on-parent */
     unsigned int gl_isgraph:1;      /* show as graph on parent */
     unsigned int gl_hidetext:1;     /* hide object-name + args when doing graph on parent */
+	unsigned int gl_gop_initialized:1;     /* used for tagged moving of gop-ed objects to avoid redundant reinit */
+    // jsarlo
+    t_magicGlass *gl_magic_glass;   /* magic glass object */
+    // end jsarlo
 };
 
 #define gl_gobj gl_obj.te_g
@@ -262,6 +272,8 @@ typedef void (*t_visfn)(t_gobj *x, struct _glist *glist, int flag);
         /* field a mouse click (when not in "edit" mode) */
 typedef int (*t_clickfn)(t_gobj *x, struct _glist *glist,
     int xpix, int ypix, int shift, int alt, int dbl, int doit);
+        /* and this to displace a gobj using tags: */
+typedef void (*t_displacefnwtag)(t_gobj *x, struct _glist *glist, int dx, int dy);
         /* ... and later, resizing; getting/setting font or color... */
 
 struct _widgetbehavior
@@ -273,6 +285,7 @@ struct _widgetbehavior
     t_deletefn w_deletefn;
     t_visfn w_visfn;
     t_clickfn w_clickfn;
+	t_displacefnwtag w_displacefnwtag;
 };
 
 /* -------- behaviors for scalars defined by objects in template --------- */
@@ -393,8 +406,7 @@ EXTERN void glist_glist(t_glist *g, t_symbol *s, int argc, t_atom *argv);
 EXTERN t_glist *glist_addglist(t_glist *g, t_symbol *sym,
     t_float x1, t_float y1, t_float x2, t_float y2,
     t_float px1, t_float py1, t_float px2, t_float py2);
-EXTERN void glist_arraydialog(t_glist *parent, t_symbol *name,
-    t_floatarg size, t_floatarg saveit, t_floatarg newgraph);
+EXTERN void glist_arraydialog(t_glist *parent, t_symbol *s, int argc, t_atom *argv);
 EXTERN t_binbuf *glist_writetobinbuf(t_glist *x, int wholething);
 EXTERN int glist_isgraph(t_glist *x);
 EXTERN void glist_redraw(t_glist *x);
@@ -411,6 +423,8 @@ extern int glist_amreloadingabstractions; /* stop GUI changes while reloading */
 EXTERN void text_setto(t_text *x, t_glist *glist, char *buf, int bufsize);
 EXTERN void text_drawborder(t_text *x, t_glist *glist, char *tag,
     int width, int height, int firsttime);
+EXTERN void text_drawborder_withtag(t_text *x, t_glist *glist, char *tag,
+    int width, int height, int firsttime);
 EXTERN void text_eraseborder(t_text *x, t_glist *glist, char *tag);
 EXTERN int text_xcoord(t_text *x, t_glist *glist);
 EXTERN int text_ycoord(t_text *x, t_glist *glist);
diff --git a/src/g_editor.c b/src/g_editor.c
index 7545bf78a..b548255c0 100644
--- a/src/g_editor.c
+++ b/src/g_editor.c
@@ -9,6 +9,7 @@
 #include "s_stuff.h"
 #include "g_canvas.h"
 #include <string.h>
+#include "g_magicglass.h"
 
 void glist_readfrombinbuf(t_glist *x, t_binbuf *b, char *filename,
     int selectem);
@@ -16,6 +17,8 @@ void glist_readfrombinbuf(t_glist *x, t_binbuf *b, char *filename,
 void open_via_helppath(const char *name, const char *dir);
 char *class_gethelpdir(t_class *c);
 
+//static int toggle_moving = 0; //global variable
+
 /* ------------------ forward declarations --------------- */
 static void canvas_doclear(t_canvas *x);
 static void glist_setlastxy(t_glist *gl, int xval, int yval);
@@ -28,7 +31,60 @@ static t_binbuf *copy_binbuf;
 static char *canvas_textcopybuf;
 static int canvas_textcopybufsize;
 static t_glist *glist_finddirty(t_glist *x);
+static void canvas_reselect(t_canvas *x);
+static void canvas_cut(t_canvas *x);
+static void canvas_undo(t_canvas *x);
 static int paste_xyoffset = 0; /* a counter of pastes to make x,y offsets */
+static void canvas_mouseup_gop(t_canvas *x, t_gobj *g);
+
+// jsarlo
+static char canvas_cnct_inlet_tag[4096];
+static char canvas_cnct_outlet_tag[4096];
+static int outlet_issignal = 0;
+static int inlet_issignal = 0;
+static int last_inlet_filter = 0;
+static int last_outlet_filter = 0;
+struct _outlet
+{
+    t_object *o_owner;
+    struct _outlet *o_next;
+    t_outconnect *o_connections;
+    t_symbol *o_sym;
+};
+// end jsarlo
+
+/* used for new duplicate behavior where we can "duplicate" into new window */
+static t_canvas *c_selection;
+
+/* iemgui uses black inlets and outlets while default objects use gray ones
+   add here more as necessary */
+int gobj_filter_highlight_behavior(t_rtext *y) {
+
+	char *buf;
+	char name[4];
+	int bufsize, i;
+	rtext_gettext(y, &buf, &bufsize);
+	for (i = 0; i < 3; i++) {
+		name[i] = buf[i];
+	}
+	name[3]='\0';
+	//fprintf(stderr,"object name = >%s<\n", name);
+	if (!strcmp(name, "bng") ||
+		!strcmp(name, "nbx") ||
+		!strcmp(name, "hdl") ||
+		!strcmp(name, "hsl") ||
+		!strcmp(name, "tgl") ||
+		!strcmp(name, "vdl") ||
+		!strcmp(name, "vsl") ||
+		!strcmp(name, "vu ") ||
+		/* alternative names for hradio and vradio when invoked from the menu */
+		!strcmp(name, "hra") ||
+		!strcmp(name, "vra")
+		)
+		return 1;
+
+	return 0;
+}
 
 /* ---------------- generic widget behavior ------------------------- */
 
@@ -45,6 +101,12 @@ void gobj_displace(t_gobj *x, t_glist *glist, int dx, int dy)
         (*x->g_pd->c_wb->w_displacefn)(x, glist, dx, dy);
 }
 
+void gobj_displace_withtag(t_gobj *x, t_glist *glist, int dx, int dy)
+{
+    if (x->g_pd->c_wb && x->g_pd->c_wb->w_displacefnwtag)
+        (*x->g_pd->c_wb->w_displacefnwtag)(x, glist, dx, dy);
+}
+
 void gobj_select(t_gobj *x, t_glist *glist, int state)
 {
     if (x->g_pd->c_wb && x->g_pd->c_wb->w_selectfn)
@@ -81,6 +143,8 @@ int gobj_shouldvis(t_gobj *x, struct _glist *glist)
         if (gx1 < x1 || gx1 > x2 || gx2 < x1 || gx2 > x2 ||
             gy1 < y1 || gy1 > y2 || gy2 < y1 || gy2 > y2)
                 return (0);
+		if (glist==glist_getcanvas(glist))
+        	sys_vgui(".x%lx.c raise all_cords\n", glist_getcanvas(glist));
     }
     if (ob = pd_checkobject(&x->g_pd))
     {
@@ -127,8 +191,9 @@ void glist_selectline(t_glist *x, t_outconnect *oc, int index1,
         x->gl_editor->e_selectline_tag = oc;
         sys_vgui(".x%lx.c itemconfigure l%lx -fill $select_color\n",
             x, x->gl_editor->e_selectline_tag);
-        sys_vgui(".x%lx.c raise l%lx\n",
-            x, x->gl_editor->e_selectline_tag);
+        sys_vgui(".x%lx.c addtag selected withtag l%lx\n",
+            glist_getcanvas(x), x->gl_editor->e_selectline_tag);
+		c_selection = x;
     }    
 }
 
@@ -151,6 +216,8 @@ void glist_deselectline(t_glist *x)
         sys_vgui(".x%lx.c itemconfigure l%lx -fill %s\n",
             x, x->gl_editor->e_selectline_tag,
             (issignal ? "$signal_cord" : "$msg_cord"));
+        sys_vgui(".x%lx.c dtag l%lx selected\n",
+            glist_getcanvas(x), glist_getcanvas(x)->gl_editor->e_selectline_tag);
     }    
 }
 
@@ -179,6 +246,7 @@ void glist_select(t_glist *x, t_gobj *y)
         sel->sel_what = y;
         x->gl_editor->e_selection = sel;
         gobj_select(y, x, 1);
+		c_selection = x;
     }
 }
 
@@ -199,6 +267,7 @@ static void glist_checkanddeselectall(t_glist *gl, t_gobj *g)
     /* call this for selected objects only */
 void glist_deselect(t_glist *x, t_gobj *y)
 {
+	//fprintf(stderr, "deselect\n");
     int fixdsp = 0;
     static int reenter = 0;
     /* if (reenter) return; */
@@ -210,11 +279,14 @@ void glist_deselect(t_glist *x, t_gobj *y)
         if (!glist_isselected(x, y)) bug("glist_deselect");
         if (x->gl_editor->e_textedfor)
         {
+			//fprintf(stderr, "e_textedfor\n");
             t_rtext *fuddy = glist_findrtext(x, (t_text *)y);
             if (x->gl_editor->e_textedfor == fuddy)
             {
+				//fprintf(stderr, "e_textedfor == fuddy\n");
                 if (x->gl_editor->e_textdirty)
                 {
+					//fprintf(stderr, "textdirty yes\n");
                     z = fuddy;
                     canvas_stowconnections(glist_getcanvas(x));
                     glist_checkanddeselectall(x, y);
@@ -246,6 +318,7 @@ void glist_deselect(t_glist *x, t_gobj *y)
         }
         if (z)
         {
+			//fprintf(stderr, "setto\n");
             char *buf;
             int bufsize;
 
@@ -268,6 +341,7 @@ void glist_noselect(t_glist *x)
             glist_deselect(x, x->gl_editor->e_selection->sel_what);
         if (x->gl_editor->e_selectedline)
             glist_deselectline(x);
+		c_selection = NULL;
     }
 }
 
@@ -292,6 +366,7 @@ void glist_selectall(t_glist *x)
                 gobj_select(y, x, 1);
             }
             sel->sel_next = 0;
+			c_selection = x;
         }
     }
 }
@@ -379,12 +454,13 @@ static void canvas_undo(t_canvas *x)
         bug("canvas_undo 2");
     else
     {
-        /* post("undo"); */
+        //fprintf(stderr,"undo\n");
         (*canvas_undo_fn)(canvas_undo_canvas, canvas_undo_buf, UNDO_UNDO);
             /* enable redo in menu */
         if (glist_isvisible(x) && glist_istoplevel(x))
             sys_vgui("pdtk_undomenu .x%lx no %s\n", x, canvas_undo_name);
         canvas_undo_whatnext = UNDO_REDO;
+		sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
     }
 }
 
@@ -402,6 +478,7 @@ static void canvas_redo(t_canvas *x)
         if (glist_isvisible(x) && glist_istoplevel(x))
             sys_vgui("pdtk_undomenu .x%lx %s no\n", x, canvas_undo_name);
         canvas_undo_whatnext = UNDO_UNDO;
+		sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
     }
 }
 
@@ -440,6 +517,12 @@ void canvas_disconnect(t_canvas *x,
             sinkno == index2 && t.tr_inno == inno)
         {
             sys_vgui(".x%lx.c delete l%lx\n", x, oc);
+            // jsarlo
+			if(x->gl_magic_glass) {
+            	magicGlass_unbind(x->gl_magic_glass);
+            	magicGlass_hide(x->gl_magic_glass);
+			}
+            // end jsarlo
             obj_disconnect(t.tr_ob, t.tr_outno, t.tr_ob2, t.tr_inno);
             break;
         }
@@ -546,12 +629,17 @@ static void canvas_undo_cut(t_canvas *x, void *z, int action)
     int mode = buf->u_mode;
     if (action == UNDO_UNDO)
     {
-        if (mode == UCUT_CUT)
+        if (mode == UCUT_CUT) {
+			//fprintf(stderr, "UCUT_CUT\n");
             canvas_dopaste(x, copy_binbuf);
-        else if (mode == UCUT_CLEAR)
+		}
+        else if (mode == UCUT_CLEAR) {
+			//fprintf(stderr, "UCUT_CLEAR\n");
             canvas_dopaste(x, buf->u_objectbuf);
+		}
         else if (mode == UCUT_TEXT)
         {
+			//fprintf(stderr, "UCUT_TEXT\n");
             t_gobj *y1, *y2;
             glist_noselect(x);
             for (y1 = x->gl_list; y2 = y1->g_next; y1 = y2)
@@ -726,9 +814,10 @@ else if (action == UNDO_FREE)
 static void glist_doreload(t_glist *gl, t_symbol *name, t_symbol *dir,
     t_gobj *except)
 {
+	//fprintf(stderr,"doreload\n");
     t_gobj *g;
     int i, nobj = glist_getindex(gl, 0);  /* number of objects */
-    int hadwindow = (gl->gl_editor != 0);
+    int hadwindow = gl->gl_havewindow;
     for (g = gl->gl_list, i = 0; g && i < nobj; i++)
     {
         if (g != except && pd_class(&g->g_pd) == canvas_class &&
@@ -740,11 +829,10 @@ static void glist_doreload(t_glist *gl, t_symbol *name, t_symbol *dir,
                 Get its index here, and afterward restore g.  Also, the
                 replacement will be at the end of the list, so we don't
                 do g = g->g_next in this case. */
+			//fprintf(stderr, "rebuildlicious\n");
             int j = glist_getindex(gl, g);
-            if (!gl->gl_editor)
-                canvas_vis(gl, 1);
-            if (!gl->gl_editor)
-                bug("editor");
+            if (!gl->gl_havewindow)
+                canvas_vis(glist_getcanvas(gl), 1);
             glist_noselect(gl);
             glist_select(gl, g);
             canvas_setundo(gl, canvas_undo_cut,
@@ -758,10 +846,10 @@ static void glist_doreload(t_glist *gl, t_symbol *name, t_symbol *dir,
         {
             if (g != except && pd_class(&g->g_pd) == canvas_class)
                 glist_doreload((t_canvas *)g, name, dir, except);
-             g = g->g_next;
+             	g = g->g_next;
         }
     }
-    if (!hadwindow && gl->gl_editor)
+    if (!hadwindow && gl->gl_havewindow)
         canvas_vis(glist_getcanvas(gl), 0);
 }
 
@@ -782,6 +870,106 @@ void canvas_reload(t_symbol *name, t_symbol *dir, t_gobj *except)
     canvas_resume_dsp(dspwas);
 }
 
+/* --------- 5. apply  ----------- */
+
+typedef struct _undo_apply        
+{
+    t_binbuf *u_objectbuf;      /* the object cleared or typed into */
+    t_binbuf *u_reconnectbuf;   /* connections into and out of object */
+	int u_index;				/* index of the previous object */
+} t_undo_apply;
+
+static void *canvas_undo_set_apply(t_canvas *x, t_gobj *obj)
+{
+    t_undo_apply *buf;
+    t_gobj *y;
+    t_linetraverser t;
+    t_outconnect *oc;
+	/* select the object we are working on */
+	if (!glist_isselected(x, obj))
+		glist_select(x, obj);
+    int nnotsel= glist_selectionindex(x, 0, 0); /* get number of all items for the offset below */
+    buf = (t_undo_apply *)getbytes(sizeof(*buf));
+
+    /* store connections into/out of the selection */
+    buf->u_reconnectbuf = binbuf_new();
+    linetraverser_start(&t, x);
+    while (oc = linetraverser_next(&t))
+    {
+        int issel1 = glist_isselected(x, &t.tr_ob->ob_g);
+        int issel2 = glist_isselected(x, &t.tr_ob2->ob_g);
+        if (issel1 != issel2)
+        {
+            binbuf_addv(buf->u_reconnectbuf, "ssiiii;",
+                gensym("#X"), gensym("connect"),
+                (issel1 ? nnotsel : 0)
+                    + glist_selectionindex(x, &t.tr_ob->ob_g, issel1),
+                t.tr_outno,
+                (issel2 ? nnotsel : 0) +
+                    glist_selectionindex(x, &t.tr_ob2->ob_g, issel2),
+                t.tr_inno);
+        }
+    }
+	/* copy object in its current state */
+    buf->u_objectbuf = canvas_docopy(x);
+
+	/* store index of the currently selected object */
+    t_selection *sel = x->gl_editor->e_selection;
+	t_gobj *tgt = sel->sel_what;
+	int index = 0;
+	for (y = x->gl_list; y; y = y->g_next) {
+		if (y == tgt) {
+			buf->u_index = index;
+			break;
+		}
+		index++;
+	}
+
+    return (buf);
+}
+
+static void canvas_undo_apply(t_canvas *x, void *z, int action)
+{
+    t_undo_apply *buf = z;
+    if (action == UNDO_UNDO || action == UNDO_REDO)
+    {
+		/* find current instance */
+		glist_noselect(x);
+		glist_select(x, glist_nth(x, buf->u_index));
+
+		/* copy it for the new undo/redo */
+		t_binbuf *tmp = canvas_docopy(x);
+
+		/* delete current instance */
+		canvas_doclear(x);
+
+		/* replace it with previous instance */
+        canvas_dopaste(x, buf->u_objectbuf);
+
+		/* change previous instance with current one */
+		buf->u_objectbuf = tmp;
+		buf->u_index = glist_selectionindex(x, 0, 0);
+
+		/* connections should stay the same */
+        pd_bind(&x->gl_pd, gensym("#X"));
+        binbuf_eval(buf->u_reconnectbuf, 0, 0, 0);
+        pd_unbind(&x->gl_pd, gensym("#X"));
+    }
+    else if (action == UNDO_FREE)
+    {
+        if (buf->u_objectbuf)
+            binbuf_free(buf->u_objectbuf);
+        if (buf->u_reconnectbuf)
+            binbuf_free(buf->u_reconnectbuf);
+        t_freebytes(buf, sizeof(*buf));
+    }
+}
+
+void canvas_apply_setundo(t_canvas *x, t_gobj *y)
+{
+	canvas_setundo(x, canvas_undo_apply, canvas_undo_set_apply(x, y), "apply");
+}
+
 /* ------------------------ event handling ------------------------ */
 
 static char *cursorlist[] = {
@@ -861,11 +1049,15 @@ static t_gobj *canvas_findhitbox(t_canvas *x, int xpos, int ypos,
     /* right-clicking on a canvas object pops up a menu. */
 static void canvas_rightclick(t_canvas *x, int xpos, int ypos, t_gobj *y)
 {
-    int canprop, canopen;
+    int canprop, canopen, isobject;
     canprop = (!y || (y && class_getpropertiesfn(pd_class(&y->g_pd))));
     canopen = (y && zgetfn(&y->g_pd, gensym("menu-open")));
-    sys_vgui("pdtk_canvas_popup .x%lx %d %d %d %d\n",
-        x, xpos, ypos, canprop, canopen);
+	if (y) {
+		isobject = 1;
+	}
+	else isobject = 0;
+    sys_vgui("pdtk_canvas_popup .x%lx %d %d %d %d %d\n",
+        x, xpos, ypos, canprop, canopen, isobject);
 }
 
 /* ----  editors -- perhaps this and "vis" should go to g_editor.c ------- */
@@ -910,14 +1102,19 @@ void canvas_destroy_editor(t_glist *x)
 {
     t_gobj *y;
     t_object *ob;
+	glist_noselect(x);
     if (x->gl_editor)
     {
-        for (y = x->gl_list; y; y = y->g_next)
-            if (ob = pd_checkobject(&y->g_pd))
-                rtext_free(glist_findrtext(x, ob));
-        editor_free(x->gl_editor, x);
-        x->gl_editor = 0;
-    }
+		if (x->gl_list) {
+        	for (y = x->gl_list; y; y = y->g_next)
+        	    if (ob = pd_checkobject(&y->g_pd))
+        	        rtext_free(glist_findrtext(x, ob));
+		}
+		if (x->gl_editor) {
+			editor_free(x->gl_editor, x);
+			x->gl_editor = 0;
+		}
+	}
 }
 
 void canvas_reflecttitle(t_canvas *x);
@@ -930,17 +1127,24 @@ void canvas_vis(t_canvas *x, t_floatarg f)
 {
     char buf[30];
     int flag = (f != 0);
+    if (x != glist_getcanvas(x))
+        bug("canvas_vis");
     if (flag)
     {
-        /* If a subpatch/abstraction has GOP/gl_isgraph set, then it will have
-         * a gl_editor already, if its not, it will not have a gl_editor.
-         * canvas_create_editor(x) checks if a gl_editor is already created,
-         * so its ok to run it on a canvas that already has a gl_editor. */
-        if (x->gl_editor && x->gl_havewindow)
+        /* post("havewindow %d, isgraph %d, isvisible %d  editor %d",
+            x->gl_havewindow, x->gl_isgraph, glist_isvisible(x),
+                (x->gl_editor != 0)); */
+            /* test if we're already visible and toplevel */
+        if (x->gl_editor)
         {           /* just put us in front */
-            sys_vgui("wm deiconify .x%lx\n", x);  
+#ifdef MSW
+            canvas_vis(x, 0);
+            canvas_vis(x, 1);
+#else
             sys_vgui("raise .x%lx\n", x);
             sys_vgui("focus .x%lx.c\n", x);
+            sys_vgui("wm deiconify .x%lx\n", x);  
+#endif
         }
         else
         {
@@ -978,7 +1182,7 @@ void canvas_vis(t_canvas *x, t_floatarg f)
         sys_vgui("destroy .x%lx\n", x);
         for (i = 1, x2 = x; x2; x2 = x2->gl_next, i++)
             ;
-        sys_vgui(".mbar.find delete %d\n", i);
+        //sys_vgui(".mbar.find delete %d\n", i);
             /* if we're a graph on our parent, and if the parent exists
                and is visible, show ourselves on parent. */
         if (glist_isgraph(x) && x->gl_owner)
@@ -1002,11 +1206,12 @@ void canvas_setgraph(t_glist *x, int flag, int nogoprect)
     if (!flag && glist_isgraph(x))
     {
         int hadeditor = (x->gl_editor != 0);
-        if (hadeditor)
-            canvas_destroy_editor(x);
         if (x->gl_owner && !x->gl_loading && glist_isvisible(x->gl_owner))
             gobj_vis(&x->gl_gobj, x->gl_owner, 0);
+        if (hadeditor)
+            canvas_destroy_editor(x);
         x->gl_isgraph = 0;
+		x->gl_hidetext = 0;
         if (x->gl_owner && !x->gl_loading && glist_isvisible(x->gl_owner))
         {
             gobj_vis(&x->gl_gobj, x->gl_owner, 1);
@@ -1027,13 +1232,8 @@ void canvas_setgraph(t_glist *x, int flag, int nogoprect)
         x->gl_hidetext = !(!(flag&2));
         if (!nogoprect && !x->gl_goprect)
         {
-            t_gobj *g;
-            for (g = x->gl_list; g; g = g->g_next)
-                if (pd_checkobject(&g->g_pd))
-            {
-                x->gl_goprect = 1;
-                break;
-            }
+			/* Ivica Ico Bukvic 5/16/10 <ico@bukvic.net> */
+			x->gl_goprect = 1;
         }
         if (glist_isvisible(x) && x->gl_goprect)
             glist_redraw(x);
@@ -1045,7 +1245,7 @@ void canvas_setgraph(t_glist *x, int flag, int nogoprect)
     }
 }
 
-void garray_properties(t_garray *x);
+void garray_properties(t_garray *x, t_glist *canvas);
 
     /* tell GUI to create a properties dialog on the canvas.  We tell
     the user the negative of the "pixel" y scale to make it appear to grow
@@ -1073,7 +1273,7 @@ void canvas_properties(t_glist *x)
         /* if any arrays are in the graph, put out their dialogs too */
     for (y = x->gl_list; y; y = y->g_next)
         if (pd_class(&y->g_pd) == garray_class) 
-            garray_properties((t_garray *)y);
+            garray_properties((t_garray *)y, x);
 }
 
     /* called from the gui when "OK" is selected on the canvas properties
@@ -1082,7 +1282,6 @@ static void canvas_donecanvasdialog(t_glist *x,
     t_symbol *s, int argc, t_atom *argv)
 {
 
-
     t_float xperpix, yperpix, x1, y1, x2, y2, xpix, ypix, xmargin, ymargin; 
     int graphme, redraw = 0;
 
@@ -1146,23 +1345,44 @@ static void canvas_donecanvasdialog(t_glist *x,
         /* LATER avoid doing 2 redraws here (possibly one inside setgraph) */
     canvas_setgraph(x, graphme, 0);
     canvas_dirty(x, 1);
-    if (x->gl_havewindow)
+    if (x->gl_havewindow) {
         canvas_redraw(x);
+	}
     else if (glist_isvisible(x->gl_owner))
     {
+		glist_noselect(x);
         gobj_vis(&x->gl_gobj, x->gl_owner, 0);
         gobj_vis(&x->gl_gobj, x->gl_owner, 1);
+		canvas_redraw(x->gl_owner);
     }
+	//ico@bukvic.net 100518 update scrollbars when GOP potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x);
+	//if gop is being disabled go one level up
+	if (!graphme) canvas=canvas->gl_owner;
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
     /* called from the gui when a popup menu comes back with "properties,"
         "open," or "help." */
+	/* Ivica Ico Bukvic <ico@bukvic.net> 2010-11-17
+	   also added "To Front" and "To Back" */
 static void canvas_done_popup(t_canvas *x, t_float which, t_float xpos, t_float ypos)
 {
     char pathbuf[FILENAME_MAX], namebuf[FILENAME_MAX];
     t_gobj *y;
     for (y = x->gl_list; y; y = y->g_next)
     {
+		/* if we are sending "to back" we need to select all objects
+		   but the one originally selected */
+		if (which == 4) /* to back */
+		{
+			if (!x->gl_edit)
+				x->gl_edit = !x->gl_edit;
+			if (glist_isselected(x, y))
+				glist_deselect(x, y);
+			else if (!glist_isselected(x, y))
+				glist_select(x, y);
+		}
         int x1, y1, x2, y2;
         if (canvas_hitbox(x, y, xpos, ypos, &x1, &y1, &x2, &y2))
         {
@@ -1170,7 +1390,12 @@ static void canvas_done_popup(t_canvas *x, t_float which, t_float xpos, t_float
             {
                 if (!class_getpropertiesfn(pd_class(&y->g_pd)))
                     continue;
-                (*class_getpropertiesfn(pd_class(&y->g_pd)))(y, x);
+				else {
+					if (!x->gl_edit)
+						canvas_editmode(x, 1);
+					glist_select(x, y);
+                	(*class_getpropertiesfn(pd_class(&y->g_pd)))(y, x);
+				}
                 return;
             }
             else if (which == 1)    /* open */
@@ -1180,7 +1405,7 @@ static void canvas_done_popup(t_canvas *x, t_float which, t_float xpos, t_float
                 vmess(&y->g_pd, gensym("menu-open"), "");
                 return;
             }
-            else    /* help */
+            else if (which == 2)   /* help */
             {
                 char *dir;
                 if (pd_class(&y->g_pd) == canvas_class &&
@@ -1205,8 +1430,41 @@ static void canvas_done_popup(t_canvas *x, t_float which, t_float xpos, t_float
                 open_via_helppath(namebuf, dir);
                 return;
             }
+			else if (which == 3) /* to front */
+			{
+				if (!x->gl_edit)
+					x->gl_edit = !x->gl_edit;
+				if (!glist_isselected(x, y))
+					glist_select(x, y);
+			}
+			else if (which == 4) /* to back */
+			{
+				/* if the item we are sending back is selected
+				   deselect it */
+				if (glist_isselected(x, y))
+					glist_deselect(x, y);
+			}
         }
     }
+	if (which == 3) /* to front */
+	{
+		/* now that all are selected */
+		canvas_cut(x);
+		canvas_undo(x);
+	}
+	if (which == 4) /* to back */
+	{
+		/* now that all are selected */
+		canvas_cut(x);
+		canvas_undo(x);
+		/* reselect the originally selected object(s) */
+		for (y = x->gl_list; y; y = y->g_next) {
+			if (glist_isselected(x, y))
+				glist_deselect(x, y);
+			else if (!glist_isselected(x, y))
+				glist_select(x, y);
+		}
+	}
     if (which == 0)
         canvas_properties(x);
     else if (which == 2)
@@ -1257,6 +1515,10 @@ void canvas_doclick(t_canvas *x, int xpos, int ypos, int which,
     x->gl_editor->e_lastmoved = 0;
     if (doit)
     {
+		if (x->gl_editor->e_onmotion == MA_MOVE) {		
+			//fprintf(stderr,"letting go of objects\n");
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+		}
         x->gl_editor->e_grab = 0;
         x->gl_editor->e_onmotion = MA_NONE;
     }
@@ -1267,6 +1529,7 @@ void canvas_doclick(t_canvas *x, int xpos, int ypos, int which,
 
     x->gl_editor->e_xwas = xpos;
     x->gl_editor->e_ywas = ypos;
+	//fprintf(stderr,"mouse %d %d\n", xpos, ypos);
 
     if (runmode && !rightclick)
     {
@@ -1340,8 +1603,43 @@ void canvas_doclick(t_canvas *x, int xpos, int ypos, int which,
                           ".x%lx.c create line %d %d %d %d -width %d -tags x\n",
                                 x, xpos, ypos, xpos, ypos,
                                     (issignal ? 2 : 1));
-                    }                                   
-                    else canvas_setcursor(x, CURSOR_EDITMODE_CONNECT);
+                    }   
+    	    	    else
+                    // jsarlo
+                    {
+               	        t_rtext *y = glist_findrtext(x, (t_text *)&ob->ob_g);
+
+                        if (canvas_cnct_outlet_tag[0] != 0)
+                        {
+                            sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                                   	x, canvas_cnct_outlet_tag,
+									(last_outlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+									(outlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                        }
+                        if (y)
+                        {
+							last_outlet_filter = gobj_filter_highlight_behavior(y);
+                            sprintf(canvas_cnct_outlet_tag, 
+                                    "%so%d",
+                                    rtext_gettag(y),
+                                    closest);
+                            sys_vgui(".x%x.c itemconfigure %s -outline $select_nlet_color -width $highlight_width\n",
+                                     x,
+                                     canvas_cnct_outlet_tag);
+                            sys_vgui(".x%x.c raise %s\n",
+                                     x,
+                                     canvas_cnct_outlet_tag);
+							outlet_issignal = obj_issignaloutlet(ob,closest);
+                        }
+                        // jsarlo
+						if(x->gl_magic_glass) {
+	                        magicGlass_unbind(x->gl_magic_glass);
+	                        magicGlass_hide(x->gl_magic_glass);
+						}
+                        // end jsarlo
+                        canvas_setcursor(x, CURSOR_EDITMODE_CONNECT);
+                    }
+                    // end jsarlo
                 }
                 else if (doit)
                     goto nooutletafterall;
@@ -1369,10 +1667,30 @@ void canvas_doclick(t_canvas *x, int xpos, int ypos, int which,
                         glist_noselect(x);
                         glist_select(x, y);
                     }
+					//toggle_moving = 1;
+					//sys_vgui("pdtk_update_xy_tooltip .x%lx %d %d\n", x, (int)xpos, (int)ypos);
+					//sys_vgui("pdtk_toggle_xy_tooltip .x%lx %d\n", x, 1);
                     x->gl_editor->e_onmotion = MA_MOVE;
                 }
             }
-            else canvas_setcursor(x, CURSOR_EDITMODE_NOTHING); 
+    	    else
+            // jsarlo 
+            {
+                if (canvas_cnct_outlet_tag[0] != 0)
+                {
+                    sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                           	x, canvas_cnct_outlet_tag,
+							(last_outlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+							(outlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                    canvas_cnct_outlet_tag[0] = 0;                  
+                }
+				if(x->gl_magic_glass) {              
+                	magicGlass_unbind(x->gl_magic_glass);
+                	magicGlass_hide(x->gl_magic_glass);
+				}
+                canvas_setcursor(x, CURSOR_EDITMODE_NOTHING); 
+    	    }
+            // end jsarlo
         }
         return;
     }
@@ -1398,6 +1716,11 @@ void canvas_doclick(t_canvas *x, int xpos, int ypos, int which,
         linetraverser_start(&t, glist2);
         while (oc = linetraverser_next(&t))
         {
+            // jsarlo
+            int parseOutno;
+            t_object *parseOb = NULL;
+            t_outlet *parseOutlet = NULL;
+            // end jsarlo
             t_float lx1 = t.tr_lx1, ly1 = t.tr_ly1,
                 lx2 = t.tr_lx2, ly2 = t.tr_ly2;
             t_float area = (lx2 - lx1) * (fy - ly1) -
@@ -1412,15 +1735,63 @@ void canvas_doclick(t_canvas *x, int xpos, int ypos, int which,
                     canvas_getindex(glist2, &t.tr_ob->ob_g), t.tr_outno,
                     canvas_getindex(glist2, &t.tr_ob2->ob_g), t.tr_inno);
             }
+            // jsarlo
+            parseOutno = t.tr_outno;
+            parseOb = t.tr_ob;
+            for (parseOutlet = parseOb->ob_outlet; 
+                 parseOutlet && parseOutno; 
+                 parseOutlet = parseOutlet->o_next, parseOutno--);
+            if (parseOutlet)
+            {
+                magicGlass_bind(x->gl_magic_glass,
+                                t.tr_ob,
+                                t.tr_outno); 
+                magicGlass_setDsp(x->gl_magic_glass,
+                                  obj_issignaloutlet(t.tr_ob, t.tr_outno));
+            }
+            magicGlass_moveText(x->gl_magic_glass, xpos, ypos); 
+            if (magicGlass_isOn(x->gl_magic_glass))
+                magicGlass_show(x->gl_magic_glass);
+            if (canvas_cnct_inlet_tag[0] != 0)
+            {
+				sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+		       			x, canvas_cnct_inlet_tag,
+						(last_inlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+						(inlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                canvas_cnct_inlet_tag[0] = 0;                  
+            }
+            if (canvas_cnct_outlet_tag[0] != 0)
+            {
+                sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                       	x, canvas_cnct_outlet_tag,
+						(last_outlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+						(outlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                canvas_cnct_outlet_tag[0] = 0;                  
+            }
+            // end jsarlo
             canvas_setcursor(x, CURSOR_EDITMODE_DISCONNECT);
             return;
         }
     }
+    // jsarlo
+    if (canvas_cnct_outlet_tag[0] != 0)
+    {
+        sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+               	x, canvas_cnct_outlet_tag,
+				(last_outlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+				(outlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+        canvas_cnct_outlet_tag[0] = 0;                  
+    }
+	if(x->gl_magic_glass) {
+    	magicGlass_unbind(x->gl_magic_glass);
+    	magicGlass_hide(x->gl_magic_glass);
+	}
+    // end jsarlo
     canvas_setcursor(x, CURSOR_EDITMODE_NOTHING);
     if (doit)
     {
         if (!shiftmod) glist_noselect(x);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags x\n",
+        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags x -outline $select_color\n",
               x, xpos, ypos, xpos, ypos);
         x->gl_editor->e_xwas = xpos;
         x->gl_editor->e_ywas = ypos;
@@ -1498,6 +1869,12 @@ void canvas_doconnect(t_canvas *x, int xpos, int ypos, int which, int doit)
 
             if (canvas_isconnected (x, ob1, closest1, ob2, closest2))
             {
+                // jsarlo
+				if(x->gl_magic_glass) {                
+					magicGlass_unbind(x->gl_magic_glass);
+                	magicGlass_hide(x->gl_magic_glass);
+				}
+                // end jsarlo
                 canvas_setcursor(x, CURSOR_EDITMODE_NOTHING);
                 return;
             }
@@ -1506,6 +1883,12 @@ void canvas_doconnect(t_canvas *x, int xpos, int ypos, int which, int doit)
             {
                 if (doit)
                     error("can't connect signal outlet to control inlet");
+                // jsarlo
+               	if(x->gl_magic_glass) {
+					magicGlass_unbind(x->gl_magic_glass);
+	                magicGlass_hide(x->gl_magic_glass);
+				}
+                // end jsarlo
                 canvas_setcursor(x, CURSOR_EDITMODE_NOTHING);
                 return;
             }
@@ -1527,6 +1910,23 @@ void canvas_doconnect(t_canvas *x, int xpos, int ypos, int which, int doit)
                     (issignal ? "$signal_cord" : "$msg_cord"),
                     (issignal ? 2 : 1), 
                     oc);
+                if (canvas_cnct_inlet_tag[0] != 0)
+                {
+                    sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                           	x, canvas_cnct_inlet_tag,
+							(last_inlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+							(inlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                    canvas_cnct_inlet_tag[0] = 0;                  
+                }
+                if (canvas_cnct_outlet_tag[0] != 0)
+                {
+                    sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                           	x, canvas_cnct_outlet_tag,
+							(last_outlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+							(outlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                    canvas_cnct_outlet_tag[0] = 0;                  
+                }
+                // end jsarlo
                 canvas_dirty(x, 1);
                 canvas_setundo(x, canvas_undo_connect,
                     canvas_undo_set_connect(x, 
@@ -1534,10 +1934,51 @@ void canvas_doconnect(t_canvas *x, int xpos, int ypos, int which, int doit)
                         canvas_getindex(x, &ob2->ob_g), closest2),
                         "connect");
             }
-            else canvas_setcursor(x, CURSOR_EDITMODE_CONNECT);
+    	    else 
+            // jsarlo
+            {
+         		t_rtext *y = glist_findrtext(x, (t_text *)&ob2->ob_g);
+                if (canvas_cnct_inlet_tag[0] != 0)
+                {
+                    sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                           	x, canvas_cnct_inlet_tag,
+							(last_inlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+							(inlet_issignal ? "$signal_nlet" : "$msg_nlet"));                
+                }
+                if (y)
+                {
+					last_inlet_filter = gobj_filter_highlight_behavior(y);
+                    sprintf(canvas_cnct_inlet_tag, 
+                            "%si%d",
+                            rtext_gettag(y),
+                            closest2);
+                    sys_vgui(".x%x.c itemconfigure %s -outline $select_nlet_color -width $highlight_width\n",
+                             x,
+                             canvas_cnct_inlet_tag);
+                    sys_vgui(".x%x.c raise %s\n",
+                             x,
+                             canvas_cnct_inlet_tag);
+					inlet_issignal = obj_issignaloutlet(ob2, closest2);
+                }
+                canvas_setcursor(x, CURSOR_EDITMODE_CONNECT);
+            }
+            // end jsarlo
             return;
-        }
+    	}
     }
+    // jsarlo
+    if (canvas_cnct_inlet_tag[0] != 0)
+    {
+        sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+               	x, canvas_cnct_inlet_tag,
+				(last_inlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+				(inlet_issignal ? "$signal_nlet" : "$msg_nlet"));               
+    }
+	if(x->gl_magic_glass) {
+    	magicGlass_unbind(x->gl_magic_glass);
+    	magicGlass_hide(x->gl_magic_glass);
+	}
+    // end jsarlo
     canvas_setcursor(x, CURSOR_EDITMODE_NOTHING);
 }
 
@@ -1574,9 +2015,50 @@ static void canvas_doregion(t_canvas *x, int xpos, int ypos, int doit)
                 x->gl_editor->e_ywas, xpos, ypos);
 }
 
+static void canvas_mouseup_gop(t_canvas *x, t_gobj *g) {
+
+	/* simulate clearing and recreating object */
+	gobj_activate(g, x, 1);
+	t_object *ob = pd_checkobject(&g->g_pd);
+	t_rtext *yyyy = glist_findrtext(x, (t_text *)&ob->ob_g);
+	/* copy current text */
+    char *buf;
+    int bufsize;
+    rtext_gettext(yyyy, &buf, &bufsize);
+	//fprintf(stderr, ">%s<\n", buf);
+	rtext_key(yyyy, 127, NULL);
+
+	/* recreate object with no args */
+	glist_deselect(x, g);
+
+	/* object was recreated, so now it is latest in the queue */
+	t_gobj *z = x->gl_list;
+
+	while (z->g_next) {
+		z = z->g_next;
+	}
+
+	glist_select(x, z);	
+	g = z;	
+	ob = pd_checkobject(&g->g_pd);
+	yyyy = glist_findrtext(x, (t_text *)&ob->ob_g);
+
+	/* redo the old text */
+	int i;
+	for (i = 0; i < bufsize; i++) {
+		rtext_key(yyyy, (int)buf[i], NULL);
+	}
+	gobj_activate(z, x, 1);
+	x->gl_editor->e_textdirty = 1;
+}
+
 void canvas_mouseup(t_canvas *x,
     t_floatarg fxpos, t_floatarg fypos, t_floatarg fwhich)
 {
+	//if (toggle_moving == 1) {
+	//	toggle_moving = 0;
+	//	sys_vgui("pdtk_toggle_xy_tooltip .x%lx %d\n", x, 0);
+	//}
     int xpos = fxpos, ypos = fypos, which = fwhich;
     /* post("mouseup %d %d %d", xpos, ypos, which); */
     if (!x->gl_editor)
@@ -1610,14 +2092,34 @@ void canvas_mouseup(t_canvas *x,
                 vmess(&gl2->gl_pd, gensym("menu-open"), "");
                 x->gl_editor->e_onmotion = MA_NONE;
                 sys_vgui(
-"pdtk_check .x%lx {Discard changes to '%s'?} {.x%lx dirty 0;\n} no\n",
+					"pdtk_check .x%lx {Discard changes to '%s'?} {.x%lx dirty 0;\n} no\n",
                     canvas_getrootfor(gl2),
-                        canvas_getrootfor(gl2)->gl_name->s_name, gl2);
+                    canvas_getrootfor(gl2)->gl_name->s_name, gl2);
                 return;
             }
-                /* OK, activate it */
-            gobj_activate(x->gl_editor->e_selection->sel_what, x, 1);
+            /* OK, activate it */
+
+			/* but before we do, check if this is GOP and adjust accordingly */
+			//fprintf(stderr,"activate...");
+			if (pd_class(&g->g_pd) == canvas_class && 
+				((t_glist *)g)->gl_isgraph &&
+				canvas_isabstraction((t_glist *)g))
+			{
+				//fprintf(stderr,"gop...");
+				/* if mouse has not moved AND this object does not have its text hidden (otherwise we only translate the selection) */
+				if (!(((t_glist *)g)->gl_hidetext) && !x->gl_editor->e_lastmoved) {
+					//fprintf(stderr,"yes\n");
+					canvas_mouseup_gop(x, x->gl_editor->e_selection->sel_what);
+				}
+				//else fprintf(stderr,"no\n");
+			}
+			/* else if it is a regular object */
+			else {
+				//fprintf(stderr,"reg_obj\n");
+				gobj_activate(x->gl_editor->e_selection->sel_what, x, 1);
+			}
         }
+		sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
     }
     
     x->gl_editor->e_onmotion = MA_NONE;
@@ -1636,14 +2138,24 @@ static void canvas_displaceselection(t_canvas *x, int dx, int dy)
     }
     for (y = x->gl_editor->e_selection; y; y = y->sel_next)
     {
+		/* for the time being let's discern from vanilla objects and those that don't conform */
+		t_glist *yglist = (t_glist *)(y->sel_what);
+		if (y->sel_what->g_pd->c_wb && y->sel_what->g_pd->c_wb->w_displacefnwtag) {
+			/* this is a vanilla object */
+			gobj_displace_withtag(y->sel_what, x, dx, dy);
+		}
+		else {
+			/* we will move the non-conforming objects the old way */
+			gobj_displace(y->sel_what, x, dx, dy);
+		}
         t_class *cl = pd_class(&y->sel_what->g_pd);
-        gobj_displace(y->sel_what, x, dx, dy);
         if (cl == vinlet_class) resortin = 1;
         else if (cl == voutlet_class) resortout = 1;
     }
+	sys_vgui(".x%lx.c move selected %d %d\n", x, dx, dy);
     if (resortin) canvas_resortinlets(x);
     if (resortout) canvas_resortoutlets(x);
-    sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+    //sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
     if (x->gl_editor->e_selection)
         canvas_dirty(x, 1);
 }
@@ -1667,8 +2179,9 @@ void canvas_key(t_canvas *x, t_symbol *s, int ac, t_atom *av)
     canvas_undo_already_set_move = 0;
     down = (atom_getfloat(av) != 0);  /* nonzero if it's a key down */
     shift = (atom_getfloat(av+2) != 0);  /* nonzero if shift-ed */
-    if (av[1].a_type == A_SYMBOL)
+    if (av[1].a_type == A_SYMBOL) {
         gotkeysym = av[1].a_w.w_symbol;
+	}
     else if (av[1].a_type == A_FLOAT)
     {
         char buf[3];
@@ -1694,7 +2207,7 @@ void canvas_key(t_canvas *x, t_symbol *s, int ac, t_atom *av)
         return;
     }
 #if 0
-    post("keynum %d, down %d", (int)keynum, down);
+    post("keynum %d, down %d, gotkeysym %s", (int)keynum, down, gotkeysym->s_name);
 #endif
     if (keynum == '\r') keynum = '\n';
     if (av[1].a_type == A_SYMBOL &&
@@ -1747,7 +2260,11 @@ void canvas_key(t_canvas *x, t_symbol *s, int ac, t_atom *av)
             || !strcmp(gotkeysym->s_name, "Up")
             || !strcmp(gotkeysym->s_name, "Down")
             || !strcmp(gotkeysym->s_name, "Left")
-            || !strcmp(gotkeysym->s_name, "Right")))
+            || !strcmp(gotkeysym->s_name, "Right")
+			|| !strcmp(gotkeysym->s_name, "CtrlHome")
+			|| !strcmp(gotkeysym->s_name, "CtrlEnd")
+			|| !strcmp(gotkeysym->s_name, "Home")
+			|| !strcmp(gotkeysym->s_name, "End")))
         {
                 /* send the key to the box's editor */
             if (!x->gl_editor->e_textdirty)
@@ -1773,15 +2290,26 @@ void canvas_key(t_canvas *x, t_symbol *s, int ac, t_atom *av)
             }
         }
                 /* check for arrow keys */
-        else if (!strcmp(gotkeysym->s_name, "Up"))
-            canvas_displaceselection(x, 0, shift ? -10 : -1);
-        else if (!strcmp(gotkeysym->s_name, "Down"))
-            canvas_displaceselection(x, 0, shift ? 10 : 1);
-        else if (!strcmp(gotkeysym->s_name, "Left"))
-            canvas_displaceselection(x, shift ? -10 : -1, 0);
-        else if (!strcmp(gotkeysym->s_name, "Right"))
-            canvas_displaceselection(x, shift ? 10 : 1, 0);
+		else if (x->gl_editor->e_selection) {
+		    if (!strcmp(gotkeysym->s_name, "Up")) {
+		        canvas_displaceselection(x, 0, shift ? -10 : -1);
+				sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+			}
+		    else if (!strcmp(gotkeysym->s_name, "Down")) {
+		        canvas_displaceselection(x, 0, shift ? 10 : 1);
+				sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+			}
+		    else if (!strcmp(gotkeysym->s_name, "Left")) {
+		        canvas_displaceselection(x, shift ? -10 : -1, 0);
+				sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+			}
+		    else if (!strcmp(gotkeysym->s_name, "Right")) {
+		        canvas_displaceselection(x, shift ? 10 : 1, 0);
+				sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+			}
+		}
     }
+
         /* if control key goes up or down, and if we're in edit mode, change
         cursor to indicate how the click action changes */
     if (x && keynum == 0 && x->gl_edit &&
@@ -1793,7 +2321,7 @@ void canvas_key(t_canvas *x, t_symbol *s, int ac, t_atom *av)
 void canvas_motion(t_canvas *x, t_floatarg xpos, t_floatarg ypos,
     t_floatarg fmod)
 { 
-    /* post("motion %d %d", xpos, ypos); */
+    /* post("motion %d %d", (int)xpos, (int)ypos); */
     int mod = fmod;
     if (!x->gl_editor)
     {
@@ -1830,7 +2358,9 @@ void canvas_motion(t_canvas *x, t_floatarg xpos, t_floatarg ypos,
                 ypos - x->gl_editor->e_ywas, RTEXT_DRAG);
     }
     else canvas_doclick(x, xpos, ypos, 0, mod, 0);
-    
+	//if (toggle_moving == 1) {
+	//	sys_vgui("pdtk_update_xy_tooltip .x%lx %d %d\n", x, (int)xpos, (int)ypos);
+	//}
     x->gl_editor->e_lastmoved = 1;
 }
 
@@ -1905,9 +2435,22 @@ void canvas_menuclose(t_canvas *x, t_floatarg fforce)
         g = glist_finddirty(x);
         if (g)
         {
-            canvas_vis(g, 1);
-            sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;\n}\n",
+			/* first open window */
+			if (!glist_istoplevel(g) && g->gl_env) {
+				/* if this is an abstraction */
+            	vmess(&g->gl_pd, gensym("menu-open"), "");
+			} else {
+				/* is this even necessary? */
+	            canvas_vis(g, 1);
+			}
+			if (!glist_istoplevel(g) && g->gl_env) {
+				/* if this is an abstraction */
+            	sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;}\n",
+                     g, g);
+			} else {
+            	sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;}\n",
                      canvas_getrootfor(g), g);
+			}
             return;
         }
 /*
@@ -1931,8 +2474,16 @@ void canvas_menuclose(t_canvas *x, t_floatarg fforce)
         if (g)
         {
             vmess(&g->gl_pd, gensym("menu-open"), "");
-            sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;\n}\n",
-                     canvas_getrootfor(x), g);
+			if (!glist_istoplevel(g) && g->gl_env) {
+				/* if this is an abstraction */
+            	sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;}\n",
+                     g, g);
+			} else {
+            	sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;}\n",
+                     canvas_getrootfor(g), g);
+			}
+            //sys_vgui("pdtk_canvas_menuclose .x%lx {.x%lx menuclose 2;\n}\n",
+            //         canvas_getrootfor(x), g);
             return;
         }
         else pd_free(&x->gl_pd);
@@ -2140,26 +2691,49 @@ void canvas_restoreconnections(t_canvas *x)
 
 static t_binbuf *canvas_docopy(t_canvas *x)
 {
-    t_gobj *y;
+	//fprintf(stderr,"docopy\n");
+    t_gobj *y, *last;
     t_linetraverser t;
     t_outconnect *oc;
     t_binbuf *b = binbuf_new();
+	int c = 0;
     for (y = x->gl_list; y; y = y->g_next)
     {
-        if (glist_isselected(x, y))
+        if (glist_isselected(x, y)) {
+			c++;
+			//fprintf(stderr, "saving object num %d\n", c);
+			//fprintf(stderr, "saving object >.x%lx<\n", (t_int)y);
+			/* introduce redundant comment to avoid recreation of old abstractions
+			   with the same canvas id which results in all commands being registered
+			   multiple times--apparently after much searching it appears that this
+			   is yet another bug in tcl/tk which means that canvas tries to do some
+			   kind of caching behind the curtains resulting in objects not always
+			   having unique ids, contrary to tcl/tk's canvas man page */
+			if (c==1) {
+            	binbuf_addv(b, "ssiis;", gensym("#X"), gensym("text"),
+                (int)((t_text *)y)->te_xpix-30, (int)((t_text *)y)->te_ypix-30, gensym("tcltksucks"));
+			}
             gobj_save(y, b);
+		}
     }
+	//fprintf(stderr,"done saving objects\n");
     linetraverser_start(&t, x);
+	c = 0;
     while (oc = linetraverser_next(&t))
     {
         if (glist_isselected(x, &t.tr_ob->ob_g)
             && glist_isselected(x, &t.tr_ob2->ob_g))
         {
+			//fprintf(stderr, "lines need to be copied\n");
+			c = 1;
             binbuf_addv(b, "ssiiii;", gensym("#X"), gensym("connect"),
-                glist_selectionindex(x, &t.tr_ob->ob_g, 1), t.tr_outno,
-                glist_selectionindex(x, &t.tr_ob2->ob_g, 1), t.tr_inno);
+//                glist_selectionindex(x, &t.tr_ob->ob_g, 1), t.tr_outno,
+//                glist_selectionindex(x, &t.tr_ob2->ob_g, 1), t.tr_inno);
+                glist_selectionindex(x, &t.tr_ob->ob_g, 1)+1, t.tr_outno,
+                glist_selectionindex(x, &t.tr_ob2->ob_g, 1)+1, t.tr_inno);
         }
     }
+	//if (!c) fprintf(stderr, "no lines copied\n");
     return (b);
 }
 
@@ -2168,6 +2742,7 @@ static void canvas_copy(t_canvas *x)
     if (!x->gl_editor || !x->gl_editor->e_selection)
         return;
     binbuf_free(copy_binbuf);
+	//fprintf(stderr, "canvas_copy\n");
     copy_binbuf = canvas_docopy(x);
     paste_xyoffset = 1;
     if (x->gl_editor->e_textedfor)
@@ -2254,6 +2829,15 @@ static void canvas_doclear(t_canvas *x)
             y2 = y->g_next;
             if (glist_isselected(x, y))
             {
+				/* if it is a graph and the window is open, destroy it first
+				   this will avoid leaving stale gop rectangle and name */
+		        if (pd_class(&y->g_pd) == canvas_class &&
+		        	((t_glist *)y)->gl_havewindow)
+				{
+					canvas_menuclose((t_glist *)y, 0);
+				}
+
+				/* now destroy the object */
                 glist_delete(x, y);
 #if 0
                 if (y2) post("cut 5 %lx %lx", y2, y2->g_next);
@@ -2266,14 +2850,16 @@ static void canvas_doclear(t_canvas *x)
     next: ;
     }
 restore:
-    canvas_resume_dsp(dspstate);
     canvas_dirty(x, 1);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
+    canvas_resume_dsp(dspstate);
 }
 
 static void canvas_cut(t_canvas *x)
 {
     if (x->gl_editor && x->gl_editor->e_selectedline)
         canvas_clearline(x);
+	/* if we are cutting text */
     else if (x->gl_editor->e_textedfor)
     {
         char *buf;
@@ -2285,6 +2871,7 @@ static void canvas_cut(t_canvas *x)
         rtext_key(x->gl_editor->e_textedfor, 127, &s_);
         canvas_dirty(x, 1);
     }
+	/* else we are cutting objects */
     else if (x->gl_editor && x->gl_editor->e_selection)
     {
         canvas_setundo(x, canvas_undo_cut,
@@ -2318,8 +2905,36 @@ static void canvas_paste_xyoffset(t_canvas *x)
     paste_xyoffset++;
 }
 
+static void canvas_paste_atmouse(t_canvas *x)
+{
+    t_selection *sel;
+	/* use safe values for x1 and y1 which are essentially the same as xyoffset */
+	int x1 = x->gl_editor->e_xwas+10, y1 = x->gl_editor->e_ywas+10, init = 0;
+	t_glist *g;
+	t_text *t;
+
+	/* find the initial offset--we use leftmost object as our reference */
+    for (sel = x->gl_editor->e_selection; sel; sel = sel->sel_next) {
+		g = (t_glist *)sel->sel_what;
+		t = (t_text *)g;
+		if (!init) {
+			x1 = t->te_xpix;
+			y1 = t->te_ypix;
+			init = 1;
+		} else if ( t->te_xpix < x1 ) {
+			x1 = t->te_xpix;
+		}
+	}
+	/* redraw objects */
+    canvas_displaceselection(x, (x->gl_editor->e_xwas)+5-x1, (x->gl_editor->e_ywas)-y1);
+	canvas_startmotion(x);
+}
+
+extern void canvas_obj(t_glist *gl, t_symbol *s, int argc, t_atom *argv);
+
 static void canvas_dopaste(t_canvas *x, t_binbuf *b)
 {
+	//fprintf(stderr,"start dopaste\n");
     t_gobj *newgobj, *last, *g2;
     int dspstate = canvas_suspend_dsp(), nbox, count;
 
@@ -2327,18 +2942,32 @@ static void canvas_dopaste(t_canvas *x, t_binbuf *b)
     glist_noselect(x);
     for (g2 = x->gl_list, nbox = 0; g2; g2 = g2->g_next) nbox++;
     
+	/* found the end of the queue */
     paste_onset = nbox;
     paste_canvas = x;
-    
+
     pd_bind(&x->gl_pd, gensym("#X"));
     binbuf_eval(b, 0, 0, 0);
     pd_unbind(&x->gl_pd, gensym("#X"));
+
+	/* select newly created objects */
     for (g2 = x->gl_list, count = 0; g2; g2 = g2->g_next, count++)
-        if (count >= nbox)
+        if (count == nbox) {
+			/* delete bogus object we created in canvas_docopy in order to circumvent tcl/tk's failure
+			   to provide "unique" id to every new instance of an object */
+            glist_delete(x, g2);
+		} else if (count > nbox) {
             glist_select(x, g2);
+			//fprintf(stderr,"object=.x%lx glist_getcanvas(x)=.x%lx\n", (t_int)g2, (t_int)glist_getcanvas((t_glist*)g2) );
+		}
+
     paste_canvas = 0;
     canvas_resume_dsp(dspstate);
     canvas_dirty(x, 1);
+	if (!canvas_undo_name || canvas_undo_name[0] != 'd') {
+		canvas_redraw(x);
+	}
+    //sys_vgui(".x%lx.c create line 0 0 100 100 -width 3 -fill black -tags tcltastic\n", x); 
     sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
     glist_donewloadbangs(x);
 }
@@ -2368,20 +2997,37 @@ static void canvas_paste(t_canvas *x)
         canvas_setundo(x, canvas_undo_paste, canvas_undo_set_paste(x),
             "paste");
         canvas_dopaste(x, copy_binbuf);
-        canvas_paste_xyoffset(x);
+        //canvas_paste_xyoffset(x);
+		canvas_paste_atmouse(x);
     }
 }
 
 static void canvas_duplicate(t_canvas *x)
 {
-    if (x->gl_editor->e_onmotion == MA_NONE && x->gl_editor->e_selection)
-    {
-        canvas_copy(x);
-        canvas_setundo(x, canvas_undo_paste, canvas_undo_set_paste(x),
-            "duplicate");
-        canvas_dopaste(x, copy_binbuf);
-        canvas_paste_xyoffset(x);
-        canvas_dirty(x, 1);
+    //if (x->gl_editor->e_onmotion == MA_NONE && x->gl_editor->e_selection)
+	if (x->gl_editor->e_onmotion == MA_NONE && c_selection && c_selection->gl_editor->e_selection)
+    {
+        //canvas_copy(x);
+        //canvas_setundo(x, canvas_undo_paste, canvas_undo_set_paste(x),
+        //    "duplicate");
+        //canvas_dopaste(x, copy_binbuf);
+        //canvas_paste_xyoffset(x);
+        //canvas_dirty(x, 1);
+        canvas_copy(c_selection);
+		if (c_selection == x) {
+			/* we are in the same window */
+		    canvas_setundo(x, canvas_undo_paste, canvas_undo_set_paste(x),
+		        "duplicate");
+		    canvas_dopaste(x, copy_binbuf);
+		    canvas_paste_xyoffset(x);
+		    canvas_dirty(x, 1);
+		} else {
+		    canvas_setundo(x, canvas_undo_paste, canvas_undo_set_paste(x),
+		        "duplicate");
+		    canvas_dopaste(x, copy_binbuf);
+		    //canvas_paste_xyoffset(x);
+		    canvas_dirty(x, 1);
+		}
     }
 }
 
@@ -2390,14 +3036,31 @@ static void canvas_selectall(t_canvas *x)
     t_gobj *y;
     if (!x->gl_edit)
         canvas_editmode(x, 1);
-            /* if everyone is already selected deselect everyone */
-    if (!glist_selectionindex(x, 0, 0))
-        glist_noselect(x);
-    else for (y = x->gl_list; y; y = y->g_next)
+
+    if (x->gl_editor && x->gl_editor->e_textedfor)
     {
-        if (!glist_isselected(x, y))
-            glist_select(x, y);
-    }
+        /* only do this if exactly one item is selected. */
+        if (x->gl_editor->e_selection->sel_what &&
+            !x->gl_editor->e_selection->sel_next)
+        {
+			t_gobj *z = x->gl_editor->e_selection->sel_what;
+			/* reactivate */
+			gobj_activate(z, x, 1);
+			/* make canvas dirty in case this was done at creation time */
+			x->gl_editor->e_textdirty = 1;
+		}
+	}
+	else {
+
+		/* if everyone is already selected deselect everyone */
+		if (!glist_selectionindex(x, 0, 0))
+		    glist_noselect(x);
+		else for (y = x->gl_list; y; y = y->g_next)
+		{
+		    if (!glist_isselected(x, y))
+		        glist_select(x, y);
+		}
+	}
 }
 
 static void canvas_reselect(t_canvas *x)
@@ -2483,8 +3146,8 @@ bad:
             (sink? class_getname(pd_class(&sink->g_pd)) : "???"));
 }
 
-#define XTOLERANCE 4
-#define YTOLERANCE 3
+#define XTOLERANCE 20
+#define YTOLERANCE 20
 #define NHIST 15
 
     /* LATER might have to speed this up */
@@ -2553,7 +3216,7 @@ static void canvas_tidy(t_canvas *x)
             bestdist = i;
         }
     }
-    post("best vertical distance %d", bestdist);
+    //post("best vertical distance %d", bestdist);
     for (y = x->gl_list; y; y = y->g_next)
         if (all || glist_isselected(x, y))
     {
@@ -2621,11 +3284,63 @@ void canvas_editmode(t_canvas *x, t_floatarg fyesplease)
     {
         glist_noselect(x);
         if (glist_isvisible(x) && glist_istoplevel(x))
-            canvas_setcursor(x, CURSOR_RUNMODE_NOTHING);
+        {
+            // jsarlo
+            if (canvas_cnct_inlet_tag[0] != 0)
+            {
+                sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                       	x, canvas_cnct_inlet_tag,
+						(last_inlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+						(inlet_issignal ? "$signal_nlet" : "$msg_nlet")); 
+                canvas_cnct_inlet_tag[0] = 0;                  
+            }
+            if (canvas_cnct_outlet_tag[0] != 0)
+            {
+                sys_vgui(".x%x.c itemconfigure %s -outline %s -fill %s -width 1\n",
+                       	x, canvas_cnct_outlet_tag,
+						(last_outlet_filter ? "black" : (outlet_issignal ? "$signal_cord" : "$msg_cord")),
+						(outlet_issignal ? "$signal_nlet" : "$msg_nlet"));
+                canvas_cnct_outlet_tag[0] = 0;                  
+            }
+			if(x->gl_magic_glass) {
+            	magicGlass_unbind(x->gl_magic_glass);
+            	magicGlass_hide(x->gl_magic_glass);
+			}
+            // end jsarlo
+        }
     }
     sys_vgui("pdtk_canvas_editval .x%lx %d\n",
         glist_getcanvas(x), x->gl_edit);
+	/*if (!x->gl_edit) {
+		sys_vgui(".x%lx.m.edit entryconfigure \"Cord Inspector\" -indicatoron false -state disabled\n", glist_getcanvas(x));
+	}
+	else {
+		sys_vgui(".x%lx.m.edit entryconfigure \"Cord Inspector\" -indicatoron false -state normal\n", glist_getcanvas(x));
+	}*/
+}
+
+// jsarlo
+void canvas_magicglass(t_canvas *x, t_floatarg fyesplease)
+{
+    int yesplease = fyesplease;
+    if (yesplease && magicGlass_isOn(x->gl_magic_glass))
+    	return;
+    if (!magicGlass_isOn(x->gl_magic_glass)) {
+		canvas_editmode(x, 1.);
+        magicGlass_setOn(x->gl_magic_glass, 1);
+        if (magicGlass_bound(x->gl_magic_glass))
+        {
+            magicGlass_show(x->gl_magic_glass);
+        }
+    }
+    else {
+        magicGlass_setOn(x->gl_magic_glass, 0);
+        magicGlass_hide(x->gl_magic_glass);
+    }
+    sys_vgui("pdtk_canvas_magicglassval .x%x %d\n",
+        glist_getcanvas(x), magicGlass_isOn(x->gl_magic_glass));
 }
+// end jsarlo
 
     /* called by canvas_font below */
 static void canvas_dofont(t_canvas *x, t_floatarg font, t_floatarg xresize,
@@ -2728,6 +3443,10 @@ void g_editor_setup(void)
         gensym("texteditor"), A_NULL);
     class_addmethod(canvas_class, (t_method)canvas_editmode,
         gensym("editmode"), A_DEFFLOAT, A_NULL);
+    // jsarlo
+    class_addmethod(canvas_class, (t_method)canvas_magicglass,
+        gensym("magicglass"), A_DEFFLOAT, A_NULL);
+    //end jsarlo
     class_addmethod(canvas_class, (t_method)canvas_print,
         gensym("print"), A_SYMBOL, A_NULL);
     class_addmethod(canvas_class, (t_method)canvas_menufont,
@@ -2745,7 +3464,7 @@ void g_editor_setup(void)
     class_addmethod(canvas_class, (t_method)canvas_donecanvasdialog,
         gensym("donecanvasdialog"), A_GIMME, A_NULL);
     class_addmethod(canvas_class, (t_method)glist_arraydialog,
-        gensym("arraydialog"), A_SYMBOL, A_FLOAT, A_FLOAT, A_FLOAT, A_NULL);
+        gensym("arraydialog"), A_GIMME, A_NULL);
 
 /* -------------- connect method used in reading files ------------------ */
     class_addmethod(canvas_class, (t_method)canvas_connect,
diff --git a/src/g_graph.c b/src/g_graph.c
index 61fdf7a73..38d17e69f 100644
--- a/src/g_graph.c
+++ b/src/g_graph.c
@@ -98,8 +98,12 @@ void glist_delete(t_glist *x, t_gobj *y)
             if (gl->gl_isgraph)
             {
                 char tag[80];
-                sprintf(tag, "graph%lx", (t_int)gl);
+                //sprintf(tag, "graph%lx", (t_int)gl);
+				//t_glist *yy = (t_glist *)y;
+				sprintf(tag, "%s", rtext_gettag(glist_findrtext(x, &gl->gl_obj)));
                 glist_eraseiofor(x, &gl->gl_obj, tag);
+                text_eraseborder(&gl->gl_obj, x,
+                    rtext_gettag(glist_findrtext(x, &gl->gl_obj)));
             }
             else
             {
@@ -113,6 +117,9 @@ void glist_delete(t_glist *x, t_gobj *y)
     if (drawcommand)
         canvas_redrawallfortemplate(template_findbyname(canvas_makebindsym(
             glist_getcanvas(x)->gl_name)), 2);
+	//if(glist_isvisible(canvas)) {
+	//	gobj_select(y, x, 0);
+	//}
     gobj_delete(y, x);
     if (glist_isvisible(canvas))
         gobj_vis(y, x, 0);
@@ -132,6 +139,7 @@ void glist_delete(t_glist *x, t_gobj *y)
             glist_getcanvas(x)->gl_name)), 1);
     canvas_setdeleting(canvas, wasdeleting);
     x->gl_valid = ++glist_valid;
+	//canvas_redraw(x);
 }
 
     /* remove every object from a glist.  Experimental. */
@@ -184,7 +192,8 @@ void glist_grab(t_glist *x, t_gobj *y, t_glistmotionfn motionfn,
 
 t_canvas *glist_getcanvas(t_glist *x)
 {
-    while (x->gl_owner && !x->gl_havewindow && x->gl_isgraph)
+    while (x->gl_owner && !x->gl_havewindow && x->gl_isgraph &&
+        gobj_shouldvis(&x->gl_gobj, x->gl_owner))
             x = x->gl_owner;
     return((t_canvas *)x);
 }
@@ -665,7 +674,7 @@ void glist_redraw(t_glist *x)
             canvas_drawredrect(x, 0);
             if (x->gl_goprect)
             {
-                post("draw it");
+                //post("draw it");
                 canvas_drawredrect(x, 1);
             }
         }
@@ -703,7 +712,9 @@ static void graph_vis(t_gobj *gr, t_glist *parent_glist, int vis)
     if (!vis)
         rtext_erase(glist_findrtext(parent_glist, &x->gl_obj));
 
-    sprintf(tag, "graph%lx", (t_int)x);
+    sprintf(tag, "%s", rtext_gettag(glist_findrtext(parent_glist, &x->gl_obj)));
+    //sprintf(tag, "graph%lx", (t_int)x);
+	//fprintf(stderr, "gettag=%s, tag=graph%lx\n", rtext_gettag(glist_findrtext(parent_glist, &x->gl_obj)),(t_int)x);
     if (vis)
         glist_drawiofor(parent_glist, &x->gl_obj, 1,
             tag, x1, y1, x2, y2);
@@ -718,7 +729,6 @@ static void graph_vis(t_gobj *gr, t_glist *parent_glist, int vis)
  %d %d %d %d %d %d %d %d %d %d -tags %s -fill #c0c0c0\n",
                 glist_getcanvas(x->gl_owner),
                 x1, y1, x1, y2, x2, y2, x2, y1, x1, y1, tag);
-            sys_vgui(".x%lx.c raise all_cords\n", glist_getcanvas(x->gl_owner));
         }
         else
         {
@@ -737,7 +747,7 @@ static void graph_vis(t_gobj *gr, t_glist *parent_glist, int vis)
         t_garray *ga;
             /* draw a rectangle around the graph */
         sys_vgui(".x%lx.c create line\
-            %d %d %d %d %d %d %d %d %d %d -fill $graph_outline -tags %s\n",
+            %d %d %d %d %d %d %d %d %d %d -fill $graph_outline -tags %sR\n",
             glist_getcanvas(x->gl_owner),
             x1, y1, x1, y2, x2, y2, x2, y1, x1, y1, tag);
         
@@ -856,6 +866,8 @@ static void graph_vis(t_gobj *gr, t_glist *parent_glist, int vis)
     {
         sys_vgui(".x%lx.c delete %s\n",
             glist_getcanvas(x->gl_owner), tag);
+        sys_vgui(".x%lx.c delete %sR\n",
+            glist_getcanvas(x->gl_owner), tag);
         for (g = x->gl_list; g; g = g->g_next)
             gobj_vis(g, x, 0);
     }
@@ -944,25 +956,32 @@ static void graph_displace(t_gobj *z, t_glist *glist, int dx, int dy)
         x->gl_obj.te_xpix += dx;
         x->gl_obj.te_ypix += dy;
         glist_redraw(x);
+		gobj_select(z, glist, 1);
         canvas_fixlinesfor(glist_getcanvas(glist), &x->gl_obj);
     }
 }
 
 static void graph_select(t_gobj *z, t_glist *glist, int state)
 {
+	//fprintf(stderr,"graph_select\n");
     t_glist *x = (t_glist *)z;
     if (!x->gl_isgraph)
         text_widgetbehavior.w_selectfn(z, glist, state);
-    else
+    else if(glist_istoplevel(glist))
     {
         t_rtext *y = glist_findrtext(glist, &x->gl_obj);
         if (canvas_showtext(x))
             rtext_select(y, state);
         sys_vgui(".x%lx.c itemconfigure %sR -fill %s\n", glist, 
-                 rtext_gettag(y), (state? "$select_color" : "black"));
+                 rtext_gettag(y), (state? "$select_color" : "$graph_outline"));
+/*
         sys_vgui(".x%lx.c itemconfigure graph%lx -fill %s\n",
                  glist_getcanvas(glist), z, 
                  (state? "$select_color" : "$graph_outline"));
+*/
+        sys_vgui(".x%lx.c itemconfigure %s -fill %s\n",
+                 glist, rtext_gettag(y), 
+                 (state? "$select_color" : "black"));
     }
 }
 
@@ -996,8 +1015,11 @@ static void graph_delete(t_gobj *z, t_glist *glist)
     t_glist *x = (t_glist *)z;
     t_gobj *y;
     text_widgetbehavior.w_deletefn(z, glist);
-    while (y = x->gl_list)
+    while (y = x->gl_list) {
         glist_delete(x, y);
+	}
+	if (glist_istoplevel(glist) && glist_isvisible(glist))
+		sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", glist);
 }
 
 static t_float graph_lastxpix, graph_lastypix;
@@ -1083,6 +1105,7 @@ t_widgetbehavior graph_widgetbehavior =
     graph_delete,
     graph_vis,
     graph_click,
+	NULL,
 };
 
     /* find the graph most recently added to this glist;
diff --git a/src/g_hdial.c b/src/g_hdial.c
index ddbd81c18..4fdc464aa 100644
--- a/src/g_hdial.c
+++ b/src/g_hdial.c
@@ -28,6 +28,9 @@ put out a "float" as in sliders, toggles, etc. */
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+void hradio_draw_select(t_hradio* x, t_glist* glist);
+
 /* ------------- hdl     gui-horicontal dial ---------------------- */
 
 t_widgetbehavior hradio_widgetbehavior;
@@ -37,11 +40,6 @@ static t_class *hradio_class, *hradio_old_class;
 
 void hradio_draw_update(t_gobj *client, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("hradio_draw_update");
-        return;
-    }
     t_hradio *x = (t_hradio *)client;
     if(glist_isvisible(glist))
     {
@@ -66,34 +64,52 @@ void hradio_draw_new(t_hradio *x, t_glist *glist)
     int xx11b=text_xpix(&x->x_gui.x_obj, glist), xx11=xx11b, xx21=xx11b+s4;
     int xx22=xx11b+dx-s4;
 
-
-    for(i=0; i<n; i++)
-    {
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE%d\n",
-                 canvas, xx11, yy11, xx11+dx, yy12,
-                 x->x_gui.x_bcol, x, i);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags %lxBUT%d\n",
-                 canvas, xx21, yy21, xx22, yy22,
-                 (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol,
-                 (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol, x, i);
-        xx11 += dx;
-        xx21 += dx;
-        xx22 += dx;
-        x->x_drawn = x->x_on;
-    }
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xx11b+x->x_gui.x_ldx, yy11+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xx11b, yy12-1, xx11b + IOWIDTH, yy12, x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xx11b, yy11, xx11b + IOWIDTH, yy11+1, x, 0);
-
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		for(i=0; i<n; i++)
+		{
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE%d %lxHRDO}\n",
+		             canvas, xx11, yy11, xx11+dx, yy12,
+		             x->x_gui.x_bcol, x, i, x);
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags {%lxBUT%d %lxHRDO}\n",
+		             canvas, xx21, yy21, xx22, yy22,
+		             (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol,
+		             (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol, x, i, x);
+		    xx11 += dx;
+		    xx21 += dx;
+		    xx22 += dx;
+		    x->x_drawn = x->x_on;
+		}
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxHRDO}\n",
+		         canvas, xx11b+x->x_gui.x_ldx, yy11+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+		         x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxHRDO}\n",
+		         canvas, xx11b, yy12-1, xx11b + IOWIDTH, yy12, nlet_tag, 0, x);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxHRDO}\n",
+		         canvas, xx11b, yy11, xx11b + IOWIDTH, yy11+1, nlet_tag, 0, x);
+	//}
 }
 
 void hradio_draw_move(t_hradio *x, t_glist *glist)
@@ -105,27 +121,46 @@ void hradio_draw_move(t_hradio *x, t_glist *glist)
     int xx11b=text_xpix(&x->x_gui.x_obj, glist), xx11=xx11b, xx21=xx11b+s4;
     int xx22=xx11b+dx-s4;
 
-    xx11 = xx11b;
-    xx21=xx11b+s4;
-    xx22=xx11b+dx-s4;
-    for(i=0; i<n; i++)
-    {
-        sys_vgui(".x%lx.c coords %lxBASE%d %d %d %d %d\n",
-                 canvas, x, i, xx11, yy11, xx11+dx, yy12);
-        sys_vgui(".x%lx.c coords %lxBUT%d %d %d %d %d\n",
-                 canvas, x, i, xx21, yy21, xx22, yy22);
-        xx11 += dx;
-        xx21 += dx;
-        xx22 += dx;
-    }
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xx11b+x->x_gui.x_ldx, yy11+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0, xx11b, yy12-1, xx11b + IOWIDTH, yy12);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0, xx11b, yy11, xx11b + IOWIDTH, yy11+1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		xx11 = xx11b;
+		xx21=xx11b+s4;
+		xx22=xx11b+dx-s4;
+		for(i=0; i<n; i++)
+		{
+		    sys_vgui(".x%lx.c coords %lxBASE%d %d %d %d %d\n",
+		             canvas, x, i, xx11, yy11, xx11+dx, yy12);
+		    sys_vgui(".x%lx.c coords %lxBUT%d %d %d %d %d\n",
+		             canvas, x, i, xx21, yy21, xx22, yy22);
+		    xx11 += dx;
+		    xx21 += dx;
+		    xx22 += dx;
+		}
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xx11b+x->x_gui.x_ldx, yy11+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xx11b, yy12-1, xx11b + IOWIDTH, yy12);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xx11b, yy11, xx11b + IOWIDTH, yy11+1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected)
+			hradio_draw_select(x, x->x_gui.x_glist);
+	}
 }
 
 void hradio_draw_erase(t_hradio* x, t_glist* glist)
@@ -133,6 +168,13 @@ void hradio_draw_erase(t_hradio* x, t_glist* glist)
     t_canvas *canvas=glist_getcanvas(glist);
     int n=x->x_number, i;
 
+	sys_vgui(".x%lx.c delete %lxHRDO\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxHRDO\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+/*
     for(i=0; i<n; i++)
     {
         sys_vgui(".x%lx.c delete %lxBASE%d\n", canvas, x, i);
@@ -140,9 +182,10 @@ void hradio_draw_erase(t_hradio* x, t_glist* glist)
     }
     sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
     if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
+        sys_vgui(".x%lx.c delete %so%d\n", canvas, rtext_gettag(yy), 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
-    sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+    sys_vgui(".x%lx.c delete %si%d\n", canvas, rtext_gettag(yy), 0);
+*/
 }
 
 void hradio_draw_config(t_hradio* x, t_glist* glist)
@@ -150,9 +193,15 @@ void hradio_draw_config(t_hradio* x, t_glist* glist)
     t_canvas *canvas=glist_getcanvas(glist);
     int n=x->x_number, i;
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol);
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
     for(i=0; i<n; i++)
     {
@@ -170,46 +219,196 @@ void hradio_draw_io(t_hradio* x, t_glist* glist, int old_snd_rcv_flags)
     int xpos=text_xpix(&x->x_gui.x_obj, glist);
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-                 canvas,
-                 xpos, ypos + x->x_gui.x_w-1,
-                 xpos + IOWIDTH, ypos + x->x_gui.x_w,
-                 x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-                 canvas,
-                 xpos, ypos,
-                 xpos + IOWIDTH, ypos+1, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		             canvas,
+		             xpos, ypos + x->x_gui.x_w-1,
+		             xpos + IOWIDTH, ypos + x->x_gui.x_w,
+		             nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		             canvas,
+		             xpos, ypos,
+		             xpos + IOWIDTH, ypos+1, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+	}
 }
 
 void hradio_draw_select(t_hradio* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
     int n=x->x_number, i;
 
-    if(x->x_gui.x_fsf.x_selected)
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    for(i=0; i<n; i++)
+		    {
+		        sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline $select_color\n", canvas, x, i);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxHRDO}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w * x->x_number - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxHRDO\n", canvas, x);
+		}
+		else
+		{
+			sys_vgui(".x%lx.c dtag %lxHRDO selected\n", canvas, x);
+		    for(i=0; i<n; i++)
+		    {
+		        sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline #%6.6x\n", canvas, x, i,
+		                 IEM_GUI_COLOR_NORMAL);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x,
+		             x->x_gui.x_lcol);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void hradio__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_hradio *x = (t_hradio *)(sh->h_master);
+
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        for(i=0; i<n; i++)
-        {
-            sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline #%6.6x\n", canvas, x, i,
-                     IEM_GUI_COLOR_SELECTED);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			sh->h_dragx = sh->h_dragy;
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_w < SCALE_HRDO_MINWIDTH)
+				x->x_gui.x_w = SCALE_HRDO_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_h < SCALE_HRDO_MINHEIGHT)
+				x->x_gui.x_h = SCALE_HRDO_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			hradio_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        for(i=0; i<n; i++)
-        {
-            sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline #%6.6x\n", canvas, x, i,
-                     IEM_GUI_COLOR_NORMAL);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x,
-                 x->x_gui.x_lcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + (x->x_gui.x_w * x->x_number),
+					x->x_gui.x_obj.te_ypix + x->x_gui.x_h, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
+    }
+    sh->h_dragon = newstate;
+}
+
+static void hradio__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_hradio *x = (t_hradio *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+
+		dx = dy;
+
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_w*x->x_number + (dx - x->x_gui.scale_offset_y) * x->x_number;
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h + (dy - x->x_gui.scale_offset_y);
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_HRDO_MINWIDTH*x->x_number)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_HRDO_MINWIDTH*x->x_number;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_HRDO_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_HRDO_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix, newx, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			//int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
     }
 }
 
@@ -293,6 +492,8 @@ static void hradio_properties(t_gobj *z, t_glist *owner)
 
 static void hradio_dialog(t_hradio *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int a = (int)atom_getintarg(0, argc, argv);
     int chg = (int)atom_getintarg(4, argc, argv);
@@ -323,6 +524,14 @@ static void hradio_dialog(t_hradio *x, t_symbol *s, int argc, t_atom *argv)
         canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
     }
 
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		hradio_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void hradio_set(t_hradio *x, t_floatarg f)
@@ -626,6 +835,21 @@ static void *hradio_donew(t_symbol *s, int argc, t_atom *argv, int old)
     iemgui_verify_snd_ne_rcv(&x->x_gui);
     iemgui_all_colfromload(&x->x_gui, bflcol);
     outlet_new(&x->x_gui.x_obj, &s_list);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -644,6 +868,13 @@ static void hradio_ff(t_hradio *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_hradio_setup(void)
@@ -686,6 +917,14 @@ void g_hradio_setup(void)
         gensym("single_change"), 0);
     class_addmethod(hradio_class, (t_method)hradio_double_change,
         gensym("double_change"), 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)hradio__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)hradio__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     hradio_widgetbehavior.w_getrectfn = hradio_getrect;
     hradio_widgetbehavior.w_displacefn = iemgui_displace;
     hradio_widgetbehavior.w_selectfn = iemgui_select;
@@ -693,6 +932,7 @@ void g_hradio_setup(void)
     hradio_widgetbehavior.w_deletefn = iemgui_delete;
     hradio_widgetbehavior.w_visfn = iemgui_vis;
     hradio_widgetbehavior.w_clickfn = hradio_newclick;
+    hradio_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(hradio_class, &hradio_widgetbehavior);
     class_sethelpsymbol(hradio_class, gensym("hradio"));
     class_setsavefn(hradio_class, hradio_save);
diff --git a/src/g_hslider.c b/src/g_hslider.c
index 5205ecbba..291735e8b 100644
--- a/src/g_hslider.c
+++ b/src/g_hslider.c
@@ -25,6 +25,8 @@
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+static void hslider_draw_select(t_hslider* x,t_glist* glist);
 
 /* ------------ hsl    gui-horicontal  slider ----------------------- */
 
@@ -35,17 +37,13 @@ static t_class *hslider_class;
 
 static void hslider_draw_update(t_gobj *client, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("hslider_draw_update");
-        return;
-    }
     t_hslider *x = (t_hslider *)client;
+    t_canvas *canvas=glist_getcanvas(glist);
+    int ypos=text_ypix(&x->x_gui.x_obj, glist);
+
     if (glist_isvisible(glist))
     {
-        t_canvas *canvas=glist_getcanvas(glist);
         int r = text_xpix(&x->x_gui.x_obj, glist) + (x->x_val + 50)/100;
-        int ypos=text_ypix(&x->x_gui.x_obj, glist);
         sys_vgui(".x%lx.c coords %lxKNOB %d %d %d %d\n",
                  canvas, x, r, ypos+1,
                  r, ypos + x->x_gui.x_h);
@@ -75,28 +73,47 @@ static void hslider_draw_new(t_hslider *x, t_glist *glist)
     int r = xpos + (x->x_val + 50)/100;
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE\n",
-             canvas, xpos-3, ypos,
-             xpos + x->x_gui.x_w+2, ypos + x->x_gui.x_h,
-             x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create line %d %d %d %d -width 3 -fill #%6.6x -tags %lxKNOB\n",
-             canvas, r, ypos+1, r,
-             ypos + x->x_gui.x_h, x->x_gui.x_fcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xpos+x->x_gui.x_ldx,
-             ypos+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-			 x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xpos-3, ypos + x->x_gui.x_h-1,
-             xpos+4, ypos + x->x_gui.x_h, x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xpos-3, ypos,
-             xpos+4, ypos+1, x, 0);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE %lxHSLDR}\n",
+		         canvas, xpos-3, ypos,
+		         xpos + x->x_gui.x_w+2, ypos + x->x_gui.x_h,
+		         x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create line %d %d %d %d -width 3 -fill #%6.6x -tags {%lxKNOB %lxHSLDR}\n",
+		         canvas, r, ypos+1, r,
+		         ypos + x->x_gui.x_h, x->x_gui.x_fcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxHSLDR}\n",
+		         canvas, xpos+x->x_gui.x_ldx,
+		         ypos+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+				 x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxHSLDR}\n",
+		         canvas, xpos-3, ypos + x->x_gui.x_h-1,
+		         xpos+4, ypos + x->x_gui.x_h, nlet_tag, 0, x);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxHSLDR}\n",
+		         canvas, xpos-3, ypos,
+		         xpos+4, ypos+1, nlet_tag, 0, x);
+	//}
 }
 
 static void hslider_draw_move(t_hslider *x, t_glist *glist)
@@ -106,31 +123,58 @@ static void hslider_draw_move(t_hslider *x, t_glist *glist)
     int r = xpos + (x->x_val + 50)/100;
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
-             canvas, x,
-             xpos-3, ypos,
-             xpos + x->x_gui.x_w+2, ypos + x->x_gui.x_h);
-    sys_vgui(".x%lx.c coords %lxKNOB %d %d %d %d\n",
-             canvas, x, r, ypos+1,
-             r, ypos + x->x_gui.x_h);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos-3, ypos + x->x_gui.x_h-1,
-             xpos+4, ypos + x->x_gui.x_h);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos-3, ypos,
-             xpos+4, ypos+1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
+		         canvas, x,
+		         xpos-3, ypos,
+		         xpos + x->x_gui.x_w+2, ypos + x->x_gui.x_h);
+		sys_vgui(".x%lx.c coords %lxKNOB %d %d %d %d\n",
+		         canvas, x, r, ypos+1,
+		         r, ypos + x->x_gui.x_h);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos-3, ypos + x->x_gui.x_h-1,
+		         xpos+4, ypos + x->x_gui.x_h);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos-3, ypos,
+		         xpos+4, ypos+1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected) {
+			hslider_draw_select(x, x->x_gui.x_glist);
+		}
+	}
 }
 
 static void hslider_draw_erase(t_hslider* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
+	sys_vgui(".x%lx.c delete %lxHSLDR\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxHSLDR\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+/*
     sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxKNOB\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
@@ -138,15 +182,22 @@ static void hslider_draw_erase(t_hslider* x,t_glist* glist)
         sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+*/
 }
 
 static void hslider_draw_config(t_hslider* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol);
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
     sys_vgui(".x%lx.c itemconfigure %lxKNOB -fill #%6.6x\n", canvas, x, x->x_gui.x_fcol);
     sys_vgui(".x%lx.c itemconfigure %lxBASE -fill #%6.6x\n", canvas, x, x->x_gui.x_bcol);
@@ -158,36 +209,183 @@ static void hslider_draw_io(t_hslider* x,t_glist* glist, int old_snd_rcv_flags)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xpos-3, ypos + x->x_gui.x_h-1,
-             xpos+4, ypos + x->x_gui.x_h, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xpos-3, ypos,
-             xpos+4, ypos+1, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas, xpos-3, ypos + x->x_gui.x_h-1,
+		         xpos+4, ypos + x->x_gui.x_h, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas, xpos-3, ypos,
+		         xpos+4, ypos+1, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+	}
 }
 
 static void hslider_draw_select(t_hslider* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline $select_color\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxHSLDR}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w + 2 - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxHSLDR\n", canvas, x);
+		}
+		else
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+			sys_vgui(".x%lx.c dtag %lxHSLDR selected\n", canvas, x);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void hslider__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_hslider *x = (t_hslider *)(sh->h_master);
+
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
 
-    if(x->x_gui.x_fsf.x_selected)
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_w < SCALE_HSLD_MINWIDTH)
+				x->x_gui.x_w = SCALE_HSLD_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_h < SCALE_HSLD_MINHEIGHT)
+				x->x_gui.x_h = SCALE_HSLD_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			hslider_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix - 3, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + 2 + x->x_gui.x_w,
+					x->x_gui.x_obj.te_ypix + x->x_gui.x_h, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
     }
+    sh->h_dragon = newstate;
 }
 
+static void hslider__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_hslider *x = (t_hslider *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_w - x->x_gui.scale_offset_x + dx;
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h - x->x_gui.scale_offset_y + dy;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_HSLD_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_HSLD_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_HSLD_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_HSLD_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix - 3,
+				 x->x_gui.x_obj.te_ypix, newx + 2, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
+    }
+}
+
+
 void hslider_draw(t_hslider *x, t_glist *glist, int mode)
 {
     if(mode == IEM_GUI_DRAW_MODE_UPDATE)
@@ -208,7 +406,6 @@ void hslider_draw(t_hslider *x, t_glist *glist, int mode)
 
 /* ------------------------ hsl widgetbehaviour----------------------------- */
 
-
 static void hslider_getrect(t_gobj *z, t_glist *glist,
                             int *xp1, int *yp1, int *xp2, int *yp2)
 {
@@ -355,6 +552,8 @@ static void hslider_bang(t_hslider *x)
 
 static void hslider_dialog(t_hslider *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int w = (int)atom_getintarg(0, argc, argv);
     int h = (int)atom_getintarg(1, argc, argv);
@@ -378,6 +577,15 @@ static void hslider_dialog(t_hslider *x, t_symbol *s, int argc, t_atom *argv)
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_IO + sr_flags);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		hslider_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void hslider_motion(t_hslider *x, t_floatarg dx, t_floatarg dy)
@@ -609,6 +817,21 @@ static void *hslider_new(t_symbol *s, int argc, t_atom *argv)
     x->x_thick = 0;
     iemgui_verify_snd_ne_rcv(&x->x_gui);
     outlet_new(&x->x_gui.x_obj, &s_float);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -617,6 +840,13 @@ static void hslider_free(t_hslider *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_hslider_setup(void)
@@ -649,6 +879,14 @@ void g_hslider_setup(void)
     class_addmethod(hslider_class, (t_method)hslider_lin, gensym("lin"), 0);
     class_addmethod(hslider_class, (t_method)hslider_init, gensym("init"), A_FLOAT, 0);
     class_addmethod(hslider_class, (t_method)hslider_steady, gensym("steady"), A_FLOAT, 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)hslider__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)hslider__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     hslider_widgetbehavior.w_getrectfn =    hslider_getrect;
     hslider_widgetbehavior.w_displacefn =   iemgui_displace;
     hslider_widgetbehavior.w_selectfn =     iemgui_select;
@@ -656,6 +894,7 @@ void g_hslider_setup(void)
     hslider_widgetbehavior.w_deletefn =     iemgui_delete;
     hslider_widgetbehavior.w_visfn =        iemgui_vis;
     hslider_widgetbehavior.w_clickfn =      hslider_newclick;
+	hslider_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(hslider_class, &hslider_widgetbehavior);
     class_sethelpsymbol(hslider_class, gensym("hslider"));
     class_setsavefn(hslider_class, hslider_save);
diff --git a/src/g_magicglass.c b/src/g_magicglass.c
new file mode 100644
index 000000000..c450bf8e5
--- /dev/null
+++ b/src/g_magicglass.c
@@ -0,0 +1,413 @@
+#include "m_pd.h"
+#include <stdio.h>
+#include "string.h"
+#include "m_pd.h"
+#include "m_imp.h"
+#include "s_stuff.h"
+#define MG_CLOCK_CLEAR_DELAY 500.5
+#define MG_CLOCK_FLASH_DELAY 50
+#define MG_SAMPLE_COUNT 2205
+
+EXTERN int glist_getfont(t_glist *x);
+
+t_class *magicGlass_class;
+
+typedef struct _magicGlass
+{
+    t_object x_obj;
+    t_object *x_connectedObj;
+    int x_connectedOutno;
+    int x_visible;
+    char x_string[4096];
+    char x_old_string[4096];
+    int x_x;
+    int x_y;
+    int x_c;
+    float x_sigF;
+    int x_dspOn;
+    int x_viewOn;
+    float x_maxSample;
+    int x_sampleCount;
+    t_clock *x_clearClock;
+	t_clock *x_flashClock;
+	unsigned int x_maxSize;
+	unsigned int x_issignal;
+	int x_display_font;
+} t_magicGlass;
+
+void magicGlass_clearText(t_magicGlass *x);
+
+void magicGlass_bind(t_magicGlass *x, t_object *obj, int outno)
+{
+    if (x->x_connectedObj != obj)
+    {
+        if (x->x_connectedObj != NULL)
+        {
+            obj_disconnect(x->x_connectedObj,
+                           x->x_connectedOutno,
+                           &x->x_obj,
+                           0);
+        }
+        x->x_connectedObj = obj;
+        x->x_connectedOutno = outno;
+		x->x_maxSize = 1;
+		magicGlass_clearText(x);
+        obj_connect(obj, outno, &x->x_obj, 0);
+    }
+}
+
+void magicGlass_unbind(t_magicGlass *x)
+{
+    if (x->x_connectedObj != NULL)
+    {
+        obj_disconnect(x->x_connectedObj,
+                       x->x_connectedOutno,
+                       &x->x_obj,
+                       0);
+    }
+    x->x_dspOn = 0;
+    x->x_maxSample = -999999;
+    x->x_sampleCount = 0;
+    x->x_connectedObj = NULL;
+    x->x_connectedOutno = 0;
+	x->x_maxSize = 1;
+}
+
+void magicGlass_updateText(t_magicGlass *x, int moved)
+{
+    int bgSize;
+	/* change second argument (10.0) to provide optimal scaling in the following entry */
+	float font = (float)(sys_hostfontsize(glist_getfont((t_glist *)(x->x_c))))/10.0;
+	if (font <= 1.0) {
+		x->x_display_font = 9;
+		font = 1.0;
+	} else {
+		x->x_display_font = sys_hostfontsize(glist_getfont((t_glist *)(x->x_c)));
+	}
+
+    if (x->x_visible)
+    {
+		if (!moved) {
+			char *color;
+			if (x->x_issignal || strcmp(x->x_old_string, x->x_string)) {
+				color = "#ffffff";
+			}
+			else {
+				color = "#e87216";
+				clock_delay(x->x_flashClock, MG_CLOCK_FLASH_DELAY);
+			}
+		    sys_vgui(".x%x.c itemconfigure magicGlassText -text {%s} -fill %s\n",
+		            x->x_c,
+		            x->x_string,
+					color);
+		} else {
+		    sys_vgui(".x%x.c itemconfigure magicGlassText -text {%s}\n",
+		            x->x_c,
+		            x->x_string);
+		}
+
+        if (strlen(x->x_string) > 0)
+        {
+			if (strlen(x->x_string) > x->x_maxSize) x->x_maxSize = strlen(x->x_string);
+        }
+		bgSize = x->x_x + (int)((30.0 * font) + ((font * 7.0) * (float)x->x_maxSize));
+        sys_vgui(".x%x.c coords magicGlassText %d %d\n",
+                 x->x_c,
+                 x->x_x + 20,
+                 x->x_y);
+        sys_vgui(".x%x.c coords magicGlassLine %d %d %d %d %d %d\n",
+                 x->x_c,
+                 x->x_x + 3,
+                 x->x_y,
+                 x->x_x + 13,
+                 x->x_y + 5,
+                 x->x_x + 13,
+                 x->x_y - 5);
+        sys_vgui(".x%x.c coords magicGlassBg %d %d %d %d\n",
+                 x->x_c,
+                 x->x_x + 13,
+                 x->x_y - (int)(12.0 * font),
+                 bgSize,
+                 x->x_y + (int)(12.0 * font));
+    }
+}
+
+void magicGlass_drawNew(t_magicGlass *x)
+{
+    sys_vgui(".x%x.c create rectangle 0 0 0 0 -outline #ffffff -fill #000000 -tags magicGlassBg\n",
+             x->x_c);
+    sys_vgui(".x%x.c create polygon 0 0 0 0 0 0 -fill #000000 -width 4 -tags magicGlassLine\n",
+             x->x_c);
+    sys_vgui(".x%x.c create text 0 0 -text {} -anchor w -fill #e87216 -font {{%s} %d %s} -tags magicGlassText\n",
+             x->x_c, sys_font, x->x_display_font, sys_fontweight);
+    sys_vgui(".x%x.c raise magicGlassBg\n",
+             x->x_c);
+    sys_vgui(".x%x.c raise magicGlassText\n",
+             x->x_c);
+    magicGlass_updateText(x, 0);
+	clock_delay(x->x_flashClock, MG_CLOCK_FLASH_DELAY);
+}
+
+void magicGlass_undraw(t_magicGlass *x)
+{
+    sys_vgui(".x%x.c delete magicGlassBg\n", x->x_c);
+    sys_vgui(".x%x.c delete magicGlassLine\n", x->x_c);
+    sys_vgui(".x%x.c delete magicGlassText\n", x->x_c);
+}
+
+void magicGlass_flashText(t_magicGlass *x)
+{
+    sys_vgui(".x%x.c itemconfigure magicGlassText -fill #ffffff\n",
+         x->x_c);
+}
+
+void magicGlass_clearText(t_magicGlass *x)
+{
+	strcpy(x->x_old_string, x->x_string);
+    x->x_string[0] = 0;
+    magicGlass_updateText(x, 0);
+}
+
+void magicGlass_bang(t_magicGlass *x) 
+{
+	x->x_issignal = 0;
+	strcpy(x->x_old_string, x->x_string);
+    strcpy(x->x_string, "bang");
+    magicGlass_updateText(x, 0);
+    clock_delay(x->x_clearClock, MG_CLOCK_CLEAR_DELAY);
+}
+
+void magicGlass_float(t_magicGlass *x, t_float f) 
+{
+	x->x_issignal = 0;
+	strcpy(x->x_old_string, x->x_string);
+    sprintf(x->x_string, "%g", f);
+    magicGlass_updateText(x, 0);
+    clock_delay(x->x_clearClock, MG_CLOCK_CLEAR_DELAY);
+}
+
+void magicGlass_symbol(t_magicGlass *x, t_symbol *sym)
+{
+	x->x_issignal = 0;
+	strcpy(x->x_old_string, x->x_string);
+    sprintf(x->x_string, "symbol %s", sym->s_name);
+    magicGlass_updateText(x, 0);
+    clock_delay(x->x_clearClock, MG_CLOCK_CLEAR_DELAY);
+}
+
+void magicGlass_anything(t_magicGlass *x, t_symbol *sym, int argc, t_atom *argv)
+{
+    char aString[4096];
+    char valueString[4096];
+    int i;
+
+	x->x_issignal = 0;
+
+	strcpy(x->x_old_string, x->x_string);
+    strcpy(aString, sym->s_name);
+    valueString[0] = 0;
+    for (i = 0; i < argc; i++)
+    {
+        if (argv[i].a_type == A_SYMBOL)
+        {
+            sprintf(valueString, " %s", argv[i].a_w.w_symbol->s_name);
+            strcat(aString, valueString);
+        }
+        else if (argv[i].a_type == A_FLOAT)
+        {
+            sprintf(valueString, " %g", argv[i].a_w.w_float);
+            strcat(aString, valueString);
+        }
+    }
+    strcpy(x->x_string, aString);
+    magicGlass_updateText(x, 0);
+    clock_delay(x->x_clearClock, MG_CLOCK_CLEAR_DELAY);
+}
+
+void magicGlass_list(t_magicGlass *x, t_symbol *sym, int argc, t_atom *argv)
+{
+    char aString[4096];
+    char valueString[4096];
+    int i;
+
+	x->x_issignal = 0;
+
+    aString[0] = 0;
+    valueString[0] = 0;
+
+	strcpy(x->x_old_string, x->x_string);
+	strcpy(aString, sym->s_name);
+    for (i = 0; i < argc; i++)
+    {
+        if (argv[i].a_type == A_SYMBOL)
+        {
+            sprintf(valueString, " %s", argv[i].a_w.w_symbol->s_name);
+            strcat(aString, valueString);
+        }
+        else if (argv[i].a_type == A_FLOAT)
+        {
+            sprintf(valueString, " %g", argv[i].a_w.w_float);
+            strcat(aString, valueString);
+        }
+    }
+    strcpy(x->x_string, aString);
+    magicGlass_updateText(x, 0);
+    clock_delay(x->x_clearClock, MG_CLOCK_CLEAR_DELAY);
+}
+
+void magicGlass_setCanvas(t_magicGlass *x, int c)
+{
+    x->x_c = c;
+}
+
+void magicGlass_show(t_magicGlass *x)
+{
+    if (!x->x_visible) {
+		x->x_sampleCount = 0;
+		x->x_maxSample = -999999;
+		x->x_string[0] = 0;
+        x->x_visible = 1;
+        magicGlass_drawNew(x);
+    }
+}
+
+void magicGlass_hide(t_magicGlass *x)
+{
+    if (x->x_visible)
+        magicGlass_undraw(x);
+    x->x_sampleCount = 0;
+    x->x_maxSample = -999999;
+    x->x_string[0] = 0;
+    x->x_visible = 0;
+}
+
+void magicGlass_moveText(t_magicGlass *x, int pX, int pY)
+{
+    int bgSize;
+    
+    x->x_x = pX;
+    x->x_y = pY;
+    magicGlass_updateText(x, 1);
+}
+
+int magicGlass_bound(t_magicGlass *x)
+{
+    if (x->x_connectedObj)
+        return 1;
+    else
+        return 0;
+}
+
+int magicGlass_isOn(t_magicGlass *x)
+{
+    if (x->x_viewOn)
+        return 1;
+    else
+        return 0;
+}
+
+void magicGlass_setOn(t_magicGlass *x, int i)
+{
+    if (i)
+    {
+        x->x_viewOn = 1;
+    }
+    else
+    {
+        x->x_viewOn = 0;
+    }
+}
+
+void magicGlass_setDsp(t_magicGlass *x, int i)
+{
+	if (i != x->x_dspOn) {
+		if (i)
+		{
+		    x->x_dspOn = 1;
+		    x->x_sampleCount = 0;
+		    x->x_maxSample = -999999;
+		}
+		else
+		{
+		    x->x_dspOn = 0;
+		}
+	}
+}
+
+t_int *magicGlass_perform(t_int *w)
+{
+    t_magicGlass *x = (t_magicGlass *)(w[1]);
+    float *in = (float *)(w[2]);
+    int N = (int)(w[3]);
+    int i;
+    if (x->x_dspOn)
+    {
+        for (i = 0; i < N; i++)
+        {
+            if (in[i] > x->x_maxSample)
+                x->x_maxSample = in[i];
+            x->x_sampleCount++;
+            if (x->x_sampleCount >= MG_SAMPLE_COUNT)
+            {
+                sprintf(x->x_string, "~ %g", x->x_maxSample);
+                magicGlass_updateText(x, 0);
+                x->x_maxSample = -999999;
+                x->x_sampleCount = 0;
+            }
+        }
+    }
+    return (w + 4);
+}
+
+void magicGlass_dsp(t_magicGlass *x, t_signal **sp)
+{
+    dsp_add(magicGlass_perform, 3, x, sp[0]->s_vec, sp[0]->s_n);
+	x->x_issignal = 1;
+}
+
+void *magicGlass_new(int c)
+{
+    t_magicGlass *x = (t_magicGlass *)pd_new(magicGlass_class);
+    x->x_connectedObj= NULL;
+    x->x_connectedOutno = 0;
+    x->x_visible = 0;
+    x->x_c = c;
+    x->x_sigF = 0;
+    x->x_dspOn = 0;
+    x->x_viewOn = 0;
+    x->x_maxSample = -999999;
+    x->x_sampleCount = 0;
+    x->x_clearClock = clock_new(x, (t_method)magicGlass_clearText);
+    x->x_flashClock = clock_new(x, (t_method)magicGlass_flashText);
+	x->x_maxSize = 1;
+	x->x_issignal = 0;
+	x->x_display_font = 9;
+    return x;
+}
+
+void magicGlass_free(t_magicGlass *x)
+{
+    x->x_dspOn = 0;
+    clock_free(x->x_clearClock);
+}
+
+void magicGlass_setup(void)
+{
+    magicGlass_class = class_new(gensym("magicGlass"),
+                                 (t_newmethod)magicGlass_new,
+                                 (t_method)magicGlass_free,
+                                 sizeof(t_magicGlass),
+                                 0,
+                                 A_DEFFLOAT,
+                                 0);
+    CLASS_MAINSIGNALIN(magicGlass_class, t_magicGlass, x_sigF);
+    class_addmethod(magicGlass_class,
+      	            (t_method)magicGlass_dsp,
+	            gensym("dsp"),
+	            0);
+    class_addbang(magicGlass_class, (t_method)magicGlass_bang);
+    class_addfloat(magicGlass_class, (t_method)magicGlass_float);
+    class_addsymbol(magicGlass_class, (t_method)magicGlass_symbol);
+    class_addanything(magicGlass_class, (t_method)magicGlass_anything);
+    class_addlist(magicGlass_class, (t_method)magicGlass_list);
+}
diff --git a/src/g_magicglass.h b/src/g_magicglass.h
new file mode 100644
index 000000000..b6a80fd2a
--- /dev/null
+++ b/src/g_magicglass.h
@@ -0,0 +1,19 @@
+EXTERN void magicGlass_bind(t_magicGlass *x, t_object *obj, int outno);
+EXTERN void magicGlass_unbind(t_magicGlass *x);
+EXTERN void magicGlass_bang(t_magicGlass *x); 
+EXTERN void magicGlass_float(t_magicGlass *x, t_float f); 
+EXTERN void magicGlass_symbol(t_magicGlass *x, t_symbol *sym);
+EXTERN void magicGlass_anything(t_magicGlass *x, t_symbol *sym, int argc, t_atom *argv);
+EXTERN void magicGlass_list(t_magicGlass *x, t_symbol *sym, int argc, t_atom *argv);
+EXTERN void magicGlass_setCanvas(t_magicGlass *x, int c);
+EXTERN void magicGlass_show(t_magicGlass *x);
+EXTERN void magicGlass_hide(t_magicGlass *x);
+EXTERN void magicGlass_moveText(t_magicGlass *x, int pX, int pY);
+EXTERN int magicGlass_bound(t_magicGlass *x);
+EXTERN int magicGlass_isOn(t_magicGlass *x);
+EXTERN void magicGlass_setOn(t_magicGlass *x, int i);
+EXTERN void magicGlass_setDsp(t_magicGlass *x, int i);
+EXTERN void *magicGlass_new(int c);
+EXTERN void magicGlass_free(t_magicGlass *x);
+EXTERN void magicGlass_setup(void);
+
diff --git a/src/g_mycanvas.c b/src/g_mycanvas.c
index ababf83e4..cb3193b79 100644
--- a/src/g_mycanvas.c
+++ b/src/g_mycanvas.c
@@ -25,6 +25,9 @@
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+void my_canvas_draw_select(t_my_canvas* x, t_glist* glist);
+
 /* ---------- cnv  my gui-canvas for a window ---------------- */
 
 t_widgetbehavior my_canvas_widgetbehavior;
@@ -38,20 +41,26 @@ void my_canvas_draw_new(t_my_canvas *x, t_glist *glist)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags %lxRECT\n",
-             canvas, xpos, ypos,
-             xpos + x->x_vis_w, ypos + x->x_vis_h,
-             x->x_gui.x_bcol, x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -outline #%6.6x -tags %lxBASE\n",
-             canvas, xpos, ypos,
-             xpos + x->x_gui.x_w, ypos + x->x_gui.x_h,
-             x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-			 x->x_gui.x_lcol, x);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(glist)) {
+
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags {%lxRECT %lxMYCNV}\n",
+		         canvas, xpos, ypos,
+		         xpos + x->x_vis_w, ypos + x->x_vis_h,
+		         x->x_gui.x_bcol, x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -outline #%6.6x -tags {%lxBASE %lxMYCNV}\n",
+		         canvas, xpos, ypos,
+		         xpos + x->x_gui.x_w, ypos + x->x_gui.x_h,
+		         x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxMYCNV}\n",
+		         canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+				 x->x_gui.x_lcol, x, x);
+	//}
 }
 
 void my_canvas_draw_move(t_my_canvas *x, t_glist *glist)
@@ -60,34 +69,53 @@ void my_canvas_draw_move(t_my_canvas *x, t_glist *glist)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c coords %lxRECT %d %d %d %d\n",
-             canvas, x, xpos, ypos, xpos + x->x_vis_w,
-             ypos + x->x_vis_h);
-    sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
-             canvas, x, xpos, ypos,
-             xpos + x->x_gui.x_w, ypos + x->x_gui.x_h);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xpos+x->x_gui.x_ldx,
-             ypos+x->x_gui.x_ldy);
+	if (glist_isvisible(canvas)) {
+
+		sys_vgui(".x%lx.c coords %lxRECT %d %d %d %d\n",
+		         canvas, x, xpos, ypos, xpos + x->x_vis_w,
+		         ypos + x->x_vis_h);
+		sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
+		         canvas, x, xpos, ypos,
+		         xpos + x->x_gui.x_w, ypos + x->x_gui.x_h);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xpos+x->x_gui.x_ldx,
+		         ypos+x->x_gui.x_ldy);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected) {
+			my_canvas_draw_select(x, x->x_gui.x_glist);
+		}
+	}
 }
 
 void my_canvas_draw_erase(t_my_canvas* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
-    sys_vgui(".x%lx.c delete %lxRECT\n", canvas, x);
-    sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
+	sys_vgui(".x%lx.c delete %lxMYCNV\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxMYCNV\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+    //sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
+    //sys_vgui(".x%lx.c delete %lxRECT\n", canvas, x);
+    //sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
 }
 
 void my_canvas_draw_config(t_my_canvas* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_bcol);
+
     sys_vgui(".x%lx.c itemconfigure %lxRECT -fill #%6.6x -outline #%6.6x\n", canvas, x,
              x->x_gui.x_bcol, x->x_gui.x_bcol);
-    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_bcol);
+    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline %s\n", canvas, x,
+             color);
     sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
 			 x->x_gui.x_lcol,
@@ -97,14 +125,155 @@ void my_canvas_draw_config(t_my_canvas* x, t_glist* glist)
 void my_canvas_draw_select(t_my_canvas* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxMYCNV}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_vis_w - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_vis_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxMYCNV\n", canvas, x);
+		}
+		else
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, x->x_gui.x_bcol);
+			sys_vgui(".x%lx.c dtag %lxMYCNV selected\n", canvas, x);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void my_canvas__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_my_canvas *x = (t_my_canvas *)(sh->h_master);
 
-    if(x->x_gui.x_fsf.x_selected)
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			x->x_vis_w = x->x_vis_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_vis_w < SCALE_CNV_MINWIDTH)
+				x->x_vis_w = SCALE_CNV_MINWIDTH;
+			x->x_vis_h = x->x_vis_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_vis_h < SCALE_CNV_MINHEIGHT)
+				x->x_vis_h = SCALE_CNV_MINHEIGHT;
+
+			if (x->x_gui.x_w > x->x_vis_w || x->x_gui.x_h > x->x_vis_h) {
+				x->x_gui.x_w = (x->x_vis_w > x->x_vis_h ? x->x_vis_h : x->x_vis_w);
+				x->x_gui.x_h = x->x_gui.x_w;
+			}
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.rng.min_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.rng.min_ent insert 0 %d\n", properties, x->x_vis_w);
+			sys_vgui(".gfxstub%lx.rng.max_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.rng.max_ent insert 0 %d\n", properties, x->x_vis_h);
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			my_canvas_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, x->x_gui.x_bcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + x->x_vis_w,
+					x->x_gui.x_obj.te_ypix + x->x_vis_h, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
+    }
+    sh->h_dragon = newstate;
+}
+
+static void my_canvas__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_my_canvas *x = (t_my_canvas *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+		newx = x->x_gui.x_obj.te_xpix + x->x_vis_w - x->x_gui.scale_offset_x + dx;
+		newy = x->x_gui.x_obj.te_ypix + x->x_vis_h - x->x_gui.scale_offset_y + dy;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_CNV_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_CNV_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_CNV_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_CNV_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix, newx, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_vis_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			int new_h = x->x_vis_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.rng.min_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.rng.min_ent insert 0 %d\n", properties, new_w);
+			sys_vgui(".gfxstub%lx.rng.max_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.rng.max_ent insert 0 %d\n", properties, new_h);
+			int min = (new_w < new_h ? new_w : new_h);
+			if (min <= x->x_gui.x_w) {
+				sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+				sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, min);
+			}
+		}
     }
 }
 
@@ -187,6 +356,8 @@ static void my_canvas_get_pos(t_my_canvas *x)
 
 static void my_canvas_dialog(t_my_canvas *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int a = (int)atom_getintarg(0, argc, argv);
     int w = (int)atom_getintarg(2, argc, argv);
@@ -206,6 +377,15 @@ static void my_canvas_dialog(t_my_canvas *x, t_symbol *s, int argc, t_atom *argv
     x->x_vis_h = h;
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_CONFIG);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		my_canvas_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void my_canvas_size(t_my_canvas *x, t_symbol *s, int ac, t_atom *av)
@@ -348,6 +528,21 @@ static void *my_canvas_new(t_symbol *s, int argc, t_atom *argv)
     x->x_at[0].a_type = A_FLOAT;
     x->x_at[1].a_type = A_FLOAT;
     iemgui_verify_snd_ne_rcv(&x->x_gui);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -356,6 +551,13 @@ static void my_canvas_ff(t_my_canvas *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_mycanvas_setup(void)
@@ -376,6 +578,13 @@ void g_mycanvas_setup(void)
     class_addmethod(my_canvas_class, (t_method)my_canvas_label_font, gensym("label_font"), A_GIMME, 0);
     class_addmethod(my_canvas_class, (t_method)my_canvas_get_pos, gensym("get_pos"), 0);
 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)my_canvas__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)my_canvas__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     my_canvas_widgetbehavior.w_getrectfn = my_canvas_getrect;
     my_canvas_widgetbehavior.w_displacefn = iemgui_displace;
     my_canvas_widgetbehavior.w_selectfn = iemgui_select;
@@ -383,6 +592,7 @@ void g_mycanvas_setup(void)
     my_canvas_widgetbehavior.w_deletefn = iemgui_delete;
     my_canvas_widgetbehavior.w_visfn = iemgui_vis;
     my_canvas_widgetbehavior.w_clickfn = NULL;
+	my_canvas_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(my_canvas_class, &my_canvas_widgetbehavior);
     class_sethelpsymbol(my_canvas_class, gensym("my_canvas"));
     class_setsavefn(my_canvas_class, my_canvas_save);
diff --git a/src/g_numbox.c b/src/g_numbox.c
index 7a413495e..3f0f76bb2 100644
--- a/src/g_numbox.c
+++ b/src/g_numbox.c
@@ -24,6 +24,9 @@
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+static void my_numbox_draw_select(t_my_numbox *x, t_glist *glist);
+
 /*------------------ global varaibles -------------------------*/
 
 
@@ -61,7 +64,7 @@ void my_numbox_clip(t_my_numbox *x)
         x->x_val = x->x_max;
 }
 
-void my_numbox_calc_fontwidth(t_my_numbox *x)
+int my_numbox_calc_fontwidth(t_my_numbox *x)
 {
     int w, f=31;
 
@@ -72,7 +75,8 @@ void my_numbox_calc_fontwidth(t_my_numbox *x)
 
     w = x->x_gui.x_fontsize * f * x->x_gui.x_w;
     w /= 36;
-    x->x_numwidth = w + (x->x_gui.x_h / 2) + 4;
+    w = w + (x->x_gui.x_h / 2) + 4;
+	return w;	
 }
 
 void my_numbox_ftoa(t_my_numbox *x)
@@ -134,11 +138,6 @@ void my_numbox_ftoa(t_my_numbox *x)
 
 static void my_numbox_draw_update(t_gobj *client, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("my_numbox_draw_update");
-        return;
-    }
     t_my_numbox *x = (t_my_numbox *)client;
     if (glist_isvisible(glist))
     {
@@ -169,12 +168,17 @@ static void my_numbox_draw_update(t_gobj *client, t_glist *glist)
         }
         else
         {
+			char color[64];
+			if (x->x_gui.x_fsf.x_selected)
+				sprintf(color, "$select_color");
+			else
+				sprintf(color, "#%6.6x", x->x_gui.x_fcol);
+
             my_numbox_ftoa(x);
             sys_vgui(
-                ".x%lx.c itemconfigure %lxNUMBER -fill #%6.6x -text {%s} \n",
+                ".x%lx.c itemconfigure %lxNUMBER -fill %s -text {%s} \n",
                 glist_getcanvas(glist), x,
-                x->x_gui.x_fsf.x_selected?
-                    IEM_GUI_COLOR_SELECTED:x->x_gui.x_fcol,
+                color,
                 x->x_buf);
             x->x_buf[0] = 0;
         }
@@ -188,45 +192,64 @@ static void my_numbox_draw_new(t_my_numbox *x, t_glist *glist)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(
-".x%lx.c create polygon %d %d %d %d %d %d %d %d %d %d -outline #%6.6x \
--fill #%6.6x -tags %lxBASE1\n",
-             canvas, xpos, ypos,
-             xpos + x->x_numwidth-4, ypos,
-             xpos + x->x_numwidth, ypos+4,
-             xpos + x->x_numwidth, ypos + x->x_gui.x_h,
-             xpos, ypos + x->x_gui.x_h,
-             IEM_GUI_COLOR_NORMAL, x->x_gui.x_bcol, x);
-    sys_vgui(
-        ".x%lx.c create line %d %d %d %d %d %d -fill #%6.6x -tags %lxBASE2\n",
-        canvas, xpos, ypos,
-        xpos + half, ypos + half,
-        xpos, ypos + x->x_gui.x_h,
-        x->x_gui.x_fcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-        -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-        canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
-        strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-        x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_lcol, x);
-    my_numbox_ftoa(x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-        -font {{%s} %d %s} -fill #%6.6x -tags %lxNUMBER\n",
-        canvas, xpos+half+2, ypos+half+d,
-        x->x_buf, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-        x->x_gui.x_fcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos, ypos + x->x_gui.x_h-1,
-             xpos+IOWIDTH, ypos + x->x_gui.x_h,
-             x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos, ypos,
-             xpos+IOWIDTH, ypos+1,
-             x, 0);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(
+	".x%lx.c create polygon %d %d %d %d %d %d %d %d %d %d -outline #%6.6x \
+	-fill #%6.6x -tags {%lxBASE1 %lxNUM}\n",
+		         canvas, xpos, ypos,
+		         xpos + x->x_numwidth-4, ypos,
+		         xpos + x->x_numwidth, ypos+4,
+		         xpos + x->x_numwidth, ypos + x->x_gui.x_h,
+		         xpos, ypos + x->x_gui.x_h,
+		         IEM_GUI_COLOR_NORMAL, x->x_gui.x_bcol, x, x);
+		sys_vgui(
+		    ".x%lx.c create line %d %d %d %d %d %d -fill #%6.6x -tags {%lxBASE2 %lxNUM}\n",
+		    canvas, xpos, ypos,
+		    xpos + half, ypos + half,
+		    xpos, ypos + x->x_gui.x_h,
+		    x->x_gui.x_fcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		    -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxNUM}\n",
+		    canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
+		    strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		    x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+		         x->x_gui.x_lcol, x, x);
+		my_numbox_ftoa(x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		    -font {{%s} %d %s} -fill #%6.6x -tags {%lxNUMBER %lxNUM}\n",
+		    canvas, xpos+half+2, ypos+half+d,
+		    x->x_buf, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+		    x->x_gui.x_fcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxNUM}\n",
+		         canvas,
+		         xpos, ypos + x->x_gui.x_h-1,
+		         xpos+IOWIDTH, ypos + x->x_gui.x_h,
+		         nlet_tag, 0, x);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxNUM}\n",
+		         canvas,
+		         xpos, ypos,
+		         xpos+IOWIDTH, ypos+1,
+		         nlet_tag, 0, x);
+	//}
 }
 
 static void my_numbox_draw_move(t_my_numbox *x, t_glist *glist)
@@ -236,36 +259,62 @@ static void my_numbox_draw_move(t_my_numbox *x, t_glist *glist)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c coords %lxBASE1 %d %d %d %d %d %d %d %d %d %d\n",
-             canvas, x, xpos, ypos,
-             xpos + x->x_numwidth-4, ypos,
-             xpos + x->x_numwidth, ypos+4,
-             xpos + x->x_numwidth, ypos + x->x_gui.x_h,
-             xpos, ypos + x->x_gui.x_h);
-    sys_vgui(".x%lx.c coords %lxBASE2 %d %d %d %d %d %d\n",
-             canvas, x, xpos, ypos,
-             xpos + half, ypos + half,
-             xpos, ypos + x->x_gui.x_h);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
-    sys_vgui(".x%lx.c coords %lxNUMBER %d %d\n",
-             canvas, x, xpos+half+2, ypos+half+d);
-   if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos, ypos + x->x_gui.x_h-1,
-             xpos+IOWIDTH, ypos + x->x_gui.x_h);
-   if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos, ypos,
-             xpos+IOWIDTH, ypos+1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c coords %lxBASE1 %d %d %d %d %d %d %d %d %d %d\n",
+		         canvas, x, xpos, ypos,
+		         xpos + x->x_numwidth-4, ypos,
+		         xpos + x->x_numwidth, ypos+4,
+		         xpos + x->x_numwidth, ypos + x->x_gui.x_h,
+		         xpos, ypos + x->x_gui.x_h);
+		sys_vgui(".x%lx.c coords %lxBASE2 %d %d %d %d %d %d\n",
+		         canvas, x, xpos, ypos,
+		         xpos + half, ypos + half,
+		         xpos, ypos + x->x_gui.x_h);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
+		sys_vgui(".x%lx.c coords %lxNUMBER %d %d\n",
+		         canvas, x, xpos+half+2, ypos+half+d);
+	   if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos, ypos + x->x_gui.x_h-1,
+		         xpos+IOWIDTH, ypos + x->x_gui.x_h);
+	   if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos, ypos,
+		         xpos+IOWIDTH, ypos+1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected)
+			my_numbox_draw_select(x, x->x_gui.x_glist);
+	}
 }
 
 static void my_numbox_draw_erase(t_my_numbox* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
+	sys_vgui(".x%lx.c delete %lxNUM\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxNUM\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+/*
     sys_vgui(".x%lx.c delete %lxBASE1\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxBASE2\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
@@ -274,23 +323,35 @@ static void my_numbox_draw_erase(t_my_numbox* x,t_glist* glist)
         sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+*/
 }
 
 static void my_numbox_draw_config(t_my_numbox* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	char lcolor[64];
+	if (x->x_gui.x_fsf.x_selected) {
+		sprintf(color, "$select_color");
+		sprintf(lcolor, "$select_color");
+	}
+	else {
+		sprintf(color, "#%6.6x", x->x_gui.x_fcol);
+		sprintf(lcolor, "#%6.6x", x->x_gui.x_lcol);
+	}
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             lcolor,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
-    sys_vgui(".x%lx.c itemconfigure %lxNUMBER -font {{%s} %d %s} -fill #%6.6x \n",
+    sys_vgui(".x%lx.c itemconfigure %lxNUMBER -font {{%s} %d %s} -fill %s \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_fcol);
+             color);
     sys_vgui(".x%lx.c itemconfigure %lxBASE1 -fill #%6.6x\n", canvas,
              x, x->x_gui.x_bcol);
-    sys_vgui(".x%lx.c itemconfigure %lxBASE2 -fill #%6.6x\n", canvas,
-             x, x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_fcol);
+    sys_vgui(".x%lx.c itemconfigure %lxBASE2 -fill %s\n", canvas,
+             x, color);
 }
 
 static void my_numbox_draw_io(t_my_numbox* x,t_glist* glist, int old_snd_rcv_flags)
@@ -299,56 +360,233 @@ static void my_numbox_draw_io(t_my_numbox* x,t_glist* glist, int old_snd_rcv_fla
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos, ypos + x->x_gui.x_h-1,
-             xpos+IOWIDTH, ypos + x->x_gui.x_h,
-             x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos, ypos,
-             xpos+IOWIDTH, ypos+1,
-             x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas,
+		         xpos, ypos + x->x_gui.x_h-1,
+		         xpos+IOWIDTH, ypos + x->x_gui.x_h,
+		         nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas,
+		         xpos, ypos,
+		         xpos+IOWIDTH, ypos+1,
+		         nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+
+	}
 }
 
 static void my_numbox_draw_select(t_my_numbox *x, t_glist *glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    if(x->x_gui.x_fsf.x_change)
+		    {
+		        x->x_gui.x_fsf.x_change = 0;
+		        clock_unset(x->x_clock_reset);
+		        x->x_buf[0] = 0;
+		        sys_queuegui(x, x->x_gui.x_glist, my_numbox_draw_update);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE1 -outline $select_color\n",
+		        canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE2 -fill $select_color\n",
+		        canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n",
+		        canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxNUMBER -fill $select_color\n",
+		        canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxNUM}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_numwidth - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxNUM\n", canvas, x);
+		}
+		else
+		{
+			sys_vgui(".x%lx.c dtag %lxNUM selected\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE1 -outline #%6.6x\n",
+		        canvas, x, IEM_GUI_COLOR_NORMAL);
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE2 -fill #%6.6x\n",
+		        canvas, x, x->x_gui.x_fcol);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n",
+		        canvas, x, x->x_gui.x_lcol);
+		    sys_vgui(".x%lx.c itemconfigure %lxNUMBER -fill #%6.6x\n",
+		        canvas, x, x->x_gui.x_fcol);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void my_numbox__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_my_numbox *x = (t_my_numbox *)(sh->h_master);
+
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
 
-    if(x->x_gui.x_fsf.x_selected)
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        if(x->x_gui.x_fsf.x_change)
-        {
-            x->x_gui.x_fsf.x_change = 0;
-            clock_unset(x->x_clock_reset);
-            x->x_buf[0] = 0;
-            sys_queuegui(x, x->x_gui.x_glist, my_numbox_draw_update);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxBASE1 -outline #%6.6x\n",
-            canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxBASE2 -fill #%6.6x\n",
-            canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n",
-            canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxNUMBER -fill #%6.6x\n",
-            canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			x->x_gui.x_fontsize = x->x_tmpfontsize;
+			x->x_gui.x_w = x->x_scalewidth;
+			x->x_gui.x_h = x->x_scaleheight;
+
+			x->x_numwidth = my_numbox_calc_fontwidth(x);
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+			sys_vgui(".gfxstub%lx.label.fontsize_entry delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.label.fontsize_entry insert 0 %d\n", properties, x->x_gui.x_fontsize);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			my_numbox_draw_move(x, x->x_gui.x_glist);
+			my_numbox_draw_config(x, x->x_gui.x_glist);
+			my_numbox_draw_update((t_gobj*)x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
+    {
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + x->x_numwidth,
+					x->x_gui.x_obj.te_ypix + x->x_gui.x_h, sh->h_outlinetag);
+		}
+
+		x->x_scalewidth = x->x_gui.x_w;
+		x->x_scaleheight = x->x_gui.x_h;
+		x->x_tmpfontsize = x->x_gui.x_fontsize;
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
+    }
+    sh->h_dragon = newstate;
+}
+
+static void my_numbox__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE1 -outline #%6.6x\n",
-            canvas, x, IEM_GUI_COLOR_NORMAL);
-        sys_vgui(".x%lx.c itemconfigure %lxBASE2 -fill #%6.6x\n",
-            canvas, x, x->x_gui.x_fcol);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n",
-            canvas, x, x->x_gui.x_lcol);
-        sys_vgui(".x%lx.c itemconfigure %lxNUMBER -fill #%6.6x\n",
-            canvas, x, x->x_gui.x_fcol);
+		t_my_numbox *x = (t_my_numbox *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+
+		/* first calculate y */
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h + (dy - x->x_gui.scale_offset_y);
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_NUM_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_NUM_MINHEIGHT;
+
+		/* then readjust fontsize */
+		x->x_tmpfontsize = (newy - x->x_gui.x_obj.te_ypix) * 0.8;
+		if (x->x_tmpfontsize < IEM_FONT_MINSIZE)
+			x->x_tmpfontsize = IEM_FONT_MINSIZE;
+
+		int f = 31;
+		if(x->x_gui.x_fsf.x_font_style == 1)
+		    f = 27;
+		else if(x->x_gui.x_fsf.x_font_style == 2)
+		    f = 25;
+		int char_w = x->x_tmpfontsize * f;
+		char_w /= 36;
+
+		/* get the new total width */
+		int new_total_width = x->x_numwidth + (dx - x->x_gui.scale_offset_x);
+		
+		/* now figure out what does this translate into in terms of character length */
+		int new_char_len = (new_total_width - ((newy - x->x_gui.x_obj.te_ypix) / 2) - 4) / char_w;
+		if (new_char_len < SCALE_NUM_MINWIDTH)
+			new_char_len = SCALE_NUM_MINWIDTH;
+
+		newx = x->x_gui.x_obj.te_xpix +
+			new_char_len * char_w +
+			((newy - x->x_gui.x_obj.te_ypix) / 2) + 4;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix, newx, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+		x->x_scalewidth = new_char_len;
+		x->x_scaleheight = newy - x->x_gui.x_obj.te_ypix;
+
+		int properties = gfxstub_haveproperties((void *)x);
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_scalewidth);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_scaleheight);
+			sys_vgui(".gfxstub%lx.label.fontsize_entry delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.label.fontsize_entry insert 0 %d\n", properties, x->x_tmpfontsize);
+		}
     }
 }
 
@@ -492,6 +730,8 @@ static void my_numbox_bang(t_my_numbox *x)
 static void my_numbox_dialog(t_my_numbox *x, t_symbol *s, int argc,
     t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int w = (int)atom_getintarg(0, argc, argv);
     int h = (int)atom_getintarg(1, argc, argv);
@@ -513,7 +753,7 @@ static void my_numbox_dialog(t_my_numbox *x, t_symbol *s, int argc,
     if(log_height < 10)
         log_height = 10;
     x->x_log_height = log_height;
-    my_numbox_calc_fontwidth(x);
+    x->x_numwidth = my_numbox_calc_fontwidth(x);
     /*if(my_numbox_check_minmax(x, min, max))
      my_numbox_bang(x);*/
     my_numbox_check_minmax(x, min, max);
@@ -522,6 +762,15 @@ static void my_numbox_dialog(t_my_numbox *x, t_symbol *s, int argc,
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_CONFIG);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		my_numbox_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void my_numbox_motion(t_my_numbox *x, t_floatarg dx, t_floatarg dy)
@@ -620,7 +869,7 @@ static void my_numbox_size(t_my_numbox *x, t_symbol *s, int ac, t_atom *av)
             h = 8;
         x->x_gui.x_h = h;
     }
-    my_numbox_calc_fontwidth(x);
+    x->x_numwidth = my_numbox_calc_fontwidth(x);
     iemgui_size((void *)x, &x->x_gui);
 }
 
@@ -667,7 +916,7 @@ static void my_numbox_label_font(t_my_numbox *x,
     if((f < 0) || (f > 2))
         f = 0;
     x->x_gui.x_fsf.x_font_style = f;
-    my_numbox_calc_fontwidth(x);
+    x->x_numwidth = my_numbox_calc_fontwidth(x);
     iemgui_label_font((void *)x, &x->x_gui, s, ac, av);
 }
 
@@ -761,7 +1010,7 @@ static void *my_numbox_new(t_symbol *s, int argc, t_atom *argv)
     int bflcol[]={-262144, -1, -1};
     int w=5, h=14;
     int lilo=0, f=0, ldx=0, ldy=-8;
-    int fs=10;
+    int fs=11;
     int log_height=256;
     double min=-1.0e+37, max=1.0e+37,v=0.0;
     char str[144];
@@ -832,7 +1081,7 @@ static void *my_numbox_new(t_symbol *s, int argc, t_atom *argv)
         h = 8;
     x->x_gui.x_h = h;
     x->x_buf[0] = 0;
-    my_numbox_calc_fontwidth(x);
+    x->x_numwidth = my_numbox_calc_fontwidth(x);
     my_numbox_check_minmax(x, min, max);
     iemgui_all_colfromload(&x->x_gui, bflcol);
     iemgui_verify_snd_ne_rcv(&x->x_gui);
@@ -840,6 +1089,25 @@ static void *my_numbox_new(t_symbol *s, int argc, t_atom *argv)
     x->x_clock_wait = clock_new(x, (t_method)my_numbox_tick_wait);
     x->x_gui.x_fsf.x_change = 0;
     outlet_new(&x->x_gui.x_obj, &s_float);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+	
+	x->x_scalewidth = 0;
+	x->x_scaleheight = 0;
+	x->x_tmpfontsize = 0;
+
     return (x);
 }
 
@@ -850,6 +1118,13 @@ static void my_numbox_free(t_my_numbox *x)
     clock_free(x->x_clock_reset);
     clock_free(x->x_clock_wait);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_numbox_setup(void)
@@ -906,6 +1181,15 @@ void g_numbox_setup(void)
     my_numbox_widgetbehavior.w_deletefn =     iemgui_delete;
     my_numbox_widgetbehavior.w_visfn =        iemgui_vis;
     my_numbox_widgetbehavior.w_clickfn =      my_numbox_newclick;
+	my_numbox_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)my_numbox__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)my_numbox__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     class_setwidget(my_numbox_class, &my_numbox_widgetbehavior);
     class_sethelpsymbol(my_numbox_class, gensym("numbox2"));
     class_setsavefn(my_numbox_class, my_numbox_save);
diff --git a/src/g_rtext.c b/src/g_rtext.c
index ddee9ba49..0e11706f8 100644
--- a/src/g_rtext.c
+++ b/src/g_rtext.c
@@ -11,6 +11,7 @@
 #include <stdio.h>
 #include <ctype.h>
 #include "m_pd.h"
+#include "m_imp.h"
 #include "s_stuff.h"
 #include "g_canvas.h"
 #include "t_tk.h"
@@ -251,9 +252,19 @@ static void rtext_senditup(t_rtext *x, int action, int *widthp, int *heightp,
                 &x->x_glist->gl_gobj)? "$select_color" : "$text_color"));
     else if (action == SEND_UPDATE)
     {
+		/*fprintf(stderr, "SEND_UPDATE canvas_class=%d isgraph=%d goprect=%d\n",
+			(pd_class(&x->x_text->te_pd) == canvas_class ? 1 : 0),
+			((t_glist *)(x->x_text))->gl_isgraph,
+			((t_glist *)(x->x_text))->gl_goprect );*/
         sys_vgui("pdtk_text_set .x%lx.c %s {%.*s}\n",
             canvas, x->x_tag, outchars, tempbuf);
-        if (pixwide != x->x_drawnwidth || pixhigh != x->x_drawnheight) 
+		/*if ( pd_class(&x->x_text->te_pd) == canvas_class &&
+        	((t_glist *)(x->x_text))->gl_isgraph &&
+        	(((t_glist *)(x->x_text))->gl_goprect) ) {
+			fprintf(stderr, "do not update outlets\n");
+		}
+		else */
+		if (pixwide != x->x_drawnwidth || pixhigh != x->x_drawnheight) 
             text_drawborder(x->x_text, x->x_glist, x->x_tag,
                 pixwide, pixhigh, 0);
         if (x->x_active)
@@ -388,6 +399,14 @@ void rtext_select(t_rtext *x, int state)
     t_canvas *canvas = glist_getcanvas(glist);
     sys_vgui(".x%lx.c itemconfigure %s -fill %s\n", canvas, 
         x->x_tag, (state? "$select_color" : "$text_color"));
+	if (x->x_text->te_pd->c_wb && x->x_text->te_pd->c_wb->w_displacefnwtag) {
+		if (state)
+			sys_vgui(".x%lx.c addtag selected withtag %s\n",
+			   	glist_getcanvas(glist), x->x_tag);
+		else
+			sys_vgui(".x%lx.c dtag %s selected\n",
+		   		glist_getcanvas(glist), x->x_tag);
+	}
     canvas_editing = canvas;
 }
 
@@ -420,6 +439,7 @@ void rtext_key(t_rtext *x, int keynum, t_symbol *keysym)
 {
     int w = 0, h = 0, indx, i, newsize, ndel;
     char *s1, *s2;
+	//post("keysym=%s", keysym->s_name);
     if (keynum)
     {
         int n = keynum;
@@ -479,7 +499,7 @@ be printable in whatever 8-bit character set we find ourselves. */
             x->x_selend = x->x_selstart;
     }
         /* this should be improved...  life's too short */
-    else if (!strcmp(keysym->s_name, "Up"))
+    else if (!strcmp(keysym->s_name, "Up") || !strcmp(keysym->s_name, "Home"))
     {
         if (x->x_selstart)
             x->x_selstart--;
@@ -487,7 +507,7 @@ be printable in whatever 8-bit character set we find ourselves. */
             x->x_selstart--;
         x->x_selend = x->x_selstart;
     }
-    else if (!strcmp(keysym->s_name, "Down"))
+    else if (!strcmp(keysym->s_name, "Down") || !strcmp(keysym->s_name, "End"))
     {
         while (x->x_selend < x->x_bufsize &&
             x->x_buf[x->x_selend] != '\n')
@@ -496,6 +516,31 @@ be printable in whatever 8-bit character set we find ourselves. */
             x->x_selend++;
         x->x_selstart = x->x_selend;
     }
+    else if (!strcmp(keysym->s_name, "CtrlHome"))
+    {
+		/* first find first non-space char going back */
+		while (x->x_selstart > 0 && x->x_buf[x->x_selstart-1] == ' ')
+			x->x_selstart--;
+		/* now go back until you find another space or the beginning of the buffer */
+        while (x->x_selstart > 0 &&
+		  x->x_buf[x->x_selstart] != '\n' &&
+		  x->x_buf[x->x_selstart-1] != ' ')
+            x->x_selstart--;
+        x->x_selend = x->x_selstart;
+    }
+    else if (!strcmp(keysym->s_name, "CtrlEnd"))
+    {
+		/* now go forward until you find another space or the end of the buffer */
+        while (x->x_selend < x->x_bufsize &&
+          x->x_buf[x->x_selend] != '\n' &&
+		  x->x_buf[x->x_selend] != ' ')
+            x->x_selend++;
+		/* now skip all the spaces and land before next word */
+        while (x->x_selend < x->x_bufsize &&
+		  x->x_buf[x->x_selend] == ' ')
+            x->x_selend++;		
+        x->x_selstart = x->x_selend;
+    }
     rtext_senditup(x, SEND_UPDATE, &w, &h, &indx);
 }
 
diff --git a/src/g_scalar.c b/src/g_scalar.c
index 85ba887ed..0896eec17 100644
--- a/src/g_scalar.c
+++ b/src/g_scalar.c
@@ -410,6 +410,7 @@ static t_widgetbehavior scalar_widgetbehavior =
     scalar_delete,
     scalar_vis,
     scalar_click,
+	NULL,
 };
 
 static void scalar_free(t_scalar *x)
diff --git a/src/g_text.c b/src/g_text.c
index 648139f7d..777303ce1 100644
--- a/src/g_text.c
+++ b/src/g_text.c
@@ -28,6 +28,10 @@ static void text_getrect(t_gobj *z, t_glist *glist,
 void canvas_startmotion(t_canvas *x);
 t_widgetbehavior text_widgetbehavior;
 
+static char *invalid_fill = "\"#ffdddd\"";
+
+EXTERN void canvas_apply_setundo(t_canvas *x, t_gobj *y);
+
 /* ----------------- the "text" object.  ------------------ */
 
     /* add a "text" object (comment) to a glist.  While this one goes for any
@@ -164,6 +168,7 @@ static void canvas_howputnew(t_canvas *x, int *connectp, int *xpixp, int *ypixp,
             else if (!g->g_next)
                 indx = nobj-1;
         }
+		sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x);
     }
     else
     {
@@ -211,17 +216,39 @@ void canvas_obj(t_glist *gl, t_symbol *s, int argc, t_atom *argv)
 /* iemlib */
 void canvas_iemguis(t_glist *gl, t_symbol *guiobjname)
 {
+	//fprintf(stderr,"canvas_iemguis\n");
     t_atom at;
     t_binbuf *b = binbuf_new();
-    int xpix, ypix;
-
+    //int xpix, ypix;
+
+	if(!strcmp(guiobjname->s_name, "cnv"))
+		glist_noselect(gl);
+
+	int connectme, xpix, ypix, indx, nobj;
+    canvas_howputnew(gl, &connectme, &xpix, &ypix, &indx, &nobj);
+
+	/*compensate for the iemgui sliders' xyoffset in the case of autopatch */
+	if(connectme) {
+		if(!strcmp(guiobjname->s_name, "hsl"))
+			xpix = xpix + 3;
+		else if(!strcmp(guiobjname->s_name, "vsl"))
+			ypix = ypix + 2;
+		else if(!strcmp(guiobjname->s_name, "vu")) {
+			xpix = xpix + 1;
+			ypix = ypix + 2;
+		}
+	}
+	
     pd_vmess(&gl->gl_pd, gensym("editmode"), "i", 1);
     glist_noselect(gl);
     SETSYMBOL(&at, guiobjname);
     binbuf_restore(b, 1, &at);
-    glist_getnextxy(gl, &xpix, &ypix);
-    canvas_objtext(gl, xpix, ypix, 1, b);
-    canvas_startmotion(glist_getcanvas(gl));
+	canvas_objtext(gl, xpix, ypix, 1, b);
+    if (connectme)
+        canvas_connect(gl, indx, 0, nobj, 0);
+    //glist_getnextxy(gl, &xpix, &ypix);
+    //canvas_objtext(gl, xpix, ypix, 1, b);
+    else canvas_startmotion(glist_getcanvas(gl));
 }
 
 void canvas_bng(t_glist *gl, t_symbol *s, int argc, t_atom *argv)
@@ -758,6 +785,8 @@ static void gatom_click(t_gatom *x,
     /* message back from dialog window */
 static void gatom_param(t_gatom *x, t_symbol *sel, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->a_glist, (t_gobj *)x);
+
     t_float width = atom_getfloatarg(0, argc, argv);
     t_float draglo = atom_getfloatarg(1, argc, argv);
     t_float draghi = atom_getfloatarg(2, argc, argv);
@@ -804,6 +833,7 @@ static void gatom_param(t_gatom *x, t_symbol *sel, int argc, t_atom *argv)
     x->a_symto = symto;
     x->a_expanded_to = canvas_realizedollar(x->a_glist, x->a_symto);
     gobj_vis(&x->a_text.te_g, x->a_glist, 1);
+	gobj_select(&x->a_text.te_g, x->a_glist, 1);
     canvas_dirty(x->a_glist, 1);
 
     /* glist_retext(x->a_glist, &x->a_text); */
@@ -1008,6 +1038,13 @@ static void text_getrect(t_gobj *z, t_glist *glist,
         that yet.  So we check directly whether the "rtext" list has been
         built.  LATER reconsider when "vis" flag should be on and off? */
 
+    // jsarlo
+    else if (strcmp("magicGlass", class_getname(x->ob_pd)) == 0)
+    {
+        width = 0;
+        height = 0;
+    }
+    // end jsarlo
     else if (glist->gl_editor && glist->gl_editor->e_rtext)
     {
         t_rtext *y = glist_findrtext(glist, x);
@@ -1042,6 +1079,30 @@ static void text_displace(t_gobj *z, t_glist *glist,
     }
 }
 
+static void text_displace_withtag(t_gobj *z, t_glist *glist,
+    int dx, int dy)
+{
+    t_text *x = (t_text *)z;
+    x->te_xpix += dx;
+    x->te_ypix += dy;
+    if (glist_isvisible(glist))
+    {
+        t_rtext *y = glist_findrtext(glist, x);
+        text_drawborder_withtag(x, glist, rtext_gettag(y),
+            rtext_width(y), rtext_height(y), 0);
+        canvas_fixlinesfor(glist_getcanvas(glist), x);
+    }
+}
+
+static void gatom_displace_withtag(t_gobj *z, t_glist *glist,
+    int dx, int dy)
+{
+    t_gatom *x = (t_gatom*)z;
+    text_displace_withtag(z, glist, dx, dy);
+    sys_vgui(".x%lx.c move %lx.l %d %d\n", glist_getcanvas(glist), 
+        x, dx, dy);
+}
+
 static void text_select(t_gobj *z, t_glist *glist, int state)
 {
     t_text *x = (t_text *)z;
@@ -1052,9 +1113,55 @@ static void text_select(t_gobj *z, t_glist *glist, int state)
         outline = "$dash_outline";
     else
         outline = "$box_outline";
-    if (glist_isvisible(glist) && gobj_shouldvis(&x->te_g, glist))
-        sys_vgui(".x%lx.c itemconfigure %sR -outline %s\n", glist, 
+    if (glist_isvisible(glist) && gobj_shouldvis(&x->te_g, glist)) {
+        sys_vgui(".x%lx.c itemconfigure %sR -outline %s\n", glist_getcanvas(glist), 
                  rtext_gettag(y), (state? "$select_color" : outline));
+		if (z->g_pd->c_wb && z->g_pd->c_wb->w_displacefnwtag) {
+			int i, ni, no;
+			if (state) {
+		    	sys_vgui(".x%lx.c addtag selected withtag %sR \n",
+		    	    glist_getcanvas(glist), rtext_gettag(y));
+
+				if (pd_class(&x->te_pd) == text_class)
+	        		sys_vgui(".x%lx.c itemconfigure %sR -width 1 -fill $obj_box_fill\n",
+						glist_getcanvas(glist), rtext_gettag(y));
+
+				t_object *ob = pd_checkobject(&x->te_pd);
+				int no = obj_noutlets(ob);
+				int ni = obj_ninlets(ob);
+
+				for (i = 0; i < no; i++) {
+					sys_vgui(".x%lx.c addtag selected withtag %so%d \n",
+									glist_getcanvas(glist), rtext_gettag(y), i);
+				}
+				for (i = 0; i < ni; i++) {
+					sys_vgui(".x%lx.c addtag selected withtag %si%d \n",
+        	    		glist_getcanvas(glist), rtext_gettag(y), i);
+				}
+			} else {
+		    	sys_vgui(".x%lx.c dtag %sR selected\n",
+		        	glist_getcanvas(glist), rtext_gettag(y));
+
+				if (pd_class(&x->te_pd) == text_class)
+			   		sys_vgui(".x%lx.c itemconfigure %sR -width 2 -fill %s\n",
+						glist_getcanvas(glist), 
+		            	rtext_gettag(y), invalid_fill);
+
+				t_object *ob = pd_checkobject(&x->te_pd);
+				int no = obj_noutlets(ob);
+				int ni = obj_ninlets(ob);
+
+				for (i = 0; i < no; i++) {
+					sys_vgui(".x%lx.c dtag %so%d selected\n",
+		    	    	glist_getcanvas(glist), rtext_gettag(y), i);
+				}
+				for (i = 0; i < ni; i++) {
+					sys_vgui(".x%lx.c dtag %si%d selected\n",
+		    	    	glist_getcanvas(glist), rtext_gettag(y), i);
+				}
+			}
+		}
+	}
 }
 
 static void text_activate(t_gobj *z, t_glist *glist, int state)
@@ -1132,6 +1239,7 @@ static int text_click(t_gobj *z, struct _glist *glist,
 
 void text_save(t_gobj *z, t_binbuf *b)
 {
+	//fprintf(stderr, "text_save\n");
     t_text *x = (t_text *)z;
     if (x->te_type == T_OBJECT)
     {
@@ -1142,20 +1250,25 @@ void text_save(t_gobj *z, t_binbuf *b)
                 (canvas_isabstraction((t_canvas *)x)
                     || canvas_istable((t_canvas *)x))))
         {  
+			//fprintf(stderr, "saveto\n");
             mess1(&x->te_pd, gensym("saveto"), b);
             binbuf_addv(b, "ssii", gensym("#X"), gensym("restore"),
                 (int)x->te_xpix, (int)x->te_ypix);
         }
         else    /* otherwise just save the text */
         {
+			//fprintf(stderr, "is this gop?\n");
             binbuf_addv(b, "ssii", gensym("#X"), gensym("obj"),
                 (int)x->te_xpix, (int)x->te_ypix);
         }
+		//fprintf(stderr, "this must be it\n");
         binbuf_addbinbuf(b, x->te_binbuf);
+		//fprintf(stderr, "DONE this must be it\n");
         binbuf_addv(b, ";");
     }
     else if (x->te_type == T_MESSAGE)
     {
+		//fprintf(stderr, "message\n");
         binbuf_addv(b, "ssii", gensym("#X"), gensym("msg"),
             (int)x->te_xpix, (int)x->te_ypix);
         binbuf_addbinbuf(b, x->te_binbuf);
@@ -1163,6 +1276,7 @@ void text_save(t_gobj *z, t_binbuf *b)
     }
     else if (x->te_type == T_ATOM)
     {
+		//fprintf(stderr, "atom\n");
         t_atomtype t = ((t_gatom *)x)->a_atom.a_type;
         t_symbol *sel = (t == A_SYMBOL ? gensym("symbolatom") :
             (t == A_FLOAT ? gensym("floatatom") : gensym("intatom")));
@@ -1179,6 +1293,7 @@ void text_save(t_gobj *z, t_binbuf *b)
     }           
     else        
     {
+		//fprintf(stderr, "text\n");
         binbuf_addv(b, "ssii", gensym("#X"), gensym("text"),
             (int)x->te_xpix, (int)x->te_ypix);
         binbuf_addbinbuf(b, x->te_binbuf);
@@ -1196,6 +1311,7 @@ t_widgetbehavior text_widgetbehavior =
     text_delete,
     text_vis,
     text_click,
+    text_displace_withtag,
 };
 
 static t_widgetbehavior gatom_widgetbehavior =
@@ -1207,6 +1323,7 @@ static t_widgetbehavior gatom_widgetbehavior =
     text_delete,
     gatom_vis,
     text_click,
+    gatom_displace_withtag,
 };
 
 /* -------------------- the "text" class  ------------ */
@@ -1238,6 +1355,12 @@ void glist_drawiofor(t_glist *glist, t_object *ob, int firsttime,
                 glist_getcanvas(glist), tag, i,
                 onset, y2 - 2,
                 onset + IOWIDTH, y2);
+				// jsarlo
+				sys_vgui(".x%x.c raise %so%d\n",
+				         glist_getcanvas(glist),
+				         tag,
+				         i);
+				// end jsarlo
     }
     n = obj_ninlets(ob);
     nplus = (n == 1 ? 1 : n-1);
@@ -1259,38 +1382,121 @@ void glist_drawiofor(t_glist *glist, t_object *ob, int firsttime,
                 glist_getcanvas(glist), tag, i,
                 onset, y1,
                 onset + IOWIDTH, y1 + EXTRAPIX);
+				// jsarlo   
+				sys_vgui(".x%x.c raise %si%d\n",
+				         glist_getcanvas(glist),
+				         tag,
+				         i);
+				// end jsarlo
     }
 }
 
+    /* draw inlets and outlets for a text object or for a graph. */
+void glist_drawiofor_withtag(t_glist *glist, t_object *ob, int firsttime,
+    char *tag, int x1, int y1, int x2, int y2)
+{
+    int n = obj_noutlets(ob), nplus = (n == 1 ? 1 : n-1), i;
+    int width = x2 - x1;
+    int issignal;
+    for (i = 0; i < n; i++)
+    {
+        int onset = x1 + (width - IOWIDTH) * i / nplus;
+        if (firsttime)
+        {
+            issignal = obj_issignaloutlet(ob,i);
+            sys_vgui(".x%lx.c create rectangle %d %d %d %d \
+                      -fill %s -outline %s -tags %so%d\n",
+                glist_getcanvas(glist), onset, y2 - 2, onset + IOWIDTH, y2,
+                (issignal ? "$signal_nlet" : "$msg_nlet"),
+                (issignal ? "$signal_cord" : "$msg_cord"),
+                tag, i);
+        }
+/*
+		else
+		{
+			sys_vgui(".x%lx.c addtag selected withtag %so%d \n",
+        	    glist_getcanvas(glist), tag, i);
+		}
+*/
+    }
+    n = obj_ninlets(ob);
+    nplus = (n == 1 ? 1 : n-1);
+    for (i = 0; i < n; i++)
+    {
+        int onset = x1 + (width - IOWIDTH) * i / nplus;
+        if (firsttime)
+        {
+            issignal = obj_issignalinlet(ob,i);
+            sys_vgui(".x%lx.c create rectangle %d %d %d %d \
+                      -fill %s -outline %s -tags %si%d\n",
+                glist_getcanvas(glist), onset, y1, onset + IOWIDTH, y1 + EXTRAPIX,
+                (issignal ? "$signal_nlet" : "$msg_nlet"),
+                (issignal ? "$signal_cord" : "$msg_cord"),
+                tag, i);
+        }
+/*
+		else
+		{
+			sys_vgui(".x%lx.c addtag selected withtag %si%d \n",
+        	    glist_getcanvas(glist), tag, i);
+		}
+*/
+    }
+}
+
+
 void text_drawborder(t_text *x, t_glist *glist,
     char *tag, int width2, int height2, int firsttime)
 {
     t_object *ob;
     int x1, y1, x2, y2, width, height, msg_draw_const, atom_draw_const;
-    text_getrect(&x->te_g, glist, &x1, &y1, &x2, &y2);
+
+	/* if this is gop patcher, the getrect should be equal to gop-ed window
+	   rather than just the size of text */
+	if (pd_class(&x->te_pd) == canvas_class &&
+        ((t_glist *)x)->gl_isgraph &&
+        ((t_glist *)x)->gl_goprect &&
+		!(((t_glist *)x)->gl_havewindow) ) {
+
+		int gop_width = ((t_glist *)x)->gl_pixwidth;
+		int gop_height = ((t_glist *)x)->gl_pixheight;
+		text_getrect(&x->te_g, glist, &x1, &y1, &x2, &y2);
+		/*fprintf(stderr,"text = %d %d %d %d     gop = %d %d\n",
+			x1, y1, x2, y2, gop_width, gop_height); */
+		if (gop_width > (x2-x1)) x2 = x1 + gop_width;
+		if (gop_height > (y2-y1)) y2 = y1 + gop_height;
+	} else {
+    	text_getrect(&x->te_g, glist, &x1, &y1, &x2, &y2);
+	}
+
     width = x2 - x1;
     height = y2 - y1;
     if (x->te_type == T_OBJECT)
     {
-        char *pattern; char *outline;
+        char *pattern; char *outline; char *fill;
         if (pd_class(&x->te_pd) == text_class)
         {
             pattern = "-";
-            outline = "$dash_outline";
+            outline = "$dash_outline -width 2";
+			fill = invalid_fill;
         }
         else
         {
             pattern = "\"\"";
             outline = "$box_outline";
+			fill = "$obj_box_fill";
         }
         if (firsttime)
+		{
             sys_vgui(".x%lx.c create polygon %d %d %d %d %d %d %d %d %d %d \
-                      -dash %s -outline %s -fill $obj_box_fill -tags %sR\n", 
+                      -dash %s -outline %s -fill %s -tags %sR\n", 
                 glist_getcanvas(glist),
                      x1, y1,  x2, y1,  x2, y2,  x1, y2,  x1, y1,  
-                     pattern, outline, tag);
+                     pattern, outline, fill, tag);
+        }
         else
         {
+			//fprintf(stderr, "redrawing rectangle? .x%lx.c %sR\n", (t_int)glist_getcanvas(glist), tag);
             sys_vgui(".x%lx.c coords %sR %d %d %d %d %d %d %d %d %d %d\n",
                 glist_getcanvas(glist), tag,
                     x1, y1,  x2, y1,  x2, y2,  x1, y2,  x1, y1);
@@ -1304,6 +1510,7 @@ void text_drawborder(t_text *x, t_glist *glist,
         msg_draw_const = ((y2-y1)/4);
         if (msg_draw_const > 10) msg_draw_const = 10; /* looks bad if too big */
         if (firsttime)
+		{
             sys_vgui(".x%lx.c create polygon \
                      %d %d %d %d %d %d %d %d %d %d %d %d %d %d \
                      -outline $box_outline -fill $msg_box_fill -tags %sR\n",
@@ -1311,39 +1518,120 @@ void text_drawborder(t_text *x, t_glist *glist,
                      x1, y1,  x2+msg_draw_const, y1,  x2, y1+msg_draw_const,  
                      x2, y2-msg_draw_const,  x2+msg_draw_const, y2,  
                 x1, y2,  x1, y1,
-                    tag);
+                    tag);	
+        }
         else
+        {
             sys_vgui(".x%lx.c coords %sR\
  %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
                 glist_getcanvas(glist), tag,
                 x1, y1,  x2+msg_draw_const, y1,  x2, y1+msg_draw_const,
                 x2, y2-msg_draw_const, x2+msg_draw_const, y2,  x1, y2,  x1, y1);
+        }
     }
     else if (x->te_type == T_ATOM)
     {
         atom_draw_const = ((y2-y1)/3);
         if (firsttime)
+		{
             sys_vgui(".x%lx.c create polygon %d %d %d %d %d %d %d %d %d %d %d %d \
                      -outline $box_outline -fill $atom_box_fill -tags %sR\n",
                 glist_getcanvas(glist),
                      x1, y1,  x2-atom_draw_const, y1,  x2, y1+atom_draw_const,  
                      x2, y2,  x1, y2,  x1, y1, 
                     tag);
-        else
+         }
+         else
+         {
             sys_vgui(".x%lx.c coords %sR\
  %d %d %d %d %d %d %d %d %d %d %d %d\n",
                 glist_getcanvas(glist), tag,
                 x1, y1,  x2-atom_draw_const, y1,  x2, y1+atom_draw_const,
                 x2, y2,  x1, y2,  x1, y1);
+         }
+    }
+
+	/* draw inlets/outlets */    
+    if (ob = pd_checkobject(&x->te_pd)) {
+        glist_drawiofor(glist, ob, firsttime, tag, x1, y1, x2, y2);
+	}
+    if (firsttime && glist==glist_getcanvas(glist)) /* raise cords over everything else */
+        sys_vgui(".x%lx.c raise all_cords\n", glist_getcanvas(glist));
+
+	//ico@bukvic.net 100518 update scrollbars when GOP potentially exceeds window size
+	//sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)glist_getcanvas(glist));
+}
+
+void text_drawborder_withtag(t_text *x, t_glist *glist,
+    char *tag, int width2, int height2, int firsttime)
+{
+    t_object *ob;
+    int x1, y1, x2, y2, width, height, msg_draw_const, atom_draw_const;
+    text_getrect(&x->te_g, glist, &x1, &y1, &x2, &y2);
+    width = x2 - x1;
+    height = y2 - y1;
+    if (x->te_type == T_OBJECT)
+    {
+        char *pattern; char *outline; char *fill;
+        if (pd_class(&x->te_pd) == text_class)
+        {
+            pattern = "-";
+            outline = "$dash_outline -width 2";
+			fill = invalid_fill;
+        }
+        else
+        {
+            pattern = "\"\"";
+            outline = "$box_outline";
+			fill = "$obj_box_fill";
+        }
+        if (firsttime)
+		{
+            sys_vgui(".x%lx.c create polygon %d %d %d %d %d %d %d %d %d %d \
+                      -dash %s -outline %s -fill %s -tags %sR\n", 
+                glist_getcanvas(glist),
+                     x1, y1,  x2, y1,  x2, y2,  x1, y2,  x1, y1,  
+                     pattern, outline, fill, tag);
+        }
+    }
+    else if (x->te_type == T_MESSAGE)
+    {
+        msg_draw_const = ((y2-y1)/4);
+        if (msg_draw_const > 10) msg_draw_const = 10; /* looks bad if too big */
+        if (firsttime)
+            sys_vgui(".x%lx.c create polygon \
+                     %d %d %d %d %d %d %d %d %d %d %d %d %d %d \
+                     -outline $box_outline -fill $msg_box_fill -tags %sR\n",
+                glist_getcanvas(glist),
+                     x1, y1,  x2+msg_draw_const, y1,  x2, y1+msg_draw_const,  
+                     x2, y2-msg_draw_const,  x2+msg_draw_const, y2,  
+                x1, y2,  x1, y1,
+                    tag);
+    }
+    else if (x->te_type == T_ATOM)
+    {
+        atom_draw_const = ((y2-y1)/3);
+        if (firsttime)
+            sys_vgui(".x%lx.c create polygon %d %d %d %d %d %d %d %d %d %d %d %d \
+                     -outline $box_outline -fill $atom_box_fill -tags %sR\n",
+                glist_getcanvas(glist),
+                     x1, y1,  x2-atom_draw_const, y1,  x2, y1+atom_draw_const,  
+                     x2, y2,  x1, y2,  x1, y1, 
+                    tag);
     }
         /* draw inlets/outlets */
     
-    if (ob = pd_checkobject(&x->te_pd))
-        glist_drawiofor(glist, ob, firsttime, tag, x1, y1, x2, y2);
-    if (firsttime) /* raise cords over everything else */
+    if (ob = pd_checkobject(&x->te_pd)) {
+        glist_drawiofor_withtag(glist, ob, firsttime, tag, x1, y1, x2, y2);
+	}
+    if (firsttime && glist==glist_getcanvas(glist)) /* raise cords over everything else */
         sys_vgui(".x%lx.c raise all_cords\n", glist_getcanvas(glist));
+
+	//ico@bukvic.net 100518 update scrollbars when GOP potentially exceeds window size
+	//sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)glist_getcanvas(glist));
 }
 
+
 void glist_eraseiofor(t_glist *glist, t_object *ob, char *tag)
 {
     int i, n;
diff --git a/src/g_toggle.c b/src/g_toggle.c
index a9d2b0207..be2122d4e 100644
--- a/src/g_toggle.c
+++ b/src/g_toggle.c
@@ -25,6 +25,10 @@
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+void toggle_draw_select(t_toggle* x, t_glist* glist);
+ 
+
 /* --------------- tgl     gui-toggle ------------------------- */
 
 t_widgetbehavior toggle_widgetbehavior;
@@ -34,11 +38,6 @@ static t_class *toggle_class;
 
 void toggle_draw_update(t_toggle *x, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("toggle_draw_update");
-        return;
-    }
     if(glist_isvisible(glist))
     {
         t_canvas *canvas=glist_getcanvas(glist);
@@ -55,32 +54,51 @@ void toggle_draw_new(t_toggle *x, t_glist *glist)
     t_canvas *canvas=glist_getcanvas(glist);
     int w=1, xx=text_xpix(&x->x_gui.x_obj, glist), yy=text_ypix(&x->x_gui.x_obj, glist);
 
-    if(x->x_gui.x_w >= 30)
-        w = 2;
-    if(x->x_gui.x_w >= 60)
-        w = 3;
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE\n",
-             canvas, xx, yy, xx + x->x_gui.x_w, yy + x->x_gui.x_h,
-             x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags %lxX1\n",
-             canvas, xx+w+1, yy+w+1, xx + x->x_gui.x_w-w, yy + x->x_gui.x_h-w, w,
-             (x->x_on!=0.0)?x->x_gui.x_fcol:x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags %lxX2\n",
-             canvas, xx+w+1, yy + x->x_gui.x_h-w-1, xx + x->x_gui.x_w-w, yy+w, w,
-             (x->x_on!=0.0)?x->x_gui.x_fcol:x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xx+x->x_gui.x_ldx,
-             yy+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xx, yy + x->x_gui.x_h-1, xx + IOWIDTH, yy + x->x_gui.x_h, x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xx, yy, xx + IOWIDTH, yy+1, x, 0);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if(x->x_gui.x_w >= 30)
+		    w = 2;
+		if(x->x_gui.x_w >= 60)
+		    w = 3;
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE %lxTGL}\n",
+		         canvas, xx, yy, xx + x->x_gui.x_w, yy + x->x_gui.x_h,
+		         x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags {%lxX1 %lxTGL}\n",
+		         canvas, xx+w+1, yy+w+1, xx + x->x_gui.x_w-w, yy + x->x_gui.x_h-w, w,
+		         (x->x_on!=0.0)?x->x_gui.x_fcol:x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags {%lxX2 %lxTGL}\n",
+		         canvas, xx+w+1, yy + x->x_gui.x_h-w-1, xx + x->x_gui.x_w-w, yy+w, w,
+		         (x->x_on!=0.0)?x->x_gui.x_fcol:x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxTGL}\n",
+		         canvas, xx+x->x_gui.x_ldx,
+		         yy+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+		         x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxTGL}\n",
+		         canvas, xx, yy + x->x_gui.x_h-1, xx + IOWIDTH, yy + x->x_gui.x_h, nlet_tag, 0, x);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxTGL}\n",
+		         canvas, xx, yy, xx + IOWIDTH, yy+1, nlet_tag, 0, x);
+	//}
 }
 
 void toggle_draw_move(t_toggle *x, t_glist *glist)
@@ -88,33 +106,59 @@ void toggle_draw_move(t_toggle *x, t_glist *glist)
     t_canvas *canvas=glist_getcanvas(glist);
     int w=1, xx=text_xpix(&x->x_gui.x_obj, glist), yy=text_ypix(&x->x_gui.x_obj, glist);
 
-    if(x->x_gui.x_w >= 30)
-        w = 2;
-
-    if(x->x_gui.x_w >= 60)
-        w = 3;
-    sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
-             canvas, x, xx, yy, xx + x->x_gui.x_w, yy + x->x_gui.x_h);
-    sys_vgui(".x%lx.c itemconfigure %lxX1 -width %d\n", canvas, x, w);
-    sys_vgui(".x%lx.c coords %lxX1 %d %d %d %d\n",
-             canvas, x, xx+w+1, yy+w+1, xx + x->x_gui.x_w-w, yy + x->x_gui.x_h-w);
-    sys_vgui(".x%lx.c itemconfigure %lxX2 -width %d\n", canvas, x, w);
-    sys_vgui(".x%lx.c coords %lxX2 %d %d %d %d\n",
-             canvas, x, xx+w+1, yy + x->x_gui.x_h-w-1, xx + x->x_gui.x_w-w, yy+w);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xx+x->x_gui.x_ldx, yy+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0, xx, yy + x->x_gui.x_h-1, xx + IOWIDTH, yy + x->x_gui.x_h);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0, xx, yy, xx + IOWIDTH, yy+1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if(x->x_gui.x_w >= 30)
+		    w = 2;
+
+		if(x->x_gui.x_w >= 60)
+		    w = 3;
+		sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
+		         canvas, x, xx, yy, xx + x->x_gui.x_w, yy + x->x_gui.x_h);
+		sys_vgui(".x%lx.c itemconfigure %lxX1 -width %d\n", canvas, x, w);
+		sys_vgui(".x%lx.c coords %lxX1 %d %d %d %d\n",
+		         canvas, x, xx+w+1, yy+w+1, xx + x->x_gui.x_w-w, yy + x->x_gui.x_h-w);
+		sys_vgui(".x%lx.c itemconfigure %lxX2 -width %d\n", canvas, x, w);
+		sys_vgui(".x%lx.c coords %lxX2 %d %d %d %d\n",
+		         canvas, x, xx+w+1, yy + x->x_gui.x_h-w-1, xx + x->x_gui.x_w-w, yy+w);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xx+x->x_gui.x_ldx, yy+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xx, yy + x->x_gui.x_h-1, xx + IOWIDTH, yy + x->x_gui.x_h);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xx, yy, xx + IOWIDTH, yy+1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected)
+			toggle_draw_select(x, x->x_gui.x_glist);
+	}
 }
 
 void toggle_draw_erase(t_toggle* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
+	sys_vgui(".x%lx.c delete %lxTGL\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxTGL\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+/*
     sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxX1\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxX2\n", canvas, x);
@@ -123,15 +167,22 @@ void toggle_draw_erase(t_toggle* x, t_glist* glist)
         sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+*/
 }
 
 void toggle_draw_config(t_toggle* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol); 
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
     sys_vgui(".x%lx.c itemconfigure %lxBASE -fill #%6.6x\n", canvas, x,
              x->x_gui.x_bcol);
@@ -147,37 +198,198 @@ void toggle_draw_io(t_toggle* x, t_glist* glist, int old_snd_rcv_flags)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xpos,
-             ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
-             ypos + x->x_gui.x_h, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xpos, ypos,
-             xpos + IOWIDTH, ypos+1, x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas, xpos,
+		         ypos + x->x_gui.x_h-1, xpos + IOWIDTH,
+		         ypos + x->x_gui.x_h, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas, xpos, ypos,
+		         xpos + IOWIDTH, ypos+1, nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+	}
 }
 
 void toggle_draw_select(t_toggle* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline $select_color\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxTGL}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxTGL\n", canvas, x);
+		}
+		else
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+			sys_vgui(".x%lx.c dtag %lxTGL selected\n", canvas, x);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void toggle__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_toggle *x = (t_toggle *)(sh->h_master);
 
-    if(x->x_gui.x_fsf.x_selected)
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			if (sh->h_dragx > sh->h_dragy)
+				sh->h_dragx = sh->h_dragy;
+			else sh->h_dragy = sh->h_dragx;
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_w < SCALE_TGL_MINWIDTH)
+				x->x_gui.x_w = SCALE_TGL_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_h < SCALE_TGL_MINHEIGHT)
+				x->x_gui.x_h = SCALE_TGL_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			toggle_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + x->x_gui.x_w,
+					x->x_gui.x_obj.te_ypix + x->x_gui.x_h, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
     }
+    sh->h_dragon = newstate;
 }
 
+static void toggle__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_toggle *x = (t_toggle *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+
+		if (dx > dy) {
+			dx = dy;
+			x->x_gui.scale_offset_x = x->x_gui.scale_offset_y;
+		}
+		else {
+			dy = dx;
+			x->x_gui.scale_offset_y = x->x_gui.scale_offset_x;
+		}
+
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_w - x->x_gui.scale_offset_x + dx;
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h - x->x_gui.scale_offset_y + dy;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_TGL_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_TGL_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_TGL_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_TGL_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix, newx, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
+    }
+}
+
+
 void toggle_draw(t_toggle *x, t_glist *glist, int mode)
 {
     if(mode == IEM_GUI_DRAW_MODE_UPDATE)
@@ -263,6 +475,8 @@ static void toggle_bang(t_toggle *x)
 
 static void toggle_dialog(t_toggle *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int a = (int)atom_getintarg(0, argc, argv);
     t_float nonzero = (t_float)atom_getfloatarg(2, argc, argv);
@@ -280,6 +494,15 @@ static void toggle_dialog(t_toggle *x, t_symbol *s, int argc, t_atom *argv)
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_IO + sr_flags);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		toggle_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void toggle_click(t_toggle *x, t_floatarg xpos, t_floatarg ypos, t_floatarg shift, t_floatarg ctrl, t_floatarg alt)
@@ -435,6 +658,21 @@ static void *toggle_new(t_symbol *s, int argc, t_atom *argv)
     iemgui_all_colfromload(&x->x_gui, bflcol);
     iemgui_verify_snd_ne_rcv(&x->x_gui);
     outlet_new(&x->x_gui.x_obj, &s_float);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -443,6 +681,13 @@ static void toggle_ff(t_toggle *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_toggle_setup(void)
@@ -469,6 +714,14 @@ void g_toggle_setup(void)
     class_addmethod(toggle_class, (t_method)toggle_label_font, gensym("label_font"), A_GIMME, 0);
     class_addmethod(toggle_class, (t_method)toggle_init, gensym("init"), A_FLOAT, 0);
     class_addmethod(toggle_class, (t_method)toggle_nonzero, gensym("nonzero"), A_FLOAT, 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)toggle__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)toggle__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     toggle_widgetbehavior.w_getrectfn = toggle_getrect;
     toggle_widgetbehavior.w_displacefn = iemgui_displace;
     toggle_widgetbehavior.w_selectfn = iemgui_select;
@@ -476,6 +729,7 @@ void g_toggle_setup(void)
     toggle_widgetbehavior.w_deletefn = iemgui_delete;
     toggle_widgetbehavior.w_visfn = iemgui_vis;
     toggle_widgetbehavior.w_clickfn = toggle_newclick;
+	toggle_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(toggle_class, &toggle_widgetbehavior);
     class_sethelpsymbol(toggle_class, gensym("toggle"));
     class_setsavefn(toggle_class, toggle_save);
diff --git a/src/g_vdial.c b/src/g_vdial.c
index f560bff9d..4fd5679bb 100644
--- a/src/g_vdial.c
+++ b/src/g_vdial.c
@@ -17,6 +17,9 @@ put out a "float" as in sliders, toggles, etc. */
 #include "g_all_guis.h"
 #include <math.h>
 
+extern int gfxstub_haveproperties(void *key);
+void vradio_draw_select(t_vradio* x, t_glist* glist);
+
 /*------------------ global variables -------------------------*/
 
 
@@ -34,11 +37,6 @@ static t_class *vradio_class, *vradio_old_class;
 
 void vradio_draw_update(t_gobj *client, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("vradio_draw_update");
-        return;
-    }
     t_hradio *x = (t_hradio *)client;
     if(glist_isvisible(glist))
     {
@@ -64,33 +62,52 @@ void vradio_draw_new(t_vradio *x, t_glist *glist)
     int xx11=text_xpix(&x->x_gui.x_obj, glist), xx12=xx11+dy;
     int xx21=xx11+s4, xx22=xx12-s4;
 
-    for(i=0; i<n; i++)
-    {
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE%d\n",
-                 canvas, xx11, yy11, xx12, yy12,
-                 x->x_gui.x_bcol, x, i);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags %lxBUT%d\n",
-                 canvas, xx21, yy21, xx22, yy22,
-                 (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol,
-                 (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol, x, i);
-        yy11 += dy;
-        yy12 += dy;
-        yy21 += dy;
-        yy22 += dy;
-        x->x_drawn = x->x_on;
-    }
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xx11+x->x_gui.x_ldx, yy11b+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas, xx11, yy11-1, xx11 + IOWIDTH, yy11, x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas, xx11, yy11b, xx11 + IOWIDTH, yy11b+1, x, 0);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		for(i=0; i<n; i++)
+		{
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE%d %lxVRDO}\n",
+		             canvas, xx11, yy11, xx12, yy12,
+		             x->x_gui.x_bcol, x, i, x);
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags {%lxBUT%d %lxVRDO}\n",
+		             canvas, xx21, yy21, xx22, yy22,
+		             (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol,
+		             (x->x_on==i)?x->x_gui.x_fcol:x->x_gui.x_bcol, x, i, x);
+		    yy11 += dy;
+		    yy12 += dy;
+		    yy21 += dy;
+		    yy22 += dy;
+		    x->x_drawn = x->x_on;
+		}
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxVRDO}\n",
+		         canvas, xx11+x->x_gui.x_ldx, yy11b+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+		         x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxVRDO}\n",
+		         canvas, xx11, yy11-1, xx11 + IOWIDTH, yy11, nlet_tag, 0, x);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxVRDO}\n",
+		         canvas, xx11, yy11b, xx11 + IOWIDTH, yy11b+1, nlet_tag, 0, x);
+	//}
 }
 
 void vradio_draw_move(t_vradio *x, t_glist *glist)
@@ -103,25 +120,44 @@ void vradio_draw_move(t_vradio *x, t_glist *glist)
     int xx11=text_xpix(&x->x_gui.x_obj, glist), xx12=xx11+dy;
     int xx21=xx11+s4, xx22=xx12-s4;
 
-    for(i=0; i<n; i++)
-    {
-        sys_vgui(".x%lx.c coords %lxBASE%d %d %d %d %d\n",
-                 canvas, x, i, xx11, yy11, xx12, yy12);
-        sys_vgui(".x%lx.c coords %lxBUT%d %d %d %d %d\n",
-                 canvas, x, i, xx21, yy21, xx22, yy22);
-        yy11 += dy;
-        yy12 += dy;
-        yy21 += dy;
-        yy22 += dy;
-    }
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xx11+x->x_gui.x_ldx, yy11b+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0, xx11, yy11-1, xx11 + IOWIDTH, yy11);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0, xx11, yy11b, xx11 + IOWIDTH, yy11b+1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		for(i=0; i<n; i++)
+		{
+		    sys_vgui(".x%lx.c coords %lxBASE%d %d %d %d %d\n",
+		             canvas, x, i, xx11, yy11, xx12, yy12);
+		    sys_vgui(".x%lx.c coords %lxBUT%d %d %d %d %d\n",
+		             canvas, x, i, xx21, yy21, xx22, yy22);
+		    yy11 += dy;
+		    yy12 += dy;
+		    yy21 += dy;
+		    yy22 += dy;
+		}
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xx11+x->x_gui.x_ldx, yy11b+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xx11, yy11-1, xx11 + IOWIDTH, yy11);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0, xx11, yy11b, xx11 + IOWIDTH, yy11b+1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected)
+			vradio_draw_select(x, x->x_gui.x_glist);
+	}
 }
 
 void vradio_draw_erase(t_vradio* x, t_glist* glist)
@@ -129,6 +165,14 @@ void vradio_draw_erase(t_vradio* x, t_glist* glist)
     t_canvas *canvas=glist_getcanvas(glist);
     int n=x->x_number, i;
 
+	sys_vgui(".x%lx.c delete %lxVRDO\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxVRDO\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+
+/*
     for(i=0; i<n; i++)
     {
         sys_vgui(".x%lx.c delete %lxBASE%d\n", canvas, x, i);
@@ -139,6 +183,7 @@ void vradio_draw_erase(t_vradio* x, t_glist* glist)
         sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+*/
 }
 
 void vradio_draw_config(t_vradio* x, t_glist* glist)
@@ -146,9 +191,15 @@ void vradio_draw_config(t_vradio* x, t_glist* glist)
     t_canvas *canvas=glist_getcanvas(glist);
     int n=x->x_number, i;
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol);
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight, 
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
     for(i=0; i<n; i++)
     {
@@ -166,46 +217,196 @@ void vradio_draw_io(t_vradio* x, t_glist* glist, int old_snd_rcv_flags)
     int xpos=text_xpix(&x->x_gui.x_obj, glist);
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-                 canvas, xpos,
-                 ypos+(x->x_number*x->x_gui.x_h)-1,
-                 xpos+ IOWIDTH,
-                 ypos+(x->x_number*x->x_gui.x_h), x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-                 canvas, xpos, ypos,
-                 xpos+ IOWIDTH, ypos+1,
-                 x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		             canvas, xpos,
+		             ypos+(x->x_number*x->x_gui.x_h)-1,
+		             xpos+ IOWIDTH,
+		             ypos+(x->x_number*x->x_gui.x_h), nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		             canvas, xpos, ypos,
+		             xpos+ IOWIDTH, ypos+1,
+		             nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+	}
 }
 
 void vradio_draw_select(t_vradio* x, t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
     int n=x->x_number, i;
 
-    if(x->x_gui.x_fsf.x_selected)
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    for(i=0; i<n; i++)
+		    {
+		        sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline $select_color\n", canvas, x, i);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxVRDO}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h * x->x_number - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxVRDO\n", canvas, x);
+		}
+		else
+		{
+		    for(i=0; i<n; i++)
+		    {
+				sys_vgui(".x%lx.c dtag %lxVRDO selected\n", canvas, x);
+		        sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline #%6.6x\n", canvas, x, i,
+		                 IEM_GUI_COLOR_NORMAL);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x,
+		             x->x_gui.x_lcol);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void vradio__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
+
+	t_vradio *x = (t_vradio *)(sh->h_master);
+
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        for(i=0; i<n; i++)
-        {
-            sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline #%6.6x\n", canvas, x, i,
-                     IEM_GUI_COLOR_SELECTED);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			sh->h_dragy = sh->h_dragx;
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_w < SCALE_VRDO_MINWIDTH)
+				x->x_gui.x_w = SCALE_VRDO_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_h < SCALE_VRDO_MINHEIGHT)
+				x->x_gui.x_h = SCALE_VRDO_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			vradio_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        for(i=0; i<n; i++)
-        {
-            sys_vgui(".x%lx.c itemconfigure %lxBASE%d -outline #%6.6x\n", canvas, x, i,
-                     IEM_GUI_COLOR_NORMAL);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x,
-                 x->x_gui.x_lcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix,
+					x->x_gui.x_obj.te_xpix + x->x_gui.x_w,
+					x->x_gui.x_obj.te_ypix + (x->x_gui.x_h * x->x_number), sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
+    }
+    sh->h_dragon = newstate;
+}
+
+static void vradio__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_vradio *x = (t_vradio *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+
+		dy = dx;
+
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_h + (dx - x->x_gui.scale_offset_x);
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h * x->x_number + (dy - x->x_gui.scale_offset_x) * x->x_number;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_VRDO_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_VRDO_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_VRDO_MINHEIGHT*x->x_number)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_VRDO_MINHEIGHT*x->x_number;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix, newx, newy);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			//int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			//sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			//sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
     }
 }
 
@@ -290,6 +491,8 @@ static void vradio_properties(t_gobj *z, t_glist *owner)
 
 static void vradio_dialog(t_vradio *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int a = (int)atom_getintarg(0, argc, argv);
     int chg = (int)atom_getintarg(4, argc, argv);
@@ -319,6 +522,15 @@ static void vradio_dialog(t_vradio *x, t_symbol *s, int argc, t_atom *argv)
         (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
         canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
     }
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		vradio_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void vradio_set(t_vradio *x, t_floatarg f)
@@ -623,6 +835,21 @@ static void *vradio_donew(t_symbol *s, int argc, t_atom *argv, int old)
     iemgui_verify_snd_ne_rcv(&x->x_gui);
     iemgui_all_colfromload(&x->x_gui, bflcol);
     outlet_new(&x->x_gui.x_obj, &s_list);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -641,6 +868,13 @@ static void vradio_ff(t_vradio *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_vradio_setup(void)
@@ -683,6 +917,14 @@ void g_vradio_setup(void)
         gensym("single_change"), 0);
     class_addmethod(vradio_class, (t_method)vradio_double_change,
         gensym("double_change"), 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)vradio__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)vradio__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     vradio_widgetbehavior.w_getrectfn = vradio_getrect;
     vradio_widgetbehavior.w_displacefn = iemgui_displace;
     vradio_widgetbehavior.w_selectfn = iemgui_select;
@@ -690,6 +932,7 @@ void g_vradio_setup(void)
     vradio_widgetbehavior.w_deletefn = iemgui_delete;
     vradio_widgetbehavior.w_visfn = iemgui_vis;
     vradio_widgetbehavior.w_clickfn = vradio_newclick;
+	vradio_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(vradio_class, &vradio_widgetbehavior);
     class_sethelpsymbol(vradio_class, gensym("vradio"));
     class_setsavefn(vradio_class, vradio_save);
diff --git a/src/g_vslider.c b/src/g_vslider.c
index bac7615fe..49eafb7c8 100644
--- a/src/g_vslider.c
+++ b/src/g_vslider.c
@@ -25,6 +25,9 @@
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+static void vslider_draw_select(t_vslider* x, t_glist* glist);
+
 /* ------------ vsl gui-vertical  slider ----------------------- */
 
 t_widgetbehavior vslider_widgetbehavior;
@@ -34,11 +37,6 @@ static t_class *vslider_class;
 
 static void vslider_draw_update(t_gobj *client, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("vslider_draw_update");
-        return;
-    }
     t_vslider *x = (t_vslider *)client;
     if (glist_isvisible(glist))
     {
@@ -58,31 +56,50 @@ static void vslider_draw_new(t_vslider *x, t_glist *glist)
     int r = ypos + x->x_gui.x_h - (x->x_val + 50)/100;
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE\n",
-             canvas, xpos, ypos-2,
-             xpos + x->x_gui.x_w, ypos + x->x_gui.x_h+3,
-             x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create line %d %d %d %d -width 3 -fill #%6.6x -tags %lxKNOB\n",
-             canvas, xpos+1, r,
-             xpos + x->x_gui.x_w, r, x->x_gui.x_fcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight, 
-             x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos, ypos + x->x_gui.x_h+2,
-             xpos+7, ypos + x->x_gui.x_h+3,
-             x, 0);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos, ypos-2,
-             xpos+7, ypos-1,
-             x, 0);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE %lxVSLDR}\n",
+		         canvas, xpos, ypos-2,
+		         xpos + x->x_gui.x_w, ypos + x->x_gui.x_h+3,
+		         x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create line %d %d %d %d -width 3 -fill #%6.6x -tags {%lxKNOB %lxVSLDR}\n",
+		         canvas, xpos+1, r,
+		         xpos + x->x_gui.x_w, r, x->x_gui.x_fcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxVSLDR}\n",
+		         canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight, 
+		         x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxVSLDR}\n",
+		         canvas,
+		         xpos, ypos + x->x_gui.x_h+2,
+		         xpos+7, ypos + x->x_gui.x_h+3,
+		         nlet_tag, 0, x);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxVSLDR}\n",
+		         canvas,
+		         xpos, ypos-2,
+		         xpos+7, ypos-1,
+		         nlet_tag, 0, x);
+	//}
 }
 
 static void vslider_draw_move(t_vslider *x, t_glist *glist)
@@ -92,31 +109,58 @@ static void vslider_draw_move(t_vslider *x, t_glist *glist)
     int r = ypos + x->x_gui.x_h - (x->x_val + 50)/100;
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
-             canvas, x,
-             xpos, ypos-2,
-             xpos + x->x_gui.x_w, ypos + x->x_gui.x_h+3);
-    sys_vgui(".x%lx.c coords %lxKNOB %d %d %d %d\n",
-             canvas, x, xpos+1, r,
-             xpos + x->x_gui.x_w, r);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos, ypos + x->x_gui.x_h+2,
-             xpos+7, ypos + x->x_gui.x_h+3);
-    if(!x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos, ypos-2,
-             xpos+7, ypos-1);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
+		         canvas, x,
+		         xpos, ypos-2,
+		         xpos + x->x_gui.x_w, ypos + x->x_gui.x_h+3);
+		sys_vgui(".x%lx.c coords %lxKNOB %d %d %d %d\n",
+		         canvas, x, xpos+1, r,
+		         xpos + x->x_gui.x_w, r);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos, ypos + x->x_gui.x_h+2,
+		         xpos+7, ypos + x->x_gui.x_h+3);
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos, ypos-2,
+		         xpos+7, ypos-1);
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected) {
+			vslider_draw_select(x, x->x_gui.x_glist);
+		}
+	}
 }
 
 static void vslider_draw_erase(t_vslider* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
+	sys_vgui(".x%lx.c delete %lxVSLDR\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxVSLDR\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+/*
     sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxKNOB\n", canvas, x);
     sys_vgui(".x%lx.c delete %lxLABEL\n", canvas, x);
@@ -124,15 +168,22 @@ static void vslider_draw_erase(t_vslider* x,t_glist* glist)
         sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
     if(!x->x_gui.x_fsf.x_rcv_able)
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+*/
 }
 
 static void vslider_draw_config(t_vslider* x,t_glist* glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol);
+
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight, 
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
     sys_vgui(".x%lx.c itemconfigure %lxKNOB -fill #%6.6x\n", canvas,
              x, x->x_gui.x_fcol);
@@ -146,40 +197,188 @@ static void vslider_draw_io(t_vslider* x,t_glist* glist, int old_snd_rcv_flags)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos, ypos + x->x_gui.x_h+2,
-             xpos+7, ypos + x->x_gui.x_h+3,
-             x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos, ypos-2,
-             xpos+7, ypos-1,
-             x, 0);
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas,
+		         xpos, ypos + x->x_gui.x_h+2,
+		         xpos+7, ypos + x->x_gui.x_h+3,
+		         nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas,
+		         xpos, ypos-2,
+		         xpos+7, ypos-1,
+		         nlet_tag, 0);
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+	}
 }
 
 static void vslider_draw_select(t_vslider *x, t_glist *glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline $select_color\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxVSLDR}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + 3 + x->x_gui.x_h - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxVSLDR\n", canvas, x);
+		}
+		else
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+			sys_vgui(".x%lx.c dtag %lxVSLDR selected\n", canvas, x);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void vslider__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
 
-    if(x->x_gui.x_fsf.x_selected)
+	t_vslider *x = (t_vslider *)(sh->h_master);
+
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_w < SCALE_VSLD_MINWIDTH)
+				x->x_gui.x_w = SCALE_VSLD_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_h < SCALE_VSLD_MINHEIGHT)
+				x->x_gui.x_h = SCALE_VSLD_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			vslider_draw_move(x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix, x->x_gui.x_obj.te_ypix - 2,
+					x->x_gui.x_obj.te_xpix + x->x_gui.x_w,
+					x->x_gui.x_obj.te_ypix + 3 + x->x_gui.x_h, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
     }
+    sh->h_dragon = newstate;
 }
 
+static void vslider__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_hslider *x = (t_hslider *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_w - x->x_gui.scale_offset_x + dx;
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h - x->x_gui.scale_offset_y + dy;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_VSLD_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_VSLD_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_VSLD_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_VSLD_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix,
+				 x->x_gui.x_obj.te_ypix - 2, newx, newy + 3);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
+    }
+}
+
+
+
 void vslider_draw(t_vslider *x, t_glist *glist, int mode)
 {
     if(mode == IEM_GUI_DRAW_MODE_UPDATE)
@@ -200,7 +399,6 @@ void vslider_draw(t_vslider *x, t_glist *glist, int mode)
 
 /* ------------------------ vsl widgetbehaviour----------------------------- */
 
-
 static void vslider_getrect(t_gobj *z, t_glist *glist,
                             int *xp1, int *yp1, int *xp2, int *yp2)
 {
@@ -321,6 +519,8 @@ static void vslider_bang(t_vslider *x)
 
 static void vslider_dialog(t_vslider *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int w = (int)atom_getintarg(0, argc, argv);
     int h = (int)atom_getintarg(1, argc, argv);
@@ -344,6 +544,15 @@ static void vslider_dialog(t_vslider *x, t_symbol *s, int argc, t_atom *argv)
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_IO + sr_flags);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		vslider_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void vslider_motion(t_vslider *x, t_floatarg dx, t_floatarg dy)
@@ -583,6 +792,21 @@ static void *vslider_new(t_symbol *s, int argc, t_atom *argv)
     iemgui_all_colfromload(&x->x_gui, bflcol);
     iemgui_verify_snd_ne_rcv(&x->x_gui);
     outlet_new(&x->x_gui.x_obj, &s_float);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -591,6 +815,13 @@ static void vslider_free(t_vslider *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_vslider_setup(void)
@@ -622,6 +853,14 @@ void g_vslider_setup(void)
     class_addmethod(vslider_class, (t_method)vslider_lin, gensym("lin"), 0);
     class_addmethod(vslider_class, (t_method)vslider_init, gensym("init"), A_FLOAT, 0);
     class_addmethod(vslider_class, (t_method)vslider_steady, gensym("steady"), A_FLOAT, 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)vslider__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)vslider__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     vslider_widgetbehavior.w_getrectfn =    vslider_getrect;
     vslider_widgetbehavior.w_displacefn =   iemgui_displace;
     vslider_widgetbehavior.w_selectfn =     iemgui_select;
@@ -629,6 +868,7 @@ void g_vslider_setup(void)
     vslider_widgetbehavior.w_deletefn =     iemgui_delete;
     vslider_widgetbehavior.w_visfn =        iemgui_vis;
     vslider_widgetbehavior.w_clickfn =      vslider_newclick;
+	vslider_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(vslider_class, &vslider_widgetbehavior);
     class_sethelpsymbol(vslider_class, gensym("vslider"));
     class_setsavefn(vslider_class, vslider_save);
diff --git a/src/g_vumeter.c b/src/g_vumeter.c
index 54ec4d7b4..3980f1bf2 100644
--- a/src/g_vumeter.c
+++ b/src/g_vumeter.c
@@ -25,6 +25,10 @@
 #include <io.h>
 #endif
 
+extern int gfxstub_haveproperties(void *key);
+static void vu_draw_select(t_vu* x, t_glist* glist);
+void vu_check_height(t_vu *x, int h);
+
 /* ----- vu  gui-peak- & rms- vu-meter-display ---------- */
 
 t_widgetbehavior vu_widgetbehavior;
@@ -81,11 +85,6 @@ static void vu_update_peak(t_vu *x, t_glist *glist)
 
 static void vu_draw_update(t_gobj *client, t_glist *glist)
 {
-    if (!glist) /* BUG this function should not receive null glists */
-    {
-        bug("vu_draw_update");
-        return;
-    }
     t_vu *x = (t_vu *)client;
     if (x->x_updaterms)
     {
@@ -112,73 +111,92 @@ static void vu_draw_new(t_vu *x, t_glist *glist)
     int k1=x->x_led_size+1, k2=IEM_VU_STEPS+1, k3=k1/2;
     int led_col, yyy, i, k4=ypos-k3;
 
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags %lxBASE\n",
-             canvas, xpos-1, ypos-2,
-             xpos+x->x_gui.x_w+1,
-             ypos+x->x_gui.x_h+2, x->x_gui.x_bcol, x);
-    for(i=1; i<=IEM_VU_STEPS; i++)
-    {
-        led_col = iemgui_vu_col[i];
-        yyy = k4 + k1*(k2-i);
-        sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags %lxRLED%d\n",
-                 canvas, quad1, yyy, quad3, yyy, x->x_led_size, iemgui_color_hex[led_col], x, i);
-        if(((i+2)&3) && (x->x_scale))
-            sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-                     -font {{%s} %d %s} -fill #%6.6x -tags %lxSCALE%d\n",
-                     canvas, end, yyy+k3, iemgui_vu_scale_str[i], 
-					 x->x_gui.x_font, x->x_gui.x_fontsize,
-                     sys_fontweight, x->x_gui.x_lcol, x, i);
-    }
-    if(x->x_scale)
-    {
-        i=IEM_VU_STEPS+1;
-        yyy = k4 + k1*(k2-i);
-        sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-                 -font {{%s} %d %s} -fill #%6.6x -tags %lxSCALE%d\n",
-                 canvas, end, yyy+k3, iemgui_vu_scale_str[i], x->x_gui.x_font, 
-				 x->x_gui.x_fontsize, sys_fontweight,
-                 x->x_gui.x_lcol, x, i);
-    }
-    sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags %lxRCOVER\n",
-             canvas, quad1, ypos-1, quad3-1,
-             ypos-1 + k1*IEM_VU_STEPS, x->x_gui.x_bcol, x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags %lxPLED\n",
-             canvas, mid, ypos+10,
-             mid, ypos+10, x->x_led_size, x->x_gui.x_bcol, x);
-    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
-             -font {{%s} %d %s} -fill #%6.6x -tags %lxLABEL\n",
-             canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
-             strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
-             x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_lcol, x);
-    if(!x->x_gui.x_fsf.x_snd_able)
-    {
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos-1, ypos + x->x_gui.x_h+1,
-             xpos + IOWIDTH-1, ypos + x->x_gui.x_h+2,
-             x, 0);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos+x->x_gui.x_w+1-IOWIDTH, ypos + x->x_gui.x_h+1,
-             xpos+x->x_gui.x_w+1, ypos + x->x_gui.x_h+2,
-             x, 1);
-    }
-    if(!x->x_gui.x_fsf.x_rcv_able)
-    {
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos-1, ypos-2,
-             xpos + IOWIDTH-1, ypos-1,
-             x, 0);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos+x->x_gui.x_w+1-IOWIDTH, ypos-2,
-             xpos+x->x_gui.x_w+1, ypos-1,
-             x, 1);
-    }
-    x->x_updaterms = x->x_updatepeak = 1;
-    sys_queuegui(x, x->x_gui.x_glist, vu_draw_update);
+	t_scalehandle *sh = (t_scalehandle *)x->x_gui.x_handle;
+	sprintf(sh->h_pathname, ".x%x.h%x", (int)canvas, (int)sh);
+
+	//if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -tags {%lxBASE %lxVU}\n",
+		         canvas, xpos-1, ypos-2,
+		         xpos+x->x_gui.x_w+1,
+		         ypos+x->x_gui.x_h+2, x->x_gui.x_bcol, x, x);
+		for(i=1; i<=IEM_VU_STEPS; i++)
+		{
+		    led_col = iemgui_vu_col[i];
+		    yyy = k4 + k1*(k2-i);
+		    sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags {%lxRLED%d %lxVU}\n",
+		             canvas, quad1, yyy, quad3, yyy, x->x_led_size, iemgui_color_hex[led_col], x, i, x);
+		    if(((i+2)&3) && (x->x_scale))
+		        sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		                 -font {{%s} %d %s} -fill #%6.6x -tags {%lxSCALE%d %lxVU}\n",
+		                 canvas, end, yyy+k3, iemgui_vu_scale_str[i], 
+						 x->x_gui.x_font, x->x_gui.x_fontsize,
+		                 sys_fontweight, x->x_gui.x_lcol, x, i, x);
+		}
+		if(x->x_scale)
+		{
+		    i=IEM_VU_STEPS+1;
+		    yyy = k4 + k1*(k2-i);
+		    sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		             -font {{%s} %d %s} -fill #%6.6x -tags {%lxSCALE%d %lxVU}\n",
+		             canvas, end, yyy+k3, iemgui_vu_scale_str[i], x->x_gui.x_font, 
+					 x->x_gui.x_fontsize, sys_fontweight,
+		             x->x_gui.x_lcol, x, i, x);
+		}
+		sys_vgui(".x%lx.c create rectangle %d %d %d %d -fill #%6.6x -outline #%6.6x -tags {%lxRCOVER %lxVU}\n",
+		         canvas, quad1, ypos-1, quad3-1,
+		         ypos-1 + k1*IEM_VU_STEPS, x->x_gui.x_bcol, x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create line %d %d %d %d -width %d -fill #%6.6x -tags {%lxPLED %lxVU}\n",
+		         canvas, mid, ypos+10,
+		         mid, ypos+10, x->x_led_size, x->x_gui.x_bcol, x, x);
+		sys_vgui(".x%lx.c create text %d %d -text {%s} -anchor w \
+		         -font {{%s} %d %s} -fill #%6.6x -tags {%lxLABEL %lxVU}\n",
+		         canvas, xpos+x->x_gui.x_ldx, ypos+x->x_gui.x_ldy,
+		         strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"",
+		         x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
+		         x->x_gui.x_lcol, x, x);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		{
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxVU}\n",
+		         canvas,
+		         xpos-1, ypos + x->x_gui.x_h+1,
+		         xpos + IOWIDTH-1, ypos + x->x_gui.x_h+2,
+		         nlet_tag, 0, x);
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%so%d %lxVU}\n",
+		         canvas,
+		         xpos+x->x_gui.x_w+1-IOWIDTH, ypos + x->x_gui.x_h+1,
+		         xpos+x->x_gui.x_w+1, ypos + x->x_gui.x_h+2,
+		         nlet_tag, 1, x);
+		}
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		{
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxVU}\n",
+		         canvas,
+		         xpos-1, ypos-2,
+		         xpos + IOWIDTH-1, ypos-1,
+		         nlet_tag, 0, x);
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags {%si%d %lxVU}\n",
+		         canvas,
+		         xpos+x->x_gui.x_w+1-IOWIDTH, ypos-2,
+		         xpos+x->x_gui.x_w+1, ypos-1,
+		         nlet_tag, 1, x);
+		}
+		x->x_updaterms = x->x_updatepeak = 1;
+		sys_queuegui(x, x->x_gui.x_glist, vu_draw_update);
+	//}
 }
 
 
@@ -186,60 +204,79 @@ static void vu_draw_move(t_vu *x, t_glist *glist)
 {
     t_canvas *canvas=glist_getcanvas(glist);
 
-    int xpos=text_xpix(&x->x_gui.x_obj, glist);
-    int ypos=text_ypix(&x->x_gui.x_obj, glist);
-    int w4=x->x_gui.x_w/4, quad1=xpos+w4+1;
-    int quad3=xpos+x->x_gui.x_w-w4,
-        end=xpos+x->x_gui.x_w+4;
-    int k1=x->x_led_size+1, k2=IEM_VU_STEPS+1, k3=k1/2;
-    int yyy, i, k4=ypos-k3;
-
-    sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
-             canvas, x, xpos-1, ypos-2,
-             xpos+x->x_gui.x_w+1,ypos+x->x_gui.x_h+2);
-    for(i=1; i<=IEM_VU_STEPS; i++)
-    {
-        yyy = k4 + k1*(k2-i);
-        sys_vgui(".x%lx.c coords %lxRLED%d %d %d %d %d\n",
-                 canvas, x, i, quad1, yyy, quad3, yyy);
-        if(((i+2)&3) && (x->x_scale))
-            sys_vgui(".x%lx.c coords %lxSCALE%d %d %d\n",
-                     canvas, x, i, end, yyy+k3);
-    }
-    if(x->x_scale)
-    {
-        i=IEM_VU_STEPS+1;
-        yyy = k4 + k1*(k2-i);
-        sys_vgui(".x%lx.c coords %lxSCALE%d %d %d\n",
-                 canvas, x, i, end, yyy+k3);
-    }
-    x->x_updaterms = x->x_updatepeak = 1;
-    sys_queuegui(x, glist, vu_draw_update);
-    sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
-             canvas, x, xpos+x->x_gui.x_ldx,
-             ypos+x->x_gui.x_ldy);
-    if(!x->x_gui.x_fsf.x_snd_able)
-    {
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos-1, ypos + x->x_gui.x_h+1,
-             xpos + IOWIDTH-1, ypos + x->x_gui.x_h+2);
-        sys_vgui(".x%lx.c coords %lxOUT%d %d %d %d %d\n",
-             canvas, x, 1,
-             xpos+x->x_gui.x_w+1-IOWIDTH, ypos + x->x_gui.x_h+1,
-                 xpos+x->x_gui.x_w+1, ypos + x->x_gui.x_h+2);
-    }
-    if(!x->x_gui.x_fsf.x_rcv_able)
-    {
-    sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 0,
-             xpos-1, ypos-2,
-             xpos + IOWIDTH-1, ypos-1);
-    sys_vgui(".x%lx.c coords %lxIN%d %d %d %d %d\n",
-             canvas, x, 1,
-             xpos+x->x_gui.x_w+1-IOWIDTH, ypos-2,
-             xpos+x->x_gui.x_w+1, ypos-1);
-    }
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		int xpos=text_xpix(&x->x_gui.x_obj, glist);
+		int ypos=text_ypix(&x->x_gui.x_obj, glist);
+		int w4=x->x_gui.x_w/4, quad1=xpos+w4+1;
+		int quad3=xpos+x->x_gui.x_w-w4,
+		    end=xpos+x->x_gui.x_w+4;
+		int k1=x->x_led_size+1, k2=IEM_VU_STEPS+1, k3=k1/2;
+		int yyy, i, k4=ypos-k3;
+
+		sys_vgui(".x%lx.c coords %lxBASE %d %d %d %d\n",
+		         canvas, x, xpos-1, ypos-2,
+		         xpos+x->x_gui.x_w+1,ypos+x->x_gui.x_h+2);
+		for(i=1; i<=IEM_VU_STEPS; i++)
+		{
+		    yyy = k4 + k1*(k2-i);
+		    sys_vgui(".x%lx.c coords %lxRLED%d %d %d %d %d\n",
+		             canvas, x, i, quad1, yyy, quad3, yyy);
+		    if(((i+2)&3) && (x->x_scale))
+		        sys_vgui(".x%lx.c coords %lxSCALE%d %d %d\n",
+		                 canvas, x, i, end, yyy+k3);
+		}
+		if(x->x_scale)
+		{
+		    i=IEM_VU_STEPS+1;
+		    yyy = k4 + k1*(k2-i);
+		    sys_vgui(".x%lx.c coords %lxSCALE%d %d %d\n",
+		             canvas, x, i, end, yyy+k3);
+		}
+		x->x_updaterms = x->x_updatepeak = 1;
+		sys_queuegui(x, glist, vu_draw_update);
+		sys_vgui(".x%lx.c coords %lxLABEL %d %d\n",
+		         canvas, x, xpos+x->x_gui.x_ldx,
+		         ypos+x->x_gui.x_ldy);
+		if(!x->x_gui.x_fsf.x_snd_able)
+		{
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos-1, ypos + x->x_gui.x_h+1,
+		         xpos + IOWIDTH-1, ypos + x->x_gui.x_h+2);
+		    sys_vgui(".x%lx.c coords %so%d %d %d %d %d\n",
+		         canvas, nlet_tag, 1,
+		         xpos+x->x_gui.x_w+1-IOWIDTH, ypos + x->x_gui.x_h+1,
+		             xpos+x->x_gui.x_w+1, ypos + x->x_gui.x_h+2);
+		}
+		if(!x->x_gui.x_fsf.x_rcv_able)
+		{
+		sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 0,
+		         xpos-1, ypos-2,
+		         xpos + IOWIDTH-1, ypos-1);
+		sys_vgui(".x%lx.c coords %si%d %d %d %d %d\n",
+		         canvas, nlet_tag, 1,
+		         xpos+x->x_gui.x_w+1-IOWIDTH, ypos-2,
+		         xpos+x->x_gui.x_w+1, ypos-1);
+		}
+		/* redraw scale handle rectangle if selected */
+		if (x->x_gui.x_fsf.x_selected)
+			vu_draw_select(x, x->x_gui.x_glist);
+	}
 }
 
 static void vu_draw_erase(t_vu* x,t_glist* glist)
@@ -247,6 +284,14 @@ static void vu_draw_erase(t_vu* x,t_glist* glist)
     int i;
     t_canvas *canvas=glist_getcanvas(glist);
 
+	sys_vgui(".x%lx.c delete %lxVU\n", canvas, x);
+	sys_vgui(".x%lx.c dtag all %lxVU\n", canvas, x);
+	if (x->x_gui.x_fsf.x_selected) {
+		t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+		sys_vgui("destroy %s\n", sh->h_pathname);
+	}
+
+/*
     sys_vgui(".x%lx.c delete %lxBASE\n", canvas, x);
     for(i=1; i<=IEM_VU_STEPS; i++)
     {
@@ -272,6 +317,7 @@ static void vu_draw_erase(t_vu* x,t_glist* glist)
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
         sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 1);
     }
+*/
 }
 
 static void vu_draw_config(t_vu* x, t_glist* glist)
@@ -279,28 +325,34 @@ static void vu_draw_config(t_vu* x, t_glist* glist)
     int i;
     t_canvas *canvas=glist_getcanvas(glist);
 
+	char color[64];
+	if (x->x_gui.x_fsf.x_selected)
+		sprintf(color, "$select_color");
+	else
+		sprintf(color, "#%6.6x", x->x_gui.x_lcol);
+
     sys_vgui(".x%lx.c itemconfigure %lxBASE -fill #%6.6x\n", canvas, x, x->x_gui.x_bcol);
     for(i=1; i<=IEM_VU_STEPS; i++)
     {
         sys_vgui(".x%lx.c itemconfigure %lxRLED%d -width %d\n", canvas, x, i,
                  x->x_led_size);
         if(((i+2)&3) && (x->x_scale))
-            sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -text {%s} -font {{%s} %d %s} -fill #%6.6x\n",
+            sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -text {%s} -font {{%s} %d %s} -fill %s\n",
                      canvas, x, i, iemgui_vu_scale_str[i], x->x_gui.x_font, 
 					 x->x_gui.x_fontsize, sys_fontweight, 
-                     x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol);
+                     color);
     }
     if(x->x_scale)
     {
         i=IEM_VU_STEPS+1;
-        sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -text {%s} -font {{%s} %d %s} -fill #%6.6x\n",
+        sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -text {%s} -font {{%s} %d %s} -fill %s\n",
                  canvas, x, i, iemgui_vu_scale_str[i], x->x_gui.x_font, 
 				 x->x_gui.x_fontsize, sys_fontweight,
-                 x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol);
+                 color);
     }
-    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill #%6.6x -text {%s} \n",
+    sys_vgui(".x%lx.c itemconfigure %lxLABEL -font {{%s} %d %s} -fill %s -text {%s} \n",
              canvas, x, x->x_gui.x_font, x->x_gui.x_fontsize, sys_fontweight,
-             x->x_gui.x_fsf.x_selected?IEM_GUI_COLOR_SELECTED:x->x_gui.x_lcol,
+             color,
              strcmp(x->x_gui.x_lab->s_name, "empty")?x->x_gui.x_lab->s_name:"");
 
     sys_vgui(".x%lx.c itemconfigure %lxRCOVER -fill #%6.6x -outline #%6.6x\n", canvas,
@@ -315,82 +367,236 @@ static void vu_draw_io(t_vu* x, t_glist* glist, int old_snd_rcv_flags)
     int ypos=text_ypix(&x->x_gui.x_obj, glist);
     t_canvas *canvas=glist_getcanvas(glist);
 
-    if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
-    {
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos-1, ypos + x->x_gui.x_h+1,
-             xpos + IOWIDTH-1, ypos + x->x_gui.x_h+2,
-             x, 0);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxOUT%d\n",
-             canvas,
-             xpos+x->x_gui.x_w+1-IOWIDTH, ypos + x->x_gui.x_h+1,
-             xpos+x->x_gui.x_w+1, ypos + x->x_gui.x_h+2,
-             x, 1);
-    }
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
-    {
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 0);
-        sys_vgui(".x%lx.c delete %lxOUT%d\n", canvas, x, 1);
-    }
-    if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
-    {
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos-1, ypos-2,
-             xpos + IOWIDTH-1, ypos-1,
-             x, 0);
-        sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %lxIN%d\n",
-             canvas,
-             xpos+x->x_gui.x_w+1-IOWIDTH, ypos-2,
-             xpos+x->x_gui.x_w+1, ypos-1,
-             x, 1);
-    }
-    if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
-    {
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 0);
-        sys_vgui(".x%lx.c delete %lxIN%d\n", canvas, x, 1);
-    }
+	if (glist_isvisible(canvas)) {
+
+		t_gobj *y = (t_gobj *)x;
+		t_object *ob = pd_checkobject(&y->g_pd);
+
+		/* GOP objects are unable to call findrtext triggering consistency check error */
+		t_rtext *yyyy = NULL;
+		if (!glist->gl_isgraph || glist_istoplevel(glist))
+			yyyy = glist_findrtext(canvas, (t_text *)&ob->ob_g);
+
+		/* on GOP we cause segfault as apparently text_gettag() returns bogus data */
+		char *nlet_tag;
+		if (yyyy) nlet_tag = rtext_gettag(yyyy);
+		else nlet_tag = "bogus";
+
+		if((old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && !x->x_gui.x_fsf.x_snd_able)
+		{
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas,
+		         xpos-1, ypos + x->x_gui.x_h+1,
+		         xpos + IOWIDTH-1, ypos + x->x_gui.x_h+2,
+		         nlet_tag, 0);
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %so%d\n",
+		         canvas,
+		         xpos+x->x_gui.x_w+1-IOWIDTH, ypos + x->x_gui.x_h+1,
+		         xpos+x->x_gui.x_w+1, ypos + x->x_gui.x_h+2,
+		         nlet_tag, 1);
+		}
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_SND_FLAG) && x->x_gui.x_fsf.x_snd_able)
+		{
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 0);
+		    sys_vgui(".x%lx.c delete %so%d\n", canvas, nlet_tag, 1);
+		}
+		if((old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && !x->x_gui.x_fsf.x_rcv_able)
+		{
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas,
+		         xpos-1, ypos-2,
+		         xpos + IOWIDTH-1, ypos-1,
+		         nlet_tag, 0);
+		    sys_vgui(".x%lx.c create rectangle %d %d %d %d -tags %si%d\n",
+		         canvas,
+		         xpos+x->x_gui.x_w+1-IOWIDTH, ypos-2,
+		         xpos+x->x_gui.x_w+1, ypos-1,
+		         nlet_tag, 1);
+		}
+		if(!(old_snd_rcv_flags & IEM_GUI_OLD_RCV_FLAG) && x->x_gui.x_fsf.x_rcv_able)
+		{
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 0);
+		    sys_vgui(".x%lx.c delete %si%d\n", canvas, nlet_tag, 1);
+		}
+	}
 }
 
 static void vu_draw_select(t_vu* x,t_glist* glist)
 {
     int i;
     t_canvas *canvas=glist_getcanvas(glist);
+	t_scalehandle *sh = (t_scalehandle *)(x->x_gui.x_handle);
+
+	if (glist_isvisible(canvas)) {
+
+		if(x->x_gui.x_fsf.x_selected)
+		{
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline $select_color\n", canvas, x);
+		    for(i=1; i<=IEM_VU_STEPS; i++)
+		    {
+		        if(((i+2)&3) && (x->x_scale))
+		            sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill $select_color\n",
+		                     canvas, x, i);
+		    }
+		    if(x->x_scale)
+		    {
+		        i=IEM_VU_STEPS+1;
+		        sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill $select_color\n",
+		                 canvas, x, i);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill $select_color\n", canvas, x);
+
+			if (x->x_gui.scale_vis)
+				sys_vgui("destroy %s\n", sh->h_pathname);
+
+			sys_vgui("canvas %s -width %d -height %d -bg $select_color -bd 0 -cursor bottom_right_corner\n",
+				 sh->h_pathname, SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT);
+			sys_vgui(".x%x.c create window %d %d -anchor nw -width %d -height %d -window %s -tags {%lxSCALE %lxVU}\n",
+				 canvas, x->x_gui.x_obj.te_xpix + x->x_gui.x_w + 1 - SCALEHANDLE_WIDTH,
+				 x->x_gui.x_obj.te_ypix + x->x_gui.x_h + 2 - SCALEHANDLE_HEIGHT,
+				 SCALEHANDLE_WIDTH, SCALEHANDLE_HEIGHT,
+				 sh->h_pathname, x, x);
+			sys_vgui("bind %s <Button> {pd [concat %s _click 1 %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <ButtonRelease> {pd [concat %s _click 0 0 0 \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			sys_vgui("bind %s <Motion> {pd [concat %s _motion %%x %%y \\;]}\n",
+				 sh->h_pathname, sh->h_bindsym->s_name);
+			x->x_gui.scale_vis = 1;
+
+			sys_vgui(".x%lx.c addtag selected withtag %lxVU\n", canvas, x);
+		}
+		else
+		{
+			sys_vgui(".x%lx.c dtag %lxVU selected\n", canvas, x);
+		    sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
+		    for(i=1; i<=IEM_VU_STEPS; i++)
+		    {
+		        if(((i+2)&3) && (x->x_scale))
+		            sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill #%6.6x\n",
+		                     canvas, x, i, x->x_gui.x_lcol);
+		    }
+		    if(x->x_scale)
+		    {
+		        i=IEM_VU_STEPS+1;
+		        sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill #%6.6x\n",
+		                 canvas, x, i, x->x_gui.x_lcol);
+		    }
+		    sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			x->x_gui.scale_vis = 0;
+		}
+	}
+}
+
+static void vu__clickhook(t_scalehandle *sh, t_floatarg f, t_floatarg xxx, t_floatarg yyy)
+{
 
-    if(x->x_gui.x_fsf.x_selected)
+	t_vu *x = (t_vu *)(sh->h_master);
+
+	if (xxx) x->x_gui.scale_offset_x = xxx;
+	if (yyy) x->x_gui.scale_offset_y = yyy;
+
+    int newstate = (int)f;
+    if (sh->h_dragon && newstate == 0)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
-        for(i=1; i<=IEM_VU_STEPS; i++)
-        {
-            if(((i+2)&3) && (x->x_scale))
-                sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill #%6.6x\n",
-                         canvas, x, i, IEM_GUI_COLOR_SELECTED);
-        }
-        if(x->x_scale)
-        {
-            i=IEM_VU_STEPS+1;
-            sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill #%6.6x\n",
-                     canvas, x, i, IEM_GUI_COLOR_SELECTED);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, IEM_GUI_COLOR_SELECTED);
+		/* done dragging */
+
+		/* first set up the undo apply */
+		canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
+		if (sh->h_dragx || sh->h_dragy) {
+
+			x->x_gui.x_w = x->x_gui.x_w + sh->h_dragx - x->x_gui.scale_offset_x;
+			if (x->x_gui.x_w < SCALE_BNG_MINWIDTH)
+				x->x_gui.x_w = SCALE_BNG_MINWIDTH;
+			x->x_gui.x_h = x->x_gui.x_h + sh->h_dragy - x->x_gui.scale_offset_y;
+			if (x->x_gui.x_h < SCALE_BNG_MINHEIGHT)
+				x->x_gui.x_h = SCALE_BNG_MINHEIGHT;
+
+			canvas_dirty(x->x_gui.x_glist, 1);
+		}
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, x->x_gui.x_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, x->x_gui.x_h);
+		}
+
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui(".x%x.c delete %s\n", x->x_gui.x_glist, sh->h_outlinetag);
+			vu_check_height(x, x->x_gui.x_h);
+			vu_draw_move(x, x->x_gui.x_glist);
+			vu_draw_config(x, x->x_gui.x_glist);
+			vu_draw_update((t_gobj *)x, x->x_gui.x_glist);
+			sys_vgui("destroy %s\n", sh->h_pathname);
+			iemgui_select((t_gobj *)x, x->x_gui.x_glist, 1);
+			canvas_fixlinesfor(x->x_gui.x_glist, (t_text *)x);
+			sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", x->x_gui.x_glist);
+		}
     }
-    else
+    else if (!sh->h_dragon && newstate)
     {
-        sys_vgui(".x%lx.c itemconfigure %lxBASE -outline #%6.6x\n", canvas, x, IEM_GUI_COLOR_NORMAL);
-        for(i=1; i<=IEM_VU_STEPS; i++)
-        {
-            if(((i+2)&3) && (x->x_scale))
-                sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill #%6.6x\n",
-                         canvas, x, i, x->x_gui.x_lcol);
-        }
-        if(x->x_scale)
-        {
-            i=IEM_VU_STEPS+1;
-            sys_vgui(".x%lx.c itemconfigure %lxSCALE%d -fill #%6.6x\n",
-                     canvas, x, i, x->x_gui.x_lcol);
-        }
-        sys_vgui(".x%lx.c itemconfigure %lxLABEL -fill #%6.6x\n", canvas, x, x->x_gui.x_lcol);
+		/* dragging */
+		if (glist_isvisible(x->x_gui.x_glist))
+		{
+			sys_vgui("lower %s\n", sh->h_pathname);
+			sys_vgui(".x%x.c create rectangle %d %d %d %d\
+	 -outline $select_color -width 1 -tags %s\n",
+				 x->x_gui.x_glist, x->x_gui.x_obj.te_xpix - 1, x->x_gui.x_obj.te_ypix - 2,
+					x->x_gui.x_obj.te_xpix + x->x_gui.x_w + 1,
+					x->x_gui.x_obj.te_ypix + x->x_gui.x_h + 2, sh->h_outlinetag);
+		}
+
+		sh->h_dragx = 0;
+		sh->h_dragy = 0;
+    }
+    sh->h_dragon = newstate;
+}
+
+static void vu__motionhook(t_scalehandle *sh,
+				    t_floatarg f1, t_floatarg f2)
+{
+    if (sh->h_dragon)
+    {
+		t_vu *x = (t_vu *)(sh->h_master);
+		int dx = (int)f1, dy = (int)f2;
+		int newx, newy;
+
+		int y_incr = (int)((dy - x->x_gui.scale_offset_y) / IEM_VU_STEPS);
+		if (dy - x->x_gui.scale_offset_y < 0)
+			y_incr -= 1;
+
+		newx = x->x_gui.x_obj.te_xpix + x->x_gui.x_w - x->x_gui.scale_offset_x + dx;
+		newy = x->x_gui.x_obj.te_ypix + x->x_gui.x_h + y_incr * IEM_VU_STEPS;
+
+		if (newx < x->x_gui.x_obj.te_xpix + SCALE_BNG_MINWIDTH)
+			newx = x->x_gui.x_obj.te_xpix + SCALE_BNG_MINWIDTH;
+		if (newy < x->x_gui.x_obj.te_ypix + SCALE_BNG_MINHEIGHT)
+			newy = x->x_gui.x_obj.te_ypix + SCALE_BNG_MINHEIGHT;
+
+		if (glist_isvisible(x->x_gui.x_glist)) {
+			sys_vgui(".x%x.c coords %s %d %d %d %d\n",
+				 x->x_gui.x_glist, sh->h_outlinetag, x->x_gui.x_obj.te_xpix - 1,
+				 x->x_gui.x_obj.te_ypix - 2, newx + 1, newy + 2);
+		}
+		sh->h_dragx = dx;
+		sh->h_dragy = dy;
+
+		int properties = gfxstub_haveproperties((void *)x);
+
+		if (properties) {
+			int new_w = x->x_gui.x_w - x->x_gui.scale_offset_x + sh->h_dragx;
+			int new_h = x->x_gui.x_h - x->x_gui.scale_offset_y + sh->h_dragy;
+			sys_vgui(".gfxstub%lx.dim.w_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.w_ent insert 0 %d\n", properties, new_w);
+			sys_vgui(".gfxstub%lx.dim.h_ent delete 0 end\n", properties);
+			sys_vgui(".gfxstub%lx.dim.h_ent insert 0 %d\n", properties, new_h);
+		}
     }
 }
 
@@ -532,6 +738,8 @@ static void vu_properties(t_gobj *z, t_glist *owner)
 
 static void vu_dialog(t_vu *x, t_symbol *s, int argc, t_atom *argv)
 {
+	canvas_apply_setundo(x->x_gui.x_glist, (t_gobj *)x);
+
     t_symbol *srl[3];
     int w = (int)atom_getintarg(0, argc, argv);
     int h = (int)atom_getintarg(1, argc, argv);
@@ -551,6 +759,15 @@ static void vu_dialog(t_vu *x, t_symbol *s, int argc, t_atom *argv)
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_IO + sr_flags);
     (*x->x_gui.x_draw)(x, x->x_gui.x_glist, IEM_GUI_DRAW_MODE_MOVE);
     canvas_fixlinesfor(glist_getcanvas(x->x_gui.x_glist), (t_text*)x);
+
+	/* forcing redraw of the scale handle */
+	if (x->x_gui.x_fsf.x_selected) {
+		vu_draw_select(x, x->x_gui.x_glist);
+	}
+
+	//ico@bukvic.net 100518 update scrollbars when object potentially exceeds window size
+    t_canvas *canvas=(t_canvas *)glist_getcanvas(x->x_gui.x_glist);
+	sys_vgui("pdtk_canvas_getscroll .x%lx.c\n", (long unsigned int)canvas);
 }
 
 static void vu_size(t_vu *x, t_symbol *s, int ac, t_atom *av)
@@ -705,6 +922,21 @@ static void *vu_new(t_symbol *s, int argc, t_atom *argv)
     inlet_new(&x->x_gui.x_obj, &x->x_gui.x_obj.ob_pd, &s_float, gensym("ft1"));
     x->x_out_rms = outlet_new(&x->x_gui.x_obj, &s_float);
     x->x_out_peak = outlet_new(&x->x_gui.x_obj, &s_float);
+
+	/* scale handle init */
+    t_scalehandle *sh;
+    char buf[64];
+    x->x_gui.x_handle = pd_new(scalehandle_class);
+    sh = (t_scalehandle *)x->x_gui.x_handle;
+    sh->h_master = (t_gobj*)x;
+    sprintf(buf, "_h%x", (int)sh);
+    pd_bind(x->x_gui.x_handle, sh->h_bindsym = gensym(buf));
+    sprintf(sh->h_outlinetag, "h%x", (int)sh);
+    sh->h_dragon = 0;
+	x->x_gui.scale_offset_x = 0;
+	x->x_gui.scale_offset_y = 0;
+	x->x_gui.scale_vis = 0;
+
     return (x);
 }
 
@@ -713,6 +945,13 @@ static void vu_free(t_vu *x)
     if(x->x_gui.x_fsf.x_rcv_able)
         pd_unbind(&x->x_gui.x_obj.ob_pd, x->x_gui.x_rcv);
     gfxstub_deleteforkey(x);
+
+	/* scale handle deconstructor */
+    if (x->x_gui.x_handle)
+    {
+		pd_unbind(x->x_gui.x_handle, ((t_scalehandle *)x->x_gui.x_handle)->h_bindsym);
+		pd_free(x->x_gui.x_handle);
+    }
 }
 
 void g_vumeter_setup(void)
@@ -733,6 +972,14 @@ void g_vumeter_setup(void)
     class_addmethod(vu_class, (t_method)vu_label, gensym("label"), A_DEFSYM, 0);
     class_addmethod(vu_class, (t_method)vu_label_pos, gensym("label_pos"), A_GIMME, 0);
     class_addmethod(vu_class, (t_method)vu_label_font, gensym("label_font"), A_GIMME, 0);
+ 
+    scalehandle_class = class_new(gensym("_scalehandle"), 0, 0,
+				  sizeof(t_scalehandle), CLASS_PD, 0);
+    class_addmethod(scalehandle_class, (t_method)vu__clickhook,
+		    gensym("_click"), A_FLOAT, A_FLOAT, A_FLOAT, 0);
+    class_addmethod(scalehandle_class, (t_method)vu__motionhook,
+		    gensym("_motion"), A_FLOAT, A_FLOAT, 0);
+
     vu_widgetbehavior.w_getrectfn =    vu_getrect;
     vu_widgetbehavior.w_displacefn =   iemgui_displace;
     vu_widgetbehavior.w_selectfn =     iemgui_select;
@@ -740,6 +987,7 @@ void g_vumeter_setup(void)
     vu_widgetbehavior.w_deletefn =     iemgui_delete;
     vu_widgetbehavior.w_visfn =        iemgui_vis;
     vu_widgetbehavior.w_clickfn =      NULL;
+	vu_widgetbehavior.w_displacefnwtag = iemgui_displace_withtag;
     class_setwidget(vu_class,&vu_widgetbehavior);
     class_sethelpsymbol(vu_class, gensym("vu"));
     class_setsavefn(vu_class, vu_save);
diff --git a/src/helpbrowser.tcl b/src/helpbrowser.tcl
index 9ce5f9905..f3307e15f 100644
--- a/src/helpbrowser.tcl
+++ b/src/helpbrowser.tcl
@@ -29,7 +29,7 @@ proc ::helpbrowser::open_helpbrowser {} {
         bind .help_browser <$::modifier-Key-w> "wm withdraw .help_browser"
 
         wm resizable .help_browser 0 0
-        frame .help_browser.frame
+        match_linux_wm [list frame .help_browser.frame]
         pack .help_browser.frame -side top -fill both
         build_references
 #        doc_make_listbox .help_browser.frame $::sys_libdir/doc 0
@@ -44,9 +44,10 @@ proc ::helpbrowser::make_rootlistbox {base} {
     # exportselection 0 looks good, but selection gets easily out-of-sync
 	set current_listbox [listbox "[set b $base.root]" -yscrollcommand "$b-scroll set" \
                              -highlightbackground white -highlightthickness 5 \
-                             -highlightcolor "#D6E5FC" -selectborderwidth 0 \
-                             -height 20 -width 23 -exportselection 0 -bd 0]
-	pack $current_listbox [scrollbar "$b-scroll" -command [list $current_listbox yview]] \
+                             -highlightcolor "#e87216" -selectborderwidth 0 \
+                             -height 20 -width 23 -exportselection 0 -bd 0 \
+							 -selectbackground "#e87216"]
+	pack $current_listbox [match_linux_wm [list scrollbar "$b-scroll" -command [list $current_listbox yview]]] \
         -side left -fill both -expand 1
     foreach item [concat [lsort [concat $libdirlist $helplist]]] {
 		$current_listbox insert end $item
@@ -94,9 +95,10 @@ proc ::helpbrowser::make_liblistbox {base dir} {
     # exportselection 0 looks good, but selection gets easily out-of-sync
 	set current_listbox [listbox "[set b $base.listbox0]" -yscrollcommand "$b-scroll set" \
                              -highlightbackground white -highlightthickness 5 \
-                             -highlightcolor "#D6E5FC" -selectborderwidth 0 \
-                             -height 20 -width 23 -exportselection 0 -bd 0]
-	pack $current_listbox [scrollbar "$b-scroll" -command [list $current_listbox yview]] \
+                             -highlightcolor "#e87216" -selectborderwidth 0 \
+                             -height 20 -width 23 -exportselection 0 -bd 0 \
+							 -selectbackground "#e87216"]
+	pack $current_listbox [match_linux_wm [list scrollbar "$b-scroll" -command [list $current_listbox yview]]] \
         -side left -fill both -expand 1
 	foreach item [lsort -dictionary [glob -directory $dir -nocomplain -types {d} -- *]] {
         if {[glob -directory $item -nocomplain -types {f} -- $doctypes] ne "" ||
@@ -134,9 +136,10 @@ proc ::helpbrowser::doc_make_listbox {base dir count} {
 	set current_listbox [listbox "[set b "$base.listbox$count"]-list" \
                              -yscrollcommand "$b-scroll set" \
                              -highlightbackground white -highlightthickness 5 \
-                             -highlightcolor "#D6E5FC" -selectborderwidth 0 \
-                             -height 20 -width 23 -exportselection 0 -bd 0]
-	pack $current_listbox [scrollbar "$b-scroll" -command "$current_listbox yview"] \
+                             -highlightcolor "#e87216" -selectborderwidth 0 \
+                             -height 20 -width 23 -exportselection 0 -bd 0 \
+							 -selectbackground "#e87216"]
+	pack $current_listbox [match_linux_wm [list scrollbar "$b-scroll" -command "$current_listbox yview"]] \
         -side left -fill both -expand 1
 	foreach item [lsort -dictionary [glob -directory $dir -nocomplain -types {d} -- *]] {
 		$current_listbox insert end "[file tail $item]/"
diff --git a/src/m_binbuf.c b/src/m_binbuf.c
index 71bc12f45..13b0293ea 100644
--- a/src/m_binbuf.c
+++ b/src/m_binbuf.c
@@ -234,6 +234,7 @@ writing to file doesn't buffer everything together. */
 
 void binbuf_add(t_binbuf *x, int argc, t_atom *argv)
 {
+	//fprintf(stderr,"binbuf_add_started %d\n", argc);
     int newsize = x->b_n + argc, i;
     t_atom *ap;
     if (ap = t_resizebytes(x->b_vec, x->b_n * sizeof(*x->b_vec),
@@ -244,6 +245,18 @@ void binbuf_add(t_binbuf *x, int argc, t_atom *argv)
         error("binbuf_addmessage: out of space");
         return;
     }
+	/*
+	for (i=0; i < argc; i++) {
+        if (argv[i].a_type == A_SYMBOL)
+        {
+            fprintf(stderr, "binbuf_add: %s\n", argv[i].a_w.w_symbol->s_name);
+        }
+        else if (argv[i].a_type == A_FLOAT)
+        {
+            fprintf(stderr, "binbuf_add: %g\n", argv[i].a_w.w_float);
+        }
+	}
+	*/
 #if 0
     startpost("binbuf_add: ");
     postatom(argc, argv);
@@ -252,11 +265,13 @@ void binbuf_add(t_binbuf *x, int argc, t_atom *argv)
     for (ap = x->b_vec + x->b_n, i = argc; i--; ap++)
         *ap = *(argv++);
     x->b_n = newsize;
+	//fprintf(stderr,"done binbuf_add\n");
 }
 
 #define MAXADDMESSV 100
 void binbuf_addv(t_binbuf *x, char *fmt, ...)
 {
+	//fprintf(stderr,"binbuf_addv started\n");
     va_list ap;
     t_atom arg[MAXADDMESSV], *at =arg;
     int nargs = 0;
@@ -272,9 +287,15 @@ void binbuf_addv(t_binbuf *x, char *fmt, ...)
         }
         switch(*fp++)
         {
-        case 'i': SETFLOAT(at, va_arg(ap, int)); break;
-        case 'f': SETFLOAT(at, va_arg(ap, double)); break;
-        case 's': SETSYMBOL(at, va_arg(ap, t_symbol *)); break;
+        case 'i': SETFLOAT(at, va_arg(ap, int));
+					//fprintf(stderr, "i = %f\n", at->a_w.w_float);
+					break;
+        case 'f': SETFLOAT(at, va_arg(ap, double)); 
+					//fprintf(stderr, "f = %f\n", at->a_w.w_float);
+					break;
+        case 's': SETSYMBOL(at, va_arg(ap, t_symbol *)); 
+					//fprintf(stderr, "s = %s\n", at->a_w.w_symbol->s_name);
+					break;
         case ';': SETSEMI(at); break;
         case ',': SETCOMMA(at); break;
         default: goto done;
@@ -284,6 +305,7 @@ void binbuf_addv(t_binbuf *x, char *fmt, ...)
     }
 done:
     va_end(ap);
+	//fprintf(stderr,"done binbuf_addv\n");
     binbuf_add(x, nargs, arg);
 }
 
@@ -292,6 +314,7 @@ symbols ";", "'",; the symbol ";" goes to "\;", etc. */
 
 void binbuf_addbinbuf(t_binbuf *x, t_binbuf *y)
 {
+	//fprintf(stderr,"starting binbuf_addbinbuf\n");
     t_binbuf *z = binbuf_new();
     int i;
     t_atom *ap;
@@ -302,22 +325,28 @@ void binbuf_addbinbuf(t_binbuf *x, t_binbuf *y)
         switch (ap->a_type)
         {
         case A_FLOAT:
+			//fprintf(stderr,"addbinbuf: float\n");
             break;
         case A_SEMI:
+			//fprintf(stderr,"addbinbuf: semi\n");
             SETSYMBOL(ap, gensym(";"));
             break;
         case A_COMMA:
+			//fprintf(stderr,"addbinbuf: comma\n");
             SETSYMBOL(ap, gensym(","));
             break;
         case A_DOLLAR:
+			//fprintf(stderr,"addbinbuf: dollar\n");
             sprintf(tbuf, "$%d", ap->a_w.w_index);
             SETSYMBOL(ap, gensym(tbuf));
             break;
         case A_DOLLSYM:
+			//fprintf(stderr,"addbinbuf: dollsym\n");
             atom_string(ap, tbuf, MAXPDSTRING);
             SETSYMBOL(ap, gensym(tbuf));
             break;
         case A_SYMBOL:
+			//fprintf(stderr,"addbinbuf: symbol\n");
                 /* FIXME make this general */
             if (!strcmp(ap->a_w.w_symbol->s_name, ";"))
                 SETSYMBOL(ap, gensym(";"));
@@ -330,6 +359,7 @@ void binbuf_addbinbuf(t_binbuf *x, t_binbuf *y)
     }
     
     binbuf_add(x, z->b_n, z->b_vec);
+	//fprintf(stderr,"done binbuf_addbinbuf\n");
 }
 
 void binbuf_addsemi(t_binbuf *x)
@@ -778,21 +808,21 @@ int binbuf_read(t_binbuf *b, char *filename, char *dirname, int crflag)
     
     if ((fd = binbuf_doopen(namebuf, 0)) < 0)
     {
-        fprintf(stderr, "open: ");
+        //fprintf(stderr, "open: ");
         perror(namebuf);
         return (1);
     }
     if ((length = lseek(fd, 0, SEEK_END)) < 0 || lseek(fd, 0, SEEK_SET) < 0 
         || !(buf = t_getbytes(length)))
     {
-        fprintf(stderr, "lseek: ");
+        //fprintf(stderr, "lseek: ");
         perror(namebuf);
         close(fd);
         return(1);
     }
     if ((readret = read(fd, buf, length)) < length)
     {
-        fprintf(stderr, "read (%d %ld) -> %d\n", fd, length, readret);
+        //fprintf(stderr, "read (%d %ld) -> %d\n", fd, length, readret);
         perror(namebuf);
         close(fd);
         t_freebytes(buf, length);
@@ -879,7 +909,7 @@ int binbuf_write(t_binbuf *x, char *filename, char *dir, int crflag)
     
     if (!(f = binbuf_dofopen(fbuf, "w")))
     {
-        fprintf(stderr, "open: ");
+        //fprintf(stderr, "open: ");
         sys_unixerror(fbuf);
         goto fail;
     }
diff --git a/src/m_obj.c b/src/m_obj.c
index 4b1a0f57e..71166aca4 100644
--- a/src/m_obj.c
+++ b/src/m_obj.c
@@ -470,6 +470,11 @@ t_outconnect *obj_connect(t_object *source, int outno,
     t_outlet *o;
     t_pd *to;
     t_outconnect *oc, *oc2;
+
+	/* ignore attempts to connect to the same object
+	   this occurs sometimes using undo/redo */
+	if (source == sink)
+		return (0);
     
     for (o = source->ob_outlet; o && outno; o = o->o_next, outno--) ;
     if (!o) return (0);
@@ -509,7 +514,6 @@ void obj_disconnect(t_object *source, int outno, t_object *sink, int inno)
     t_outlet *o;
     t_pd *to;
     t_outconnect *oc, *oc2;
-    
     for (o = source->ob_outlet; o && outno; o = o->o_next, outno--)
     if (!o) return;
     if (sink->ob_pd->c_firstin)
@@ -525,7 +529,7 @@ void obj_disconnect(t_object *source, int outno, t_object *sink, int inno)
     if (!i) return;
     to = &i->i_pd;
 doit:
-    if (!(oc = o->o_connections)) return;
+    if (!o || !(oc = o->o_connections)) return;
     if (oc->oc_to == to)
     {
         o->o_connections = oc->oc_next;
diff --git a/src/m_pd.h b/src/m_pd.h
index 43e901e96..04f15bcf2 100644
--- a/src/m_pd.h
+++ b/src/m_pd.h
@@ -11,7 +11,7 @@ extern "C" {
 #define PD_MAJOR_VERSION 0
 #define PD_MINOR_VERSION 42
 #define PD_BUGFIX_VERSION 5
-#define PD_TEST_VERSION "extended"
+#define PD_TEST_VERSION "extended-l2ork-20101215"
 
 /* old name for "MSW" flag -- we have to take it for the sake of many old
 "nmakefiles" for externs, which will define NT and not MSW */
@@ -647,6 +647,14 @@ EXTERN void c_addmess(t_method fn, t_symbol *sel, t_atomtype arg1, ...);
 #define typedmess pd_typedmess
 #define vmess pd_vmess
 
+// jsarlo
+EXTERN char sys_signal_line_color[8];
+EXTERN char sys_control_line_color[8];
+EXTERN char sys_iolet_select_color[8];
+EXTERN int sys_iolet_select_width;
+EXTERN int sys_dropshadow;
+// end jsarlo
+
 /* A definition to help gui objects straddle 0.34-0.35 changes.  If this is
 defined, there is a "te_xpix" field in objects, not a "te_xpos" as before: */
 
diff --git a/src/m_sched.c b/src/m_sched.c
index a38050ae0..9a9a6b916 100644
--- a/src/m_sched.c
+++ b/src/m_sched.c
@@ -443,8 +443,6 @@ static void m_pollingscheduler( void)
             /* T.Grill - done */
             sys_unlock();
 #endif
-/* this code causes more issues than it solves on Mac OS X and maybe Windows */
-#ifdef __linux__
                 /* if dacs remain "idle" for 1 sec, they're hung up. */
             if (timeforward != 0)
                 idlecount = 0;
@@ -472,7 +470,6 @@ static void m_pollingscheduler( void)
                     }
                 }
             }
-#endif /* __linux__ */
         }
         else
         {
diff --git a/src/makefile b/src/makefile
new file mode 100644
index 000000000..3ebb96a29
--- /dev/null
+++ b/src/makefile
@@ -0,0 +1,311 @@
+# On Mac OS X, this needs to be defined to enable dlopen and weak linking
+# support.  Its safe on other platforms since gcc only checks this env var on
+# Apple's gcc.  <hans@at.or.at>
+ifeq ($(shell uname -s),Darwin)
+export MACOSX_DEPLOYMENT_TARGET = 10.3
+endif
+
+VPATH = ../obj:./
+OBJ_DIR = ../obj
+BIN_DIR = ../bin
+PDEXEC = $(BIN_DIR)/pd-l2ork
+EXT= pd_linux
+GUINAME= pd-gui
+
+prefix = /usr/local
+exec_prefix = ${prefix}
+bindir = ${exec_prefix}/bin
+includedir = ${prefix}/include
+libdir = ${exec_prefix}/lib
+mandir = ${prefix}/share/man
+
+GFLAGS = -DINSTALL_PREFIX=\"$(prefix)\"
+
+# varibles to match packages/Makefile.buildlayout so that they can be easily
+# overridden when building Pd-extended builds. <hans@at.or.at>
+libpddir = $(libdir)/pd-l2ork
+pddocdir = $(libpddir)/doc
+libpdbindir = $(libpddir)/bin
+
+CPPFLAGS = -DDL_OPEN -DPA_USE_OSS -DUNIX -DUNISTD        -DUSEAPI_OSS         -fno-strict-aliasing -DPA_USE_ALSA -DUSEAPI_ALSA
+MORECFLAGS =  -O6 -funroll-loops -fomit-frame-pointer -DUSEAPI_JACK -D_LARGEFILE64_SOURCE
+# if on 10.6/Intel, then build GUI as 32-bit
+ifeq ($(shell uname -r | sed 's|\([0-9][0-9]*\)\.[0-9][0-9]*\.[0-9][0-9]*|\1|'), 10)
+  GINCLUDE = -arch i386 $(CPPFLAGS) -framework Tcl -framework Tk
+else
+  GINCLUDE = $(CPPFLAGS)  -I/usr/include/tcl8.5
+endif
+GLIB = -ltk8.5 -ltcl8.5  -lrt -ljack -ljack
+
+LDFLAGS = -Wl,-export-dynamic -lasound -lrt -ljack
+LIB =   -ldl -lm -lpthread -lasound
+
+WARN_CFLAGS = -Wall -W -Wstrict-prototypes \
+    -Wno-unused -Wno-parentheses -Wno-switch
+ARCH_CFLAGS = -DPD 
+
+CFLAGS = -g -O2 $(ARCH_CFLAGS) $(WARN_CFLAGS) $(CPPFLAGS) $(MORECFLAGS)
+
+# the sources
+
+SYSSRC += s_midi_oss.c s_audio_oss.c s_audio_alsa.c s_audio_alsamm.c s_midi_alsa.c s_audio_jack.c d_fft_mayer.c d_fftroutine.c
+
+ASIOSRC = 
+
+ASIOOBJ = $(ASIOSRC:.cpp=.o)
+
+# these files cause a warning when using auto-vectorization:
+# "warning: dereferencing type-punned pointer will break strict-aliasing rules"
+TYPE_PUNNING_SRC = d_ctl.c d_array.c d_delay.c d_filter.c d_math.c d_osc.c d_soundfile.c
+
+# these are safe for full gcc 4.x optimization
+OPT_SAFE_SRC = g_canvas.c g_graph.c g_text.c g_rtext.c g_array.c g_template.c g_io.c \
+    g_scalar.c g_traversal.c g_guiconnect.c g_readwrite.c g_editor.c \
+    g_all_guis.c g_bang.c g_hdial.c g_hslider.c g_mycanvas.c g_numbox.c \
+    g_toggle.c g_vdial.c g_vslider.c g_vumeter.c g_magicglass.c \
+    m_pd.c m_class.c m_obj.c m_atom.c m_memory.c m_binbuf.c \
+    m_conf.c m_glob.c m_sched.c \
+    s_main.c s_inter.c s_file.c s_print.c \
+    s_loader.c s_path.c s_entry.c s_audio.c s_midi.c \
+    d_ugen.c d_arithmetic.c d_dac.c d_misc.c \
+    d_fft.c d_global.c \
+    d_resample.c \
+    x_arithmetic.c x_connective.c x_interface.c x_midi.c x_misc.c \
+    x_time.c x_acoustics.c x_net.c x_qlist.c x_gui.c x_list.c \
+	import.c \
+    $(SYSSRC)
+
+SRC = $(TYPE_PUNNING_SRC) $(OPT_SAFE_SRC)
+
+TYPE_PUNNING_OBJ = $(TYPE_PUNNING_SRC:.c=.o) 
+OPT_SAFE_OBJ = $(OPT_SAFE_SRC:.c=.o) 
+OBJ = $(SRC:.c=.o) 
+
+GSRC =  t_main.c t_tkcmd.c
+
+GOBJ = $(GSRC:.c=.o)
+
+# get version from m_pd.h to use in doc/1.manual/1.introduction.txt
+PD_MAJOR_VERSION := $(shell grep PD_MAJOR_VERSION m_pd.h | \
+	sed 's|^.define *PD_MAJOR_VERSION *\([0-9]*\).*|\1|' )
+PD_MINOR_VERSION := $(shell grep PD_MINOR_VERSION m_pd.h | \
+	sed 's|^.define *PD_MINOR_VERSION *\([0-9]*\).*|\1|' )
+PD_BUGFIX_VERSION := $(shell grep PD_BUGFIX_VERSION m_pd.h | \
+	sed 's|^.define *PD_BUGFIX_VERSION *\([0-9]*\).*|\1|' )
+PD_TEST_VERSION := $(shell grep PD_TEST_VERSION m_pd.h | \
+	sed 's|^.define *PD_TEST_VERSION *"\(.*\)".*|\1|' )
+PD_VERSION := $(PD_MAJOR_VERSION).$(PD_MINOR_VERSION).$(PD_BUGFIX_VERSION)
+ifneq ($(PD_TEST_VERSION),)
+	PD_VERSION := $(PD_VERSION)-$(PD_TEST_VERSION)
+endif
+
+#
+#  ------------------ targets ------------------------------------
+#
+
+.PHONY: pd gui externs all
+
+all: pd $(BIN_DIR)/pd-watchdog gui $(BIN_DIR)/pdsend \
+    $(BIN_DIR)/pdreceive externs
+
+bin: pd $(BIN_DIR)/pd-watchdog gui $(BIN_DIR)/pdsend \
+    $(BIN_DIR)/pdreceive
+
+$(OPT_SAFE_OBJ) : %.o : %.c
+	$(CC) $(CFLAGS) $(OPT_CFLAGS) $(GFLAGS) $(INCLUDE) -c -o $(OBJ_DIR)/$*.o $*.c 
+
+$(TYPE_PUNNING_OBJ) : %.o : %.c
+	$(CC) $(CFLAGS) $(GFLAGS) $(INCLUDE) -c -o $(OBJ_DIR)/$*.o $*.c 
+
+$(GOBJ) : %.o : %.c
+	$(CC) $(CFLAGS) $(GFLAGS) $(GINCLUDE) -c -o $(OBJ_DIR)/$*.o $*.c 
+
+$(ASIOOBJ): %.o : %.cpp
+	$(CXX) $(CFLAGS) $(INCLUDE) -c -o $(OBJ_DIR)/$*.o $*.cpp
+
+pd: $(PDEXEC)
+
+ifneq ($(GSRC),)
+gui: $(BIN_DIR)/$(GUINAME)
+else
+gui:
+endif
+
+pd-watchdog: $(BIN_DIR)/pd-watchdog
+
+$(BIN_DIR):
+	test -d $(BIN_DIR) || mkdir -p $(BIN_DIR)
+
+$(BIN_DIR)/pd-watchdog: s_watchdog.c $(BIN_DIR)
+	$(CC) $(CFLAGS) $(STRIPFLAG) -o $(BIN_DIR)/pd-watchdog s_watchdog.c
+
+$(BIN_DIR)/pdsend: u_pdsend.c $(BIN_DIR)
+	$(CC) $(CFLAGS)  $(STRIPFLAG) -o $(BIN_DIR)/pdsend u_pdsend.c
+
+$(BIN_DIR)/pdreceive: u_pdreceive.c $(BIN_DIR)
+	$(CC) $(CFLAGS)  $(STRIPFLAG) -o $(BIN_DIR)/pdreceive u_pdreceive.c
+
+$(PDEXEC): $(OBJ) $(BIN_DIR)
+	cd ../obj;  $(CC) $(LDFLAGS) $(DBG_CFLAGS) -o $(PDEXEC) $(OBJ) $(LIB)
+
+$(BIN_DIR)/pd-gui: $(GOBJ) $(GSRC)
+	cd ../obj; $(CC) $(INCLUDE) -o $(BIN_DIR)/$(GUINAME) $(GOBJ) $(GLIB)
+
+# if on 10.6/Intel, then force build GUI as 32-bit
+ifeq ($(shell uname -r | sed 's|\([0-9][0-9]*\)\.[0-9][0-9]*\.[0-9][0-9]*|\1|'), 10)
+  ARCH_FLAG = -arch i386
+else
+  ARCH_FLAG = 
+endif
+#this is for Max OSX only...
+$(BIN_DIR)/libPdTcl.dylib: $(GOBJ) $(GSRC)
+	cd ../obj && $(CC) $(ARCH_FLAG) $(CFLAGS) -dynamiclib -read_only_relocs warning  \
+		-o $(BIN_DIR)/libPdTcl.dylib $(GOBJ)  \
+		-F \
+		-framework Tcl  -framework Tk  -framework System  \
+		-Wl,-install_name,@executable_path/../Resources/bin/libPdTcl.dylib
+	install_name_tool -change /Tcl.framework/Versions/8.4/Tcl\
+		 @executable_path/../Frameworks/Tcl.framework/Versions/8.4/Tcl \
+		 -change /Tk.framework/Versions/8.4/Tk \
+		 @executable_path/../Frameworks/Tk.framework/Versions/8.4/Tk \
+		../bin/libPdTcl.dylib
+
+# this is for Windows/MinGW (only?)
+$(BIN_DIR)/pdtcl.dll: $(GOBJ)
+	cd $(BIN_DIR); dllwrap --export-all-symbols --output-def pdtcl.def \
+	--output-lib=pdtcl.a --dllname=$(GUINAME) $(OBJ_DIR)/t_tkcmd.o $(LIB) $(GLIB)
+	strip --strip-unneeded $(BIN_DIR)/pdtcl.dll
+
+externs: 
+	make -C ../extra/bonk~    
+	make -C ../extra/choice   
+	make -C ../extra/expr~    
+	make -C ../extra/fiddle~  
+	make -C ../extra/loop~    
+	make -C ../extra/lrshift~ 
+	make -C ../extra/pique    
+	make -C ../extra/sigmund~ 
+	make -C ../extra/pd~      
+	make -C ../extra/stdout   
+
+BINARYMODE=-m755
+
+ABOUT_FILE=$(DESTDIR)$(pddocdir)/1.manual/1.introduction.txt
+install:  all
+	install -d $(DESTDIR)$(libpdbindir)
+	install $(BIN_DIR)/$(GUINAME) $(DESTDIR)$(libpdbindir)/$(GUINAME)
+	install $(BIN_DIR)/pd-watchdog $(DESTDIR)$(libpdbindir)/pd-watchdog
+	install -m644 pd.tk $(DESTDIR)$(libpdbindir)/pd.tk
+	install -m644 pkgIndex.tcl $(DESTDIR)$(libpdbindir)/pkgIndex.tcl
+	install -m644 helpbrowser.tcl $(DESTDIR)$(libpdbindir)/helpbrowser.tcl
+	install -d $(DESTDIR)$(bindir)
+	install $(BINARYMODE) $(PDEXEC) $(DESTDIR)$(bindir)/pd-l2ork
+# kludge to allow pd~ to work by default in pd-l2ork
+	rm -f $(DESTDIR)$(libpddir)/pd
+	ln -s $(bindir)/pd-l2ork $(DESTDIR)$(libpddir)/pd
+	install -m755 $(BIN_DIR)/pdsend $(DESTDIR)$(bindir)/pdsend
+	install -m755 $(BIN_DIR)/pdreceive $(DESTDIR)$(bindir)/pdreceive 
+	for dir in $(shell ls -1 ../doc | grep -v CVS); do \
+		echo "installing $$dir"; \
+		install -d $(DESTDIR)$(pddocdir)/$$dir ; \
+		install -m644 -p ../doc/$$dir/*.* $(DESTDIR)$(pddocdir)/$$dir ; \
+	done
+	for dir in $(shell ls -1 ../doc/7.stuff | grep -v CVS); do \
+		echo "installing 7.stuff/$$dir"; \
+		install -d $(DESTDIR)$(pddocdir)/7.stuff/$$dir ; \
+		install -m644 -p ../doc/7.stuff/$$dir/*.* \
+                    $(DESTDIR)$(pddocdir)/7.stuff/$$dir ; \
+	done
+	mv $(ABOUT_FILE) $(ABOUT_FILE).tmp
+	cat $(ABOUT_FILE).tmp | sed 's|PD_VERSION|Pd version $(PD_VERSION)|' \
+		> $(ABOUT_FILE)
+	rm $(ABOUT_FILE).tmp
+	rsync -ax --exclude=.git --exclude=.svn ../extra $(DESTDIR)$(libpddir)/
+	install -d $(DESTDIR)$(includedir)/pdl2ork
+	install -m644 m_pd.h $(DESTDIR)$(includedir)/pdl2ork/m_pd.h
+	install -m644 m_imp.h $(DESTDIR)$(includedir)/pdl2ork/m_imp.h
+	install -m644 g_canvas.h $(DESTDIR)$(includedir)/pdl2ork/g_canvas.h
+	install -m644 s_stuff.h $(DESTDIR)$(includedir)/pdl2ork/s_stuff.h
+	install -m644 g_all_guis.h $(DESTDIR)$(includedir)/pdl2ork/g_all_guis.h
+	install -d $(DESTDIR)$(mandir)/man1
+	gzip < ../man/pd.1 >  $(DESTDIR)$(mandir)/man1/pd-l2ork.1.gz
+	chmod 644 $(DESTDIR)$(mandir)/man1/pd-l2ork.1.gz
+	gzip < ../man/pdsend.1 >  $(DESTDIR)$(mandir)/man1/pdsend.1.gz
+	chmod 644 $(DESTDIR)$(mandir)/man1/pdsend.1.gz
+	gzip < ../man/pdreceive.1 >  $(DESTDIR)$(mandir)/man1/pdreceive.1.gz
+	chmod 644 $(DESTDIR)$(mandir)/man1/pdreceive.1.gz
+	@echo "Pd install succeeded."
+
+local-clean:	
+	-rm -f -- $(OBJ)
+	-rm -f ../obj/* $(PDEXEC) $(BIN_DIR)/$(GUINAME) $(BIN_DIR)/pdsend \
+	    $(BIN_DIR)/pdreceive $(BIN_DIR)/pd-watchdog m_stamp.c
+	-rm -f -- *~
+	-(cd ../doc/6.externs; rm -f *.pd_linux)
+	-rm -f makefile.dependencies
+	touch makefile.dependencies
+	chmod 666 makefile.dependencies
+
+extra-clean:
+	-rm -f `find ../extra/ -name "*.pd_*"`
+	-rm -f tags
+
+clean: extra-clean local-clean
+
+distclean: clean
+	-rm -f config.cache config.log config.status makefile tags \
+		autom4te.cache/output.* autom4te.cache/traces.* autom4te.cache/requests
+	-rmdir autom4te.cache
+	-rm -rf autom4te-*.cache
+
+tags: $(SRC) $(GSRC); ctags *.[ch]
+
+depend: makefile.dependencies
+
+makefile.dependencies: makefile
+	$(CC) $(CPPFLAGS) -M $(SRC) > makefile.dependencies
+
+uninstall:
+	rm -f -r $(DESTDIR)$(libpddir)
+	rm -f $(DESTDIR)$(bindir)/pd-l2ork
+	rm -f $(DESTDIR)$(bindir)/pdsend
+	rm -f $(DESTDIR)$(bindir)/pdreceive
+	rm -f $(DESTDIR)$(includedir)/m_pd.h
+	rm -f $(DESTDIR)$(includedir)/m_imp.h
+	rm -f $(DESTDIR)$(includedir)/s_stuff.h
+	rm -f $(DESTDIR)$(includedir)/g_all_guis.h
+	rm -f $(DESTDIR)$(includedir)/g_canvas.
+	rm -f $(DESTDIR)$(mandir)/man1/pd.1.gz
+	rm -f $(DESTDIR)$(mandir)/man1/pdsend.1.gz
+	rm -f $(DESTDIR)$(mandir)/man1/pdreceive.1.gz
+
+include makefile.dependencies
+
+
+TAGS: etags
+
+etags:
+	etags *.h $(SRC) $(SYSSRC)
+	etags --append --language=none --regex="/proc[ \t]+\([^ \t]+\)/\1/" pd.tk *.tcl
+	find /usr/include -type f -name \*.h -exec etags -a '{}' \;
+	make etags_`uname -s`
+
+etags_Darwin:
+	find /System/Library/Frameworks  -type f -name \*.h -exec etags -a '{}' \;
+	find /Library/Frameworks  -type f -name \*.h -exec etags -a '{}' \;
+	find /sw/include -type f -name \*.h -exec etags -a '{}' \;
+
+etags_Linux:
+
+etags_MINGW:
+	find /usr/local/include/ -type f -name \*.h -exec etags -a '{}' \;
+
+
+
+
+
+
+
+
+
+
diff --git a/src/makefile.dependencies b/src/makefile.dependencies
new file mode 100644
index 000000000..343adc95a
--- /dev/null
+++ b/src/makefile.dependencies
@@ -0,0 +1,1115 @@
+d_ctl.o: d_ctl.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/math.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h
+d_array.o: d_array.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/endian.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h
+d_delay.o: d_delay.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+d_filter.o: d_filter.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/math.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h
+d_math.o: d_math.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/math.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h /usr/include/sys/types.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/time.h /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h
+d_osc.o: d_osc.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/math.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h
+d_soundfile.o: d_soundfile.c config.h /usr/include/unistd.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/posix_opt.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/fcntl.h \
+ /usr/include/bits/fcntl.h /usr/include/sys/types.h /usr/include/time.h \
+ /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/pthread.h \
+ /usr/include/sched.h /usr/include/bits/sched.h /usr/include/xlocale.h \
+ /usr/include/signal.h /usr/include/bits/setjmp.h /usr/include/stdio.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/errno.h /usr/include/bits/errno.h \
+ /usr/include/linux/errno.h /usr/include/asm/errno.h \
+ /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \
+ m_pd.h
+g_canvas.o: g_canvas.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ m_imp.h s_stuff.h g_canvas.h /usr/include/string.h \
+ /usr/include/xlocale.h g_all_guis.h g_magicglass.h
+g_graph.o: g_graph.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h m_pd.h t_tk.h g_canvas.h s_stuff.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h
+g_text.o: g_text.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h m_pd.h m_imp.h s_stuff.h t_tk.h g_canvas.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/math.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h
+g_rtext.o: g_rtext.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h m_imp.h s_stuff.h g_canvas.h t_tk.h
+g_array.o: g_array.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ g_canvas.h /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h
+g_template.o: g_template.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ s_stuff.h g_canvas.h
+g_io.o: g_io.c m_pd.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ g_canvas.h /usr/include/string.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/xlocale.h
+g_scalar.o: g_scalar.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ g_canvas.h
+g_traversal.o: g_traversal.c /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ g_canvas.h
+g_guiconnect.o: g_guiconnect.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h g_canvas.h
+g_readwrite.o: g_readwrite.c /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ g_canvas.h /usr/include/string.h /usr/include/xlocale.h
+g_editor.o: g_editor.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h m_pd.h \
+ m_imp.h s_stuff.h g_canvas.h /usr/include/string.h \
+ /usr/include/xlocale.h g_magicglass.h
+g_all_guis.o: g_all_guis.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_bang.o: g_bang.c config.h /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_hdial.o: g_hdial.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_hslider.o: g_hslider.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_mycanvas.o: g_mycanvas.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_numbox.o: g_numbox.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_toggle.o: g_toggle.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_vdial.o: g_vdial.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h
+g_vslider.o: g_vslider.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_vumeter.o: g_vumeter.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/ctype.h m_pd.h g_canvas.h t_tk.h g_all_guis.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+g_magicglass.o: g_magicglass.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h m_imp.h s_stuff.h
+m_pd.o: m_pd.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h m_pd.h m_imp.h
+m_class.o: m_class.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h m_imp.h s_stuff.h \
+ /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/sys/types.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/time.h /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h /usr/include/string.h \
+ /usr/include/xlocale.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h
+m_obj.o: m_obj.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h m_imp.h
+m_atom.o: m_atom.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h
+m_memory.o: m_memory.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ m_pd.h m_imp.h
+m_binbuf.o: m_binbuf.c config.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h m_pd.h s_stuff.h /usr/include/stdio.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/fcntl.h \
+ /usr/include/bits/fcntl.h /usr/include/string.h /usr/include/xlocale.h
+m_conf.o: m_conf.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+m_glob.o: m_glob.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h m_imp.h
+m_sched.o: m_sched.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h m_imp.h s_stuff.h \
+ /usr/include/pthread.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sched.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h \
+ /usr/include/bits/sched.h /usr/include/bits/time.h \
+ /usr/include/xlocale.h /usr/include/signal.h /usr/include/bits/sigset.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/bits/setjmp.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h
+s_main.o: s_main.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h m_imp.h s_stuff.h \
+ /usr/include/sys/types.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include-fixed/limits.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include-fixed/syslimits.h \
+ /usr/include/limits.h /usr/include/bits/posix1_lim.h \
+ /usr/include/bits/local_lim.h /usr/include/linux/limits.h \
+ /usr/include/bits/posix2_lim.h /usr/include/string.h \
+ /usr/include/xlocale.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/fcntl.h /usr/include/bits/fcntl.h /usr/include/stdlib.h \
+ /usr/include/alloca.h /usr/include/unistd.h \
+ /usr/include/bits/posix_opt.h /usr/include/bits/confname.h \
+ /usr/include/getopt.h
+s_inter.o: s_inter.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h m_imp.h \
+ g_canvas.h /usr/include/unistd.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h \
+ /usr/include/sys/socket.h /usr/include/sys/uio.h \
+ /usr/include/sys/types.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/bits/uio.h /usr/include/bits/socket.h \
+ /usr/include/bits/sockaddr.h /usr/include/asm/socket.h \
+ /usr/include/asm/sockios.h /usr/include/netinet/in.h \
+ /usr/include/stdint.h /usr/include/bits/wchar.h /usr/include/bits/in.h \
+ /usr/include/netinet/tcp.h /usr/include/netdb.h /usr/include/rpc/netdb.h \
+ /usr/include/bits/netdb.h /usr/include/stdlib.h /usr/include/alloca.h \
+ /usr/include/sys/time.h /usr/include/sys/mman.h /usr/include/bits/mman.h \
+ /usr/include/sys/resource.h /usr/include/bits/resource.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h /usr/include/signal.h \
+ /usr/include/bits/signum.h /usr/include/bits/siginfo.h \
+ /usr/include/bits/sigaction.h /usr/include/bits/sigcontext.h \
+ /usr/include/bits/sigstack.h /usr/include/bits/sigthread.h \
+ /usr/include/fcntl.h /usr/include/bits/fcntl.h /usr/include/errno.h \
+ /usr/include/bits/errno.h /usr/include/linux/errno.h \
+ /usr/include/asm/errno.h /usr/include/asm-generic/errno.h \
+ /usr/include/asm-generic/errno-base.h /usr/include/string.h \
+ /usr/include/xlocale.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/execinfo.h /usr/include/sched.h /usr/include/bits/sched.h
+s_file.o: s_file.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h \
+ /usr/include/string.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/xlocale.h /usr/include/stdlib.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/errno.h /usr/include/bits/errno.h \
+ /usr/include/linux/errno.h /usr/include/asm/errno.h \
+ /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h \
+ /usr/include/sys/stat.h /usr/include/bits/stat.h /usr/include/fcntl.h \
+ /usr/include/bits/fcntl.h
+s_print.o: s_print.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/stdlib.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/errno.h \
+ /usr/include/bits/errno.h /usr/include/linux/errno.h \
+ /usr/include/asm/errno.h /usr/include/asm-generic/errno.h \
+ /usr/include/asm-generic/errno-base.h s_stuff.h
+s_loader.o: s_loader.c /usr/include/dlfcn.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/dlfcn.h /usr/include/stdlib.h /usr/include/sys/types.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/time.h /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h \
+ /usr/include/sys/stat.h /usr/include/bits/stat.h /usr/include/string.h \
+ /usr/include/xlocale.h m_pd.h s_stuff.h /usr/include/stdio.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h
+s_path.o: s_path.c /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/sys/types.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/unistd.h \
+ /usr/include/bits/posix_opt.h /usr/include/bits/confname.h \
+ /usr/include/getopt.h /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/include/string.h /usr/include/xlocale.h m_pd.h m_imp.h s_stuff.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/fcntl.h /usr/include/bits/fcntl.h /usr/include/ctype.h
+s_entry.o: s_entry.c
+s_audio.o: s_audio.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h \
+ /usr/include/stdio.h /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h \
+ /usr/include/sys/time.h /usr/include/time.h /usr/include/bits/time.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/sys/resource.h \
+ /usr/include/bits/resource.h /usr/include/stdlib.h \
+ /usr/include/sys/types.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/errno.h /usr/include/bits/errno.h \
+ /usr/include/linux/errno.h /usr/include/asm/errno.h \
+ /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h
+s_midi.o: s_midi.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h m_imp.h \
+ /usr/include/unistd.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h \
+ /usr/include/sys/time.h /usr/include/time.h /usr/include/bits/time.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/string.h /usr/include/xlocale.h \
+ /usr/include/stdio.h /usr/include/libio.h /usr/include/_G_config.h \
+ /usr/include/wchar.h /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/signal.h /usr/include/bits/signum.h \
+ /usr/include/bits/siginfo.h /usr/include/bits/sigaction.h \
+ /usr/include/bits/sigcontext.h /usr/include/bits/sigstack.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/bits/sigthread.h
+d_ugen.o: d_ugen.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h m_imp.h \
+ /usr/include/stdlib.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/sys/types.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/time.h /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h
+d_arithmetic.o: d_arithmetic.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+d_dac.o: d_dac.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h
+d_misc.o: d_misc.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h
+d_fft.o: d_fft.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+d_global.o: d_global.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/string.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/xlocale.h
+d_resample.o: d_resample.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+x_arithmetic.o: x_arithmetic.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/math.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h
+x_connective.o: x_connective.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/string.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/xlocale.h /usr/include/stdio.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h
+x_interface.o: x_interface.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+x_midi.o: x_midi.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+x_misc.o: x_misc.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h \
+ /usr/include/math.h /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h /usr/include/stdio.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/unistd.h \
+ /usr/include/bits/posix_opt.h /usr/include/bits/confname.h \
+ /usr/include/getopt.h /usr/include/sys/types.h /usr/include/time.h \
+ /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/sys/time.h \
+ /usr/include/sys/times.h /usr/include/sys/param.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include-fixed/limits.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include-fixed/syslimits.h \
+ /usr/include/limits.h /usr/include/bits/posix1_lim.h \
+ /usr/include/bits/local_lim.h /usr/include/linux/limits.h \
+ /usr/include/bits/posix2_lim.h /usr/include/linux/param.h \
+ /usr/include/asm/param.h
+x_time.o: x_time.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h
+x_acoustics.o: x_acoustics.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/math.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/huge_val.h /usr/include/bits/huge_valf.h \
+ /usr/include/bits/huge_vall.h /usr/include/bits/inf.h \
+ /usr/include/bits/nan.h /usr/include/bits/mathdef.h \
+ /usr/include/bits/mathcalls.h
+x_net.o: x_net.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h \
+ /usr/include/sys/types.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/sys/socket.h \
+ /usr/include/sys/uio.h /usr/include/bits/uio.h \
+ /usr/include/bits/socket.h /usr/include/bits/sockaddr.h \
+ /usr/include/asm/socket.h /usr/include/asm/sockios.h \
+ /usr/include/netinet/in.h /usr/include/stdint.h \
+ /usr/include/bits/wchar.h /usr/include/bits/in.h \
+ /usr/include/netinet/tcp.h /usr/include/netdb.h /usr/include/rpc/netdb.h \
+ /usr/include/bits/netdb.h /usr/include/stdio.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h
+x_qlist.o: x_qlist.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/string.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/xlocale.h /usr/include/unistd.h \
+ /usr/include/bits/posix_opt.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/bits/confname.h \
+ /usr/include/getopt.h
+x_gui.o: x_gui.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/unistd.h \
+ /usr/include/bits/posix_opt.h /usr/include/bits/confname.h \
+ /usr/include/getopt.h
+x_list.o: x_list.c config.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h /usr/include/malloc.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/stdio.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/alloca.h
+import.o: import.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h g_canvas.h \
+ /usr/include/stdio.h /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/stdlib.h /usr/include/sys/types.h /usr/include/time.h \
+ /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/include/string.h /usr/include/xlocale.h
+s_midi_oss.o: s_midi_oss.c config.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/stdlib.h \
+ /usr/include/sys/types.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/include/fcntl.h /usr/include/bits/fcntl.h /usr/include/errno.h \
+ /usr/include/bits/errno.h /usr/include/linux/errno.h \
+ /usr/include/asm/errno.h /usr/include/asm-generic/errno.h \
+ /usr/include/asm-generic/errno-base.h m_pd.h s_stuff.h
+s_audio_oss.o: s_audio_oss.c /usr/include/linux/soundcard.h \
+ /usr/include/linux/ioctl.h /usr/include/asm/ioctl.h \
+ /usr/include/asm-generic/ioctl.h /usr/include/endian.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/linux/patchkey.h m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h s_stuff.h \
+ /usr/include/errno.h /usr/include/bits/errno.h \
+ /usr/include/linux/errno.h /usr/include/asm/errno.h \
+ /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \
+ /usr/include/stdio.h /usr/include/bits/types.h \
+ /usr/include/bits/typesizes.h /usr/include/libio.h \
+ /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/stdlib.h \
+ /usr/include/sys/types.h /usr/include/time.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/sys/time.h \
+ /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/include/sys/ioctl.h /usr/include/bits/ioctls.h \
+ /usr/include/asm/ioctls.h /usr/include/bits/ioctl-types.h \
+ /usr/include/sys/ttydefaults.h /usr/include/fcntl.h \
+ /usr/include/bits/fcntl.h /usr/include/sched.h /usr/include/bits/sched.h \
+ /usr/include/sys/mman.h /usr/include/bits/mman.h
+s_audio_alsa.o: s_audio_alsa.c /usr/include/alsa/asoundlib.h \
+ /usr/include/unistd.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/stdio.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/stdlib.h /usr/include/sys/types.h /usr/include/time.h \
+ /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/fcntl.h \
+ /usr/include/bits/fcntl.h /usr/include/assert.h /usr/include/sys/poll.h \
+ /usr/include/bits/poll.h /usr/include/errno.h /usr/include/bits/errno.h \
+ /usr/include/linux/errno.h /usr/include/asm/errno.h \
+ /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \
+ /usr/include/alsa/asoundef.h /usr/include/alsa/version.h \
+ /usr/include/alsa/global.h /usr/include/alsa/input.h \
+ /usr/include/alsa/output.h /usr/include/alsa/error.h \
+ /usr/include/alsa/conf.h /usr/include/alsa/pcm.h \
+ /usr/include/alsa/rawmidi.h /usr/include/alsa/timer.h \
+ /usr/include/alsa/hwdep.h /usr/include/alsa/control.h \
+ /usr/include/alsa/mixer.h /usr/include/alsa/seq_event.h \
+ /usr/include/alsa/seq.h /usr/include/alsa/seqmid.h \
+ /usr/include/alsa/seq_midi_event.h m_pd.h s_stuff.h \
+ /usr/include/sys/time.h /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/include/sys/ioctl.h /usr/include/bits/ioctls.h \
+ /usr/include/asm/ioctls.h /usr/include/asm/ioctl.h \
+ /usr/include/asm-generic/ioctl.h /usr/include/bits/ioctl-types.h \
+ /usr/include/sys/ttydefaults.h /usr/include/sched.h \
+ /usr/include/bits/sched.h /usr/include/sys/mman.h \
+ /usr/include/bits/mman.h s_audio_alsa.h
+s_audio_alsamm.o: s_audio_alsamm.c /usr/include/alsa/asoundlib.h \
+ /usr/include/unistd.h /usr/include/features.h \
+ /usr/include/bits/predefs.h /usr/include/sys/cdefs.h \
+ /usr/include/bits/wordsize.h /usr/include/gnu/stubs.h \
+ /usr/include/gnu/stubs-32.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/stdio.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/stdlib.h /usr/include/sys/types.h /usr/include/time.h \
+ /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/fcntl.h \
+ /usr/include/bits/fcntl.h /usr/include/assert.h /usr/include/sys/poll.h \
+ /usr/include/bits/poll.h /usr/include/errno.h /usr/include/bits/errno.h \
+ /usr/include/linux/errno.h /usr/include/asm/errno.h \
+ /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \
+ /usr/include/alsa/asoundef.h /usr/include/alsa/version.h \
+ /usr/include/alsa/global.h /usr/include/alsa/input.h \
+ /usr/include/alsa/output.h /usr/include/alsa/error.h \
+ /usr/include/alsa/conf.h /usr/include/alsa/pcm.h \
+ /usr/include/alsa/rawmidi.h /usr/include/alsa/timer.h \
+ /usr/include/alsa/hwdep.h /usr/include/alsa/control.h \
+ /usr/include/alsa/mixer.h /usr/include/alsa/seq_event.h \
+ /usr/include/alsa/seq.h /usr/include/alsa/seqmid.h \
+ /usr/include/alsa/seq_midi_event.h m_pd.h s_stuff.h \
+ /usr/include/sys/time.h /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/include/sys/ioctl.h /usr/include/bits/ioctls.h \
+ /usr/include/asm/ioctls.h /usr/include/asm/ioctl.h \
+ /usr/include/asm-generic/ioctl.h /usr/include/bits/ioctl-types.h \
+ /usr/include/sys/ttydefaults.h /usr/include/sched.h \
+ /usr/include/bits/sched.h s_audio_alsa.h
+s_midi_alsa.o: s_midi_alsa.c config.h /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/unistd.h /usr/include/bits/posix_opt.h \
+ /usr/include/bits/confname.h /usr/include/getopt.h /usr/include/stdlib.h \
+ /usr/include/sys/types.h /usr/include/time.h /usr/include/endian.h \
+ /usr/include/bits/endian.h /usr/include/bits/byteswap.h \
+ /usr/include/sys/select.h /usr/include/bits/select.h \
+ /usr/include/bits/sigset.h /usr/include/bits/time.h \
+ /usr/include/sys/sysmacros.h /usr/include/bits/pthreadtypes.h \
+ /usr/include/alloca.h /usr/include/sys/stat.h /usr/include/bits/stat.h \
+ /usr/include/fcntl.h /usr/include/bits/fcntl.h /usr/include/errno.h \
+ /usr/include/bits/errno.h /usr/include/linux/errno.h \
+ /usr/include/asm/errno.h /usr/include/asm-generic/errno.h \
+ /usr/include/asm-generic/errno-base.h /usr/include/alsa/asoundlib.h \
+ /usr/include/string.h /usr/include/xlocale.h /usr/include/assert.h \
+ /usr/include/sys/poll.h /usr/include/bits/poll.h \
+ /usr/include/alsa/asoundef.h /usr/include/alsa/version.h \
+ /usr/include/alsa/global.h /usr/include/alsa/input.h \
+ /usr/include/alsa/output.h /usr/include/alsa/error.h \
+ /usr/include/alsa/conf.h /usr/include/alsa/pcm.h \
+ /usr/include/alsa/rawmidi.h /usr/include/alsa/timer.h \
+ /usr/include/alsa/hwdep.h /usr/include/alsa/control.h \
+ /usr/include/alsa/mixer.h /usr/include/alsa/seq_event.h \
+ /usr/include/alsa/seq.h /usr/include/alsa/seqmid.h \
+ /usr/include/alsa/seq_midi_event.h m_pd.h s_stuff.h
+s_audio_jack.o: s_audio_jack.c
+d_fft_mayer.o: d_fft_mayer.c m_pd.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h
+d_fftroutine.o: d_fftroutine.c /usr/include/stdio.h \
+ /usr/include/features.h /usr/include/bits/predefs.h \
+ /usr/include/sys/cdefs.h /usr/include/bits/wordsize.h \
+ /usr/include/gnu/stubs.h /usr/include/gnu/stubs-32.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stddef.h \
+ /usr/include/bits/types.h /usr/include/bits/typesizes.h \
+ /usr/include/libio.h /usr/include/_G_config.h /usr/include/wchar.h \
+ /usr/lib/gcc/i486-linux-gnu/4.4.1/include/stdarg.h \
+ /usr/include/bits/stdio_lim.h /usr/include/bits/sys_errlist.h \
+ /usr/include/math.h /usr/include/bits/huge_val.h \
+ /usr/include/bits/huge_valf.h /usr/include/bits/huge_vall.h \
+ /usr/include/bits/inf.h /usr/include/bits/nan.h \
+ /usr/include/bits/mathdef.h /usr/include/bits/mathcalls.h \
+ /usr/include/stdlib.h /usr/include/sys/types.h /usr/include/time.h \
+ /usr/include/endian.h /usr/include/bits/endian.h \
+ /usr/include/bits/byteswap.h /usr/include/sys/select.h \
+ /usr/include/bits/select.h /usr/include/bits/sigset.h \
+ /usr/include/bits/time.h /usr/include/sys/sysmacros.h \
+ /usr/include/bits/pthreadtypes.h /usr/include/alloca.h m_pd.h
diff --git a/src/makefile.in b/src/makefile.in
index ce12d470a..51e141b76 100644
--- a/src/makefile.in
+++ b/src/makefile.in
@@ -23,7 +23,7 @@ GFLAGS = -DINSTALL_PREFIX=\"$(prefix)\"
 
 # varibles to match packages/Makefile.buildlayout so that they can be easily
 # overridden when building Pd-extended builds. <hans@at.or.at>
-libpddir = $(libdir)/pd-extended
+libpddir = $(libdir)/pd-l2ork
 pddocdir = $(libpddir)/doc
 libpdbindir = $(libpddir)/bin
 
@@ -62,7 +62,7 @@ TYPE_PUNNING_SRC = d_ctl.c d_array.c d_delay.c d_filter.c d_math.c d_osc.c d_sou
 OPT_SAFE_SRC = g_canvas.c g_graph.c g_text.c g_rtext.c g_array.c g_template.c g_io.c \
     g_scalar.c g_traversal.c g_guiconnect.c g_readwrite.c g_editor.c \
     g_all_guis.c g_bang.c g_hdial.c g_hslider.c g_mycanvas.c g_numbox.c \
-    g_toggle.c g_vdial.c g_vslider.c g_vumeter.c \
+    g_toggle.c g_vdial.c g_vslider.c g_vumeter.c g_magicglass.c \
     m_pd.c m_class.c m_obj.c m_atom.c m_memory.c m_binbuf.c \
     m_conf.c m_glob.c m_sched.c \
     s_main.c s_inter.c s_file.c s_print.c \
@@ -200,8 +200,9 @@ install:  all
 	install -m644 helpbrowser.tcl $(DESTDIR)$(libpdbindir)/helpbrowser.tcl
 	install -d $(DESTDIR)$(bindir)
 	install $(BINARYMODE) $(PDEXEC) $(DESTDIR)$(bindir)/@PDEXEC@
-# kludge to allow pd~ to work by default in pd-extended
-	ln -s $(bindir)/pdextended $(DESTDIR)$(libpddir)/pd
+# kludge to allow pd~ to work by default in pd-l2ork
+	rm -f $(DESTDIR)$(libpddir)/pd
+	ln -s $(bindir)/pd-l2ork $(DESTDIR)$(libpddir)/pd
 	install -m755 $(BIN_DIR)/pdsend $(DESTDIR)$(bindir)/pdsend
 	install -m755 $(BIN_DIR)/pdreceive $(DESTDIR)$(bindir)/pdreceive 
 	for dir in $(shell ls -1 ../doc | grep -v CVS); do \
@@ -220,12 +221,12 @@ install:  all
 		> $(ABOUT_FILE)
 	rm $(ABOUT_FILE).tmp
 	rsync -ax --exclude=.git --exclude=.svn ../extra $(DESTDIR)$(libpddir)/
-	install -d $(DESTDIR)$(includedir)/pdextended
-	install -m644 m_pd.h $(DESTDIR)$(includedir)/pdextended/m_pd.h
-	install -m644 m_imp.h $(DESTDIR)$(includedir)/pdextended/m_imp.h
-	install -m644 g_canvas.h $(DESTDIR)$(includedir)/pdextended/g_canvas.h
-	install -m644 s_stuff.h $(DESTDIR)$(includedir)/pdextended/s_stuff.h
-	install -m644 g_all_guis.h $(DESTDIR)$(includedir)/pdextended/g_all_guis.h
+	install -d $(DESTDIR)$(includedir)/pdl2ork
+	install -m644 m_pd.h $(DESTDIR)$(includedir)/pdl2ork/m_pd.h
+	install -m644 m_imp.h $(DESTDIR)$(includedir)/pdl2ork/m_imp.h
+	install -m644 g_canvas.h $(DESTDIR)$(includedir)/pdl2ork/g_canvas.h
+	install -m644 s_stuff.h $(DESTDIR)$(includedir)/pdl2ork/s_stuff.h
+	install -m644 g_all_guis.h $(DESTDIR)$(includedir)/pdl2ork/g_all_guis.h
 	install -d $(DESTDIR)$(mandir)/man1
 	gzip < ../man/pd.1 >  $(DESTDIR)$(mandir)/man1/@PDEXEC@.1.gz
 	chmod 644 $(DESTDIR)$(mandir)/man1/@PDEXEC@.1.gz
diff --git a/src/makefile.mingw b/src/makefile.mingw
index 78c5834a8..ca7d0b3b0 100755
--- a/src/makefile.mingw
+++ b/src/makefile.mingw
@@ -254,15 +254,15 @@ install:  all
 	install -p pd.ico $(DESTDIR)$(bindir)/pd.ico
 	install -p pdsend.exe $(DESTDIR)$(bindir)/pdsend.exe
 	install -p pdreceive.exe $(DESTDIR)$(bindir)/pdreceive.exe
-	install -d $(DESTDIR)$(includedir)/pdextended
-	install -p m_pd.h $(DESTDIR)$(includedir)/pdextended/m_pd.h
-	install -p m_imp.h $(DESTDIR)$(includedir)/pdextended/m_imp.h
-	install -p g_canvas.h $(DESTDIR)$(includedir)/pdextended/g_canvas.h
-	install -p s_stuff.h $(DESTDIR)$(includedir)/pdextended/s_stuff.h
-	install -p g_all_guis.h $(DESTDIR)$(includedir)/pdextended/g_all_guis.h
+	install -d $(DESTDIR)$(includedir)/pdl2ork
+	install -p m_pd.h $(DESTDIR)$(includedir)/pdl2ork/m_pd.h
+	install -p m_imp.h $(DESTDIR)$(includedir)/pdl2ork/m_imp.h
+	install -p g_canvas.h $(DESTDIR)$(includedir)/pdl2ork/g_canvas.h
+	install -p s_stuff.h $(DESTDIR)$(includedir)/pdl2ork/s_stuff.h
+	install -p g_all_guis.h $(DESTDIR)$(includedir)/pdl2ork/g_all_guis.h
 # since Pd-vanilla on Mac OS X doesn't have an 'include/pd' folder,
 # Pd-extended will mimic Pd-vanilla's include/pd until Pd-vanilla gets one
-	cp -pr $(DESTDIR)$(includedir)/pdextended $(DESTDIR)$(includedir)/pd
+	cp -pr $(DESTDIR)$(includedir)/pdl2ork $(DESTDIR)$(includedir)/pd
 	install -p m_pd.h $(DESTDIR)$(includedir)
 	for dir in $(shell ls -1 ../doc | grep -v CVS); do \
 		echo "installing $$dir"; \
diff --git a/src/makefile.nt b/src/makefile.nt
new file mode 100644
index 000000000..7b4e834e8
--- /dev/null
+++ b/src/makefile.nt
@@ -0,0 +1,175 @@
+# Makefile for PD on MSW
+
+all: pd ..\bin\pdsend.exe ..\bin\pdreceive.exe
+
+
+VCSDK = "C:\Program Files\Microsoft SDKs\Windows\v6.0A"
+VC9 = "C:\Program Files\Microsoft Visual Studio 9.0\VC"
+#VC="\Program Files\DevStudio\Vc"
+INCLUDE = -I.\ -I..\Tcl\include -I\DXSDK\include -I$(VC9)\Include \
+ -I$(VCSDK)\Include
+
+LDIR = $(VCSDK)\lib
+LD2 = $(VC9)\lib
+
+LIB = /NODEFAULTLIB:libcmt /NODEFAULTLIB:oldnames /NODEFAULTLIB:libc \
+    /NODEFAULTLIB:uuid $(LDIR)\kernel32.lib \
+    $(LDIR)\wsock32.lib $(LDIR)\winmm.lib $(LDIR)\advapi32.lib \
+    $(LDIR)\setupapi.lib ..\bin\pthreadVC.lib \
+    $(LD2)\libcmt.lib $(LD2)\oldnames.lib
+
+CFLAGS = /nologo /W3 /DMSW /DNT /DPD /DPD_INTERNAL /DWIN32 /DWINDOWS /Ox \
+	-DPA_LITTLE_ENDIAN -DUSEAPI_MMIO -DUSEAPI_PORTAUDIO -D__i386__ -DPA19 \
+        -D_CRT_SECURE_NO_WARNINGS
+LFLAGS = /nologo
+
+SYSSRC = s_audio_pa.c s_audio_pablio.c s_audio_paring.c \
+    s_audio_mmio.c s_midi_pm.c
+
+SRC = g_canvas.c g_graph.c g_text.c g_rtext.c g_array.c g_template.c g_io.c \
+    g_scalar.c g_traversal.c g_guiconnect.c g_readwrite.c g_editor.c \
+    g_all_guis.c g_bang.c g_hdial.c g_hslider.c g_mycanvas.c g_numbox.c \
+    g_toggle.c g_vdial.c g_vslider.c g_vumeter.c \
+    m_pd.c m_class.c m_obj.c m_atom.c m_memory.c m_binbuf.c \
+    m_conf.c m_glob.c m_sched.c \
+    s_main.c s_inter.c s_file.c s_print.c \
+    s_loader.c s_path.c s_entry.c s_audio.c s_midi.c \
+    d_ugen.c d_ctl.c d_arithmetic.c d_osc.c d_filter.c d_dac.c d_misc.c \
+    d_math.c d_fft.c d_fft_mayer.c d_fftroutine.c d_array.c d_global.c \
+    d_delay.c d_resample.c \
+    x_arithmetic.c x_connective.c x_interface.c x_midi.c x_misc.c \
+    x_time.c x_acoustics.c x_net.c x_qlist.c x_gui.c x_list.c d_soundfile.c \
+    $(SYSSRC)
+
+PADIR = ..\portaudio
+INCPA = -I$(PADIR)\include -I$(PADIR)\src\common -I..\lib\asio
+PASRC = $(PADIR)\src
+SRCPA = $(PASRC)/common/pa_stream.c \
+        $(PASRC)/common/pa_trace.c \
+        $(PASRC)/common/pa_skeleton.c \
+        $(PASRC)/common/pa_process.c \
+        $(PASRC)/common/pa_front.c \
+        $(PASRC)/common/pa_dither.c \
+        $(PASRC)/common/pa_cpuload.c \
+        $(PASRC)/common/pa_converters.c \
+        $(PASRC)/common/pa_allocation.c \
+        $(PASRC)/os/win/pa_win_hostapis.c \
+        $(PASRC)/os/win/pa_win_util.c \
+        $(PASRC)/hostapi/wmme/pa_win_wmme.c 
+
+SRCASIO = $(PADIR)/pa_asio/pa_asio.cpp 
+
+ASIOLIB = $(LDIR)\user32.lib $(LDIR)\gdi32.lib $(LDIR)\winspool.lib \
+$(LDIR)\comdlg32.lib $(LDIR)\advapi32.lib $(LDIR)\shell32.lib \
+$(LDIR)\ole32.lib $(LDIR)\oleaut32.lib $(LDIR)\uuid.lib \
+$(LDIR)\odbc32.lib $(LDIR)\odbccp32.lib ..\lib\asio\asiolib.lib
+
+
+PAOBJ = pa_stream.obj pa_trace.obj pa_skeleton.obj pa_process.obj \
+	pa_front.obj pa_dither.obj pa_cpuload.obj pa_converters.obj \
+	pa_allocation.obj pa_win_hostapis.obj pa_win_util.obj pa_asio.obj \
+	pa_win_wmme.obj 
+#       pa_win_wdmks.obj
+
+PMDIR = ..\portmidi
+INCPM = -I$(PMDIR)\pm_common -I$(PMDIR)\pm_win -I$(PMDIR)\porttime -DNEWBUFFER
+SRCPM = $(PADIR)/pm_common/portmidi.c \
+        $(PMDIR)/pm_common/pmutil.c \
+        $(PMDIR)/porttime/porttime.c \
+        $(PMDIR)/porttime/ptwinmm.c \
+        $(PMDIR)/pm_win/pmwin.c \
+        $(PMDIR)/pm_win/pmwinmm.c
+
+PMOBJ = portmidi.obj pmutil.obj porttime.obj ptwinmm.obj pmwin.obj pmwinmm.obj
+
+OBJC = $(SRC:.c=.obj) $(PAOBJ) $(PMOBJ)
+
+GSRC =  t_main.c t_tkcmd.c
+
+GOBJ = $(GSRC:.c=.obj)
+.PHONY: pd gui
+
+ALLCF = $(CFLAGS)  $(INCLUDE) $(INCASIO) $(INCPA) $(INCPM) /D_WINDOWS \
+    /DPA_NO_DS
+
+.c.obj:
+	cl /c $(ALLCF) /Tc$*.c
+
+pd: ..\bin\pd.exe ..\bin\pd.com
+
+..\bin\pd.exe: s_entry.obj ..\bin\pd.lib
+	link $(LFLAGS) /OUT:..\bin\pd.exe /INCREMENTAL:NO s_entry.obj \
+	    ..\bin\pd.lib $(LIB) $(ASIOLIB)
+
+..\bin\pd.dll ..\bin\pd.lib: $(OBJC) $(OBJASIO)
+	link /DLL /OUT:..\bin\pd.dll /EXPORT:sys_main $(LFLAGS) $(OBJC) \
+	    $(OBJASIO) $(LIB) $(ASIOLIB)
+
+..\bin\pdsend.exe: u_pdsend.obj
+	link $(LFLAGS) /out:..\bin\pdsend.exe /INCREMENTAL:NO u_pdsend.obj \
+	    $(LIB)
+
+..\bin\pdreceive.exe: u_pdreceive.obj
+	link $(LFLAGS) /out:..\bin\pdreceive.exe /INCREMENTAL:NO \
+	    u_pdreceive.obj $(LIB)
+
+s_entry_com.obj: s_entry.c
+	copy s_entry.c s_entry_com.c
+	cl /c -DCOMMANDVERSION s_entry_com.c 
+	del s_entry_com.c
+
+..\bin\pd.com: s_entry_com.obj ..\bin\pd.lib
+	link $(LFLAGS) /out:..\bin\pd.com /INCREMENTAL:NO s_entry_com.obj \
+	    ..\bin\pd.lib $(LIB) $(ASIOLIB)
+
+# explicit rules to compile portaudio sources:
+pa_stream.obj: $(PASRC)\common\pa_stream.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_stream.c
+pa_trace.obj: $(PASRC)\common\pa_trace.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_trace.c
+pa_skeleton.obj: $(PASRC)\common\pa_skeleton.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_skeleton.c
+pa_process.obj: $(PASRC)\common\pa_process.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_process.c
+pa_front.obj: $(PASRC)\common\pa_front.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_front.c
+pa_dither.obj: $(PASRC)\common\pa_dither.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_dither.c
+pa_cpuload.obj: $(PASRC)\common\pa_cpuload.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_cpuload.c
+pa_converters.obj: $(PASRC)\common\pa_converters.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_converters.c
+pa_allocation.obj: $(PASRC)\common\pa_allocation.c
+	cl /c $(ALLCF) $(PASRC)\common\pa_allocation.c
+
+pa_win_hostapis.obj: $(PASRC)\os\win\pa_win_hostapis.c
+	cl /c $(ALLCF) $(PASRC)\os\win\pa_win_hostapis.c
+pa_win_util.obj: $(PASRC)\os\win\pa_win_util.c
+	cl /c $(ALLCF) $(PASRC)\os\win\pa_win_util.c
+pa_win_wmme.obj: $(PASRC)\hostapi\wmme\pa_win_wmme.c
+	cl /c $(ALLCF) $(PASRC)\hostapi\wmme\pa_win_wmme.c
+pa_win_wdmks.obj: $(PADIR)\pa_win_wdmks\pa_win_wdmks.c
+	cl /c $(ALLCF) \
+	-DWINVER=0x400 -DKSAUDIO_SPEAKER_DIRECTOUT \
+	$(PADIR)\pa_win_wdmks\pa_win_wdmks.c
+pa_asio.obj: $(PASRC)\hostapi\asio\pa_asio.cpp
+	cl /c $(ALLCF) $(PASRC)\hostapi\asio\pa_asio.cpp
+
+portmidi.obj: $(PMDIR)\pm_common\portmidi.c
+	cl /c $(ALLCF) $(PMDIR)\pm_common\portmidi.c
+pmutil.obj: $(PMDIR)\pm_common\pmutil.c
+	cl /c $(ALLCF) $(PMDIR)\pm_common\pmutil.c
+pmwin.obj: $(PMDIR)\pm_win\pmwin.c
+	cl /c $(ALLCF) $(PMDIR)\pm_win\pmwin.c
+pmwinmm.obj: $(PMDIR)\pm_win\pmwinmm.c
+	cl /c $(ALLCF) $(PMDIR)\pm_win\pmwinmm.c
+porttime.obj: $(PMDIR)\porttime\porttime.c
+	cl /c $(ALLCF) $(PMDIR)\porttime\porttime.c
+ptwinmm.obj: $(PMDIR)\porttime\ptwinmm.c
+	cl /c $(ALLCF) $(PMDIR)\porttime\ptwinmm.c
+
+# the following should also clean up "bin" but it doesn't because "bin" holds
+# precious stuff from elsewhere.
+clean:
+	del *.obj
+
diff --git a/src/pd.tk b/src/pd.tk
index e8cb0b2a3..9a2379ed1 100644
--- a/src/pd.tk
+++ b/src/pd.tk
@@ -9,19 +9,175 @@
 # a new dialogbox was inserted, named:
 # "pdtk_iemgui_dialog -- dialog window for iem guis"
 #
-# all this changes are labeled with #######iemlib##########
+# all these changes are labeled with #######iemlib########
 
 # set pd_nt (bad name) 0 for unix, 1 for microsoft, and 2 for Mac OSX.
+
+#May 22 2009
+#GUI improvements and dynamic runtime 8.5 widget upgrade for Linux by Ivica Ico Bukvic
+#http://ico.bukvic.net <ico@vt.edu>
+
+if { [info tclversion] >= 8.5 } {
+
+	# EDIT THIS PART TO CUSTOMIZE LINUX THEME
+	# match gnome colors
+	# Ubuntu Human
+	set linux_wm_bgcolor "#e5e5e5"
+	# set linux_wm_hlcolor "#fdbf69"
+	set linux_wm_hlcolor "#f9ba81"
+
+	# ttk colors
+	# -frame, -lighter, and -selectbg are automatically
+	#	replaced by theme colors specified above
+	variable colors
+	array set colors {
+		-frame 		"#e5e5e5"
+		-window		"#ffffff"
+		-darkest 	"#999999"
+		-darker 	"#709970"
+		-dark		"#a8e6a8"
+		-light		"#d2ffd2"
+		-lighter 	"#e5e5e5"
+		-disabledfg	"#a3a3a3"
+		-selectbg	"#fdbf69"
+		-selectfg	"#000000"
+	}
+	# STOP EDITING BEYOND THIS POINT
+
+	#sync ttk with theme choice above it
+	set colors(-frame) $linux_wm_bgcolor
+	set colors(-lighter) $linux_wm_bgcolor
+	set colors(-selectbg) $linux_wm_hlcolor
+
+	ttk::style theme create purty_linux -parent clam -settings {
+
+		ttk::style configure "." \
+			-background 	$colors(-frame) \
+			-foreground 	black \
+			-bordercolor	$colors(-darkest) \
+			-selectbackground 	$colors(-selectbg) \
+			-selectforeground 	$colors(-selectfg) \
+			-troughcolor	$colors(-dark) \
+			-arrowcolor 	$colors(-darkest) \
+			-font 		TkDefaultFont \
+			;
+
+		ttk::style map "." -background \
+			[list disabled $colors(-frame)  active $colors(-lighter)] ;
+		ttk::style map "." -foreground [list disabled $colors(-disabledfg)] ;
+		    ttk::style map "." -embossed [list disabled 0] ;
+
+		ttk::style configure TButton \
+			-anchor center -width -11 -padding "1 1" \
+			-relief raised -shiftrelief 1 \
+			-highlightthickness 1 -highlightcolor $colors(-selectbg)
+
+		ttk::style map TButton -relief {
+			{pressed !disabled} 	sunken
+			{active !disabled} 	raised
+		} -highlightcolor {alternate black}
+
+		ttk::style configure TCheckbutton \
+			-indicatorcolor $colors(-window) -padding 2
+		ttk::style configure TRadiobutton \
+			-indicatorcolor $colors(-window) -padding 2
+		ttk::style map TCheckbutton -indicatorcolor \
+			[list  disabled $colors(-frame)  pressed $colors(-frame)]
+		ttk::style map TRadiobutton -indicatorcolor \
+			[list  disabled $colors(-frame)  pressed $colors(-frame)]
+
+		ttk::style configure TMenubutton \
+			-width -11 -padding "3 3" -relief raised
+
+		ttk::style configure TEntry \
+			-padding 1 -fieldbackground $colors(-window) ;
+		ttk::style map TEntry -fieldbackground \
+			[list readonly $colors(-frame) disabled $colors(-frame)]
+		ttk::style configure TCombobox \
+			-padding 1 -fieldbackground $colors(-window) ;
+		ttk::style map TCombobox -fieldbackground \
+			[list readonly $colors(-frame) disabled $colors(-frame)]
+
+		ttk::style configure Toolbutton -relief flat -padding 2
+		ttk::style map Toolbutton -relief \
+			{disabled flat selected sunken pressed sunken active raised}
+		ttk::style map Toolbutton -background \
+			[list pressed $colors(-dark)  active $colors(-light)]
+
+		ttk::style configure TScrollbar -relief raised
+		ttk::style configure TScale \
+			-groovewidth 4 -troughrelief sunken \
+			-sliderwidth raised -borderwidth 2
+		ttk::style configure TProgressbar \
+			-background $colors(-selectbg) -borderwidth 0
+
+		ttk::style configure TLabelframe -relief groove -borderwidth 2
+
+		ttk::style configure TNotebook -tabmargins {2 2 1 0}
+		ttk::style configure TNotebook.Tab \
+			-padding {4 2} -background $colors(-dark)
+		ttk::style map TNotebook.Tab \
+			-background [list selected $colors(-frame)] \
+			-expand [list selected {2 2 1 0}] \
+			;
+
+		ttk::style configure Treeview -fieldbackground $colors(-window)
+		ttk::style configure Heading -font TkHeadingFont -relief raised
+		ttk::style configure Row -background $colors(-window)
+		ttk::style map Row \
+			-background [list selected $colors(-selectbg)]
+		ttk::style map Item \
+			-foreground [list selected $colors(-selectfg)]
+		ttk::style map Cell \
+			-foreground [list selected $colors(-selectfg)]
+	}
+}
+
+# Automate matching of the linux wm and use ttk where possible
+# As of right now it is only enabled if system is Linux/Unix using tcl >= 8.5
+proc match_linux_wm {list} {
+	global pd_nt linux_wm_bgcolor linux_wm_hlcolor
+	if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
+		if {[lsearch -regexp $list ::] == -1} {
+			if {[lindex $list 0] != "button" \
+				&& [lindex $list 0] != "checkbutton" \
+				&& [lindex $list 0] != "radiobutton" \
+				&& [lindex $list 0] != "entry" \
+				&& [lindex $list 0] != "scrollbar"} { 
+					lappend list -bg $linux_wm_bgcolor
+			}
+			if {[lindex $list 0] == "listbox" \
+				|| [lindex $list 0] == "text"} {
+
+				lappend list -bg white -highlightcolor $linux_wm_hlcolor
+			}
+			if {[lindex $list 0] == "menu"} {
+	
+				lappend list -activebackground $linux_wm_hlcolor -bd 0
+			}
+			#convert non-ttk objects to ttk objects
+			if {[lindex $list 0] == "button" \
+				|| [lindex $list 0] == "checkbutton" \
+				|| [lindex $list 0] == "radiobutton" \
+				|| [lindex $list 0] == "entry" \
+				|| [lindex $list 0] == "scrollbar"} { 
+				set newlist [lreplace $list 0 0 ttk::[lindex $list 0]]
+			}
+		}
+	}
+	if {[info exists newlist]} {
+		eval $newlist
+	} else {
+		eval $list
+	}
+}
+
 if { $tcl_platform(platform) == "windows" }  {
     set pd_nt 1
     set ctrl_key "Control"
-    # fonts
+    # fontsc
     set defaultFontFamily {DejaVu Sans Mono}
-    font create menuFont -family Tahoma -size 11
-    option add *Menu.font menuFont startupFile
-    option add *HelpBrowser*font menuFont startupFile
-    option add *DialogWindow*font menuFont startupFile
-    option add *PdWindow*font menuFont startupFile
+    font create menuFont -family Tahoma -size 10
     # mouse cursors
     set cursor_runmode_nothing "arrow"
     set cursor_runmode_clickme "right_ptr"
@@ -66,8 +222,14 @@ if { $tcl_platform(platform) == "windows" }  {
 	}
 	set externalsdir "$::env(HOME)/Library/Pd"
 } else { 
+	# set nicer theme
+	ttk::style theme use purty_linux
+	set window_prefs {}
     set pd_nt 0
     set ctrl_key "Control"
+	# Ctrl modifier
+	set ctrl_l_down 0
+	set ctrl_r_down 0
     # fonts
     set defaultFontFamily {DejaVu Sans Mono}
     # mouse cursors
@@ -76,7 +238,7 @@ if { $tcl_platform(platform) == "windows" }  {
     set cursor_runmode_thicken "sb_v_double_arrow"
     set cursor_runmode_addpoint "plus"
     set cursor_editmode_nothing "hand2"
-    set cursor_editmode_connect "circle"
+    set cursor_editmode_connect "target"
     set cursor_editmode_disconnect "X_cursor"
 	# set file types that open/save recognize
 	set filetypes {
@@ -132,25 +294,64 @@ proc center_window { w args } {
 # start Pd-extended font hacks -----------------------------
 
 # Pd-0.39.2-extended hacks to make font/box sizes the same across platform
-puts stderr "tk scaling is [tk scaling]"
+#puts stderr "tk scaling is [tk scaling]"
 tk scaling 1
 
-# for some reason, the fonts are bigger in Tcl/Tk 8.5 than 8.4
-if {$pd_nt != 1 && $::tcl_version eq "8.5"} {
-	set console_font_size 9
-} else { 
-	set console_font_size 12
-}
 # this font is for the Pd Window console text
-font create console_font -family $defaultFontFamily -weight normal \
-	-size $console_font_size
+font create console_font -family $defaultFontFamily -size 9 -weight normal
 # this font is for text in Pd windows
-font create text_font -family {Times} -size 14 -weight normal
+font create text_font -family $defaultFontFamily -size 9 -weight normal
 # for text in Properties Panels and other panes
-font create highlight_font -family $defaultFontFamily -size 14 -weight bold
+font create highlight_font -family $defaultFontFamily -size 9 -weight bold
 
 # end Pd-extended font hacks -----------------------------
 
+# calculate offset on a movable canvas
+set tmp_xpix 0
+set tmp_ypix 0
+
+set popup_xpix 0
+set popup_ypix 0
+
+# monitor pointer position
+set pointer_x_local 0
+set pointer_y_local 0
+
+set pointer_x_virtual 0
+set pointer_y_virtual 0
+
+set pointer_x_global 0
+set pointer_y_global 0
+
+# text pasting global
+set copytexttocanvas 0
+
+# x:y location tooltip during dragging
+set tooltip [toplevel .tooltip -bd 1 -bg black]
+wm attributes $tooltip -topmost 1
+wm overrideredirect $tooltip 1
+pack [label $tooltip.label -bg lightyellow -fg black -text aaa -justify left]
+wm withdraw $tooltip
+
+# timeout for the tooltip
+proc pdtk_toggle_xy_tooltip {name num} {
+	global tooltip
+	if {$num == 0} {
+		wm withdraw $tooltip
+	} else {
+		wm deiconify $tooltip
+	}
+}
+
+proc pdtk_update_xy_tooltip {name x y} {
+	global tooltip
+	global pointer_x_virtual pointer_y_virtual pointer_x_global pointer_y_global
+	wm geometry $tooltip +[expr $pointer_x_global+15]+[expr $pointer_y_global-2]
+	$tooltip.label configure -text [concat x: $x\ny: $y]
+	set pointer_x_virtual $x
+	set pointer_y_virtual $y
+}
+
 # begin hack to hide hidden files/folder in tk browser on unix ----------
 if {$pd_nt == 0} {
     # load the dialog once, otherwise setting the vars will not work
@@ -164,8 +365,10 @@ if {$pd_nt == 0} {
 }
 # end hidden files/folder hack ------------------
 
-# Tearoff is set to true by default:
+# Tearoff is set to false by default:
 set pd_tearoff 0
+# Put menu tearoff is set to true by default:
+set put_tearoff 1
 # turn off tearoff menus globally
 #option add *tearOff 0
 
@@ -179,7 +382,7 @@ set pd_array_listview_page(0) 0
 # color scheme
 set canvas_fill "white"
 set text_color "#000"
-set select_color "#00f"
+set select_color "#e87216"
 set dash_outline "#f00"
 set dash_fill "#f7f7f7"
 set box_outline "#ccc"
@@ -195,6 +398,10 @@ set msg_cord "#565"
 set msg_nlet "white"
 set mixed_nlet "#88aaff"
 
+#nlet highlighting stuff
+set select_nlet_color $select_color
+set highlight_width 3
+
 if {$pd_nt == 1} {
     global pd_guidir
     set pd_gui2 [string range $argv0 0 [expr [string last \\ $argv0 ] - 1]]
@@ -224,8 +431,8 @@ if {$pd_nt == 2} {
         global pd_macready pd_macdropped
         foreach file $args {
             if {$pd_macready != 0} {
-                . configure -cursor watch
-                .printout.text configure -cursor watch
+                pd [concat pd open [pdtk_enquote [file tail $file]] \
+                        [pdtk_enquote  [file dirname $file]] \;]
                 menu_doc_open [file dirname $file] [file tail $file]
             } else {
                 set pd_macdropped $args
@@ -250,7 +457,7 @@ if {$pd_nt == 0} {
     }
 }
 
-set pd_deffont {courier 12 bold}
+set pd_deffont {courier 10}
 
 set help_top_directory $pd_guidir/doc
 
@@ -286,22 +493,30 @@ switch $pd_nt {
 ################## set up main window #########################
 # the menus are instantiated here for the main window
 # for the patch windows, they are created by pdtk_canvas_new
-menu .mbar
 
-menu .mbar.file -tearoff $pd_tearoff
+#ttk error button customizations
+ttk::style configure IOErrorOn.TButton -background "#dd2222"
+ttk::style map IOErrorOn.TButton -background [list active "#ff2222"] \
+	-foreground [list disabled black]
+ttk::style configure IOErrorOff.TButton -background lightgrey
+ttk::style map IOErrorOff.TButton -background [list active $colors(-frame)]
+
+match_linux_wm [list menu .mbar -relief flat]
+match_linux_wm [list menu .mbar.file -tearoff $pd_tearoff]
 .mbar add cascade -label File -menu .mbar.file
-menu .mbar.edit -tearoff $pd_tearoff
+match_linux_wm [list menu .mbar.edit -tearoff $pd_tearoff]
 .mbar add cascade -label Edit -menu .mbar.edit
-menu .mbar.put -tearoff $pd_tearoff
+match_linux_wm [list menu .mbar.put -tearoff $pd_tearoff]
 .mbar add cascade -label Put -menu .mbar.put
-menu .mbar.find -tearoff $pd_tearoff
-.mbar add cascade -label Find -menu .mbar.find
-menu .mbar.windows -postcommand [concat pdtk_fixwindowmenu] -tearoff $pd_tearoff
-menu .mbar.audio -tearoff $pd_tearoff
+#match_linux_wm [list menu .mbar.find -tearoff $put_tearoff]
+#.mbar add cascade -label Find -menu .mbar.find
+match_linux_wm [list menu .mbar.windows -postcommand [concat pdtk_fixwindowmenu] \
+	-tearoff $pd_tearoff]
+match_linux_wm [list menu .mbar.audio -tearoff $pd_tearoff]
 if {$pd_nt != 2} {
     .mbar add cascade -label "Windows" -menu .mbar.windows
     .mbar add cascade -label "Media" -menu .mbar.audio
-    menu .mbar.help -tearoff $pd_tearoff
+    match_linux_wm [list menu .mbar.help -tearoff $pd_tearoff]
     .mbar add cascade -label "Help" -menu .mbar.help
 } else {
     menu .mbar.apple -tearoff 0
@@ -309,7 +524,7 @@ if {$pd_nt != 2} {
     # arrange menus according to Apple HIG
     .mbar add cascade -label "Media" -menu .mbar.audio
     .mbar add cascade -label "Window" -menu .mbar.windows
-    menu .mbar.help -tearoff $pd_tearoff
+    match_linux_wm [list menu .mbar.help -tearoff $pd_tearoff]
     .mbar add cascade -label "Help" -menu .mbar.help
 }
 
@@ -325,11 +540,16 @@ if {$pd_nt == 1} {
 
 proc showhide_printouttext {state} {
     if {$state} {
-        . configure -width 587 -height 458
         pack .printout -side bottom -fill both -expand 1
+		pack .controls.clr_console -pady 30
+	#wm resizable . 1 1
+	#wm minsize . 460 194
     } else {
-        . configure -width 390 -height 90
         pack forget .printout
+		pack forget .controls.clr_console
+	#wm minsize . 0 0
+	#wm geometry . 355x75
+	#wm resizable . 0 0
     }
 }
 
@@ -339,64 +559,101 @@ set ctrls_inlevel 0
 set ctrls_outlevel 0
 set show_text_window 0
 
-# tmp kludge to fix small fonts on windows, irrelevant in 0.43/gui-rewrite
-if {$pd_nt == 1} {
-    frame .controls -class PdWindow
+match_linux_wm [list frame .controls]
+if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
+	ttk::separator .eyecandy
+	pack .eyecandy .controls -fill x -expand 0
 } else {
-    frame .controls
+	pack .controls -fill x -expand 1
 }
-pack .controls -side top -fill x
-frame .controls.switches
-checkbutton .controls.switches.audiobutton -text {compute audio} \
+match_linux_wm [list frame .controls.switches]
+match_linux_wm [list checkbutton .controls.switches.audiobutton -text {compute audio  } \
     -variable ctrls_audio_on \
-    -command {pd [concat pd dsp $ctrls_audio_on \;]}
+    -command {pd [concat pd dsp $ctrls_audio_on \;]}]
 
-checkbutton .controls.switches.meterbutton -text {peak meters} \
+match_linux_wm [list checkbutton .controls.switches.meterbutton -text {peak meters} \
     -variable ctrls_meter_on \
-    -command {pd [concat pd meters $ctrls_meter_on \;]}
+    -command {pd [concat pd meters $ctrls_meter_on \;]}]
 
-checkbutton .controls.switches.console -text "console" \
+match_linux_wm [list checkbutton .controls.switches.console -text "console" \
     -variable show_console \
-    -command {showhide_printouttext $show_console}
-# the console is open by default
-.controls.switches.console select  
+    -command {showhide_printouttext $show_console}]
 
 pack .controls.switches.audiobutton .controls.switches.meterbutton \
     .controls.switches.console -side top -anchor w
 
-frame .controls.inout
-frame .controls.inout.in
-label .controls.inout.in.label -text IN
-entry .controls.inout.in.level -textvariable ctrls_inlevel -width 3
-button .controls.inout.in.clip -text {CLIP} -state disabled
+match_linux_wm [list frame .controls.inout]
+match_linux_wm [list frame .controls.inout.in]
+match_linux_wm [list label .controls.inout.in.label -text IN]
+entry .controls.inout.in.level -textvariable ctrls_inlevel -width 3 \
+	-highlightthickness 0 -takefocus 0 -state readonly -readonlybackground white
+if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
+	match_linux_wm [list button .controls.inout.in.clip \
+		-text {CLIP} -state disabled -style IOErrorOff.TButton -width 4]
+} else {
+	button .controls.inout.in.clip -text {CLIP} -state disabled
+}
+
+match_linux_wm [list frame .controls.inout.in.spacer]
+
 pack .controls.inout.in.label .controls.inout.in.level \
-    .controls.inout.in.clip -side top -pady 2
+    .controls.inout.in.clip .controls.inout.in.spacer -side top -pady 1
+
+match_linux_wm [list frame .controls.inout.out]
+match_linux_wm [list label .controls.inout.out.label -text OUT]
+entry .controls.inout.out.level -textvariable ctrls_outlevel -width 3 \
+	 -highlightthickness 0 -takefocus 0 -state readonly -readonlybackground white
+if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
+	match_linux_wm [list button .controls.inout.out.clip \
+		-text {CLIP} -state disabled -style IOErrorOff.TButton -width 4]
+} else {
+	button .controls.inout.out.clip -text {CLIP} -state disabled
+}
+
+match_linux_wm [list frame .controls.inout.out.spacer]
 
-frame .controls.inout.out
-label .controls.inout.out.label -text OUT
-entry .controls.inout.out.level -textvariable ctrls_outlevel -width 3
-button .controls.inout.out.clip -text {CLIP} -state disabled
 pack .controls.inout.out.label .controls.inout.out.level \
-    .controls.inout.out.clip -side top -pady 2
+    .controls.inout.out.clip .controls.inout.out.spacer -side top -pady 1
+
+if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
+	match_linux_wm [list ttk::button .controls.dio -text "\nIO Errors\n" \
+		-command { if {![info exists show_console] || $show_console == 0} \
+		{ menu_toggle_console; }; \
+		pd [concat pd audiostatus \;]} \
+		-width 8 -style IOErrorOff.TButton]
+} else {
+	button .controls.dio -text "DIO\nerrors" \
+		-command { if {![info exists show_console] || $show_console == 0} \ 
+		{ .controls.switches.console invoke; }; \
+		pd [concat pd audiostatus \;]}
+}
 
-button .controls.dio -text "DIO\nerrors" \
-    -command {pd [concat pd audiostatus \;]}
+match_linux_wm [list button .controls.clr_console -text "Clear Console" \
+	-command {.printout.text delete 0.0 end}]
 
 pack .controls.inout.in .controls.inout.out -side left -padx 6
 pack .controls.inout -side left -padx 14
 pack .controls.switches -side right
 pack .controls.dio -side right -padx 20
 
+if {[info exists show_console] && $show_console == 1} {
+	pack .controls.clr_console -pady 30
+}
 
-frame .printout
-text .printout.text -relief raised -bd 2 -font console_font \
-    -yscrollcommand ".printout.scroll set" -width 80
+match_linux_wm [list frame .printout]
+text .printout.text -relief sunken -bd 1 -font console_font \
+    -yscrollcommand ".printout.scroll set" -width 70 -highlightthickness 0 -takefocus 0
 # .printout.text insert end "\n\n\n\n\n\n\n\n\n\n"
-scrollbar .printout.scroll -command ".printout.text yview"
+match_linux_wm [list scrollbar .printout.scroll -command ".printout.text yview"]
 pack .printout.scroll -side right -fill y
 pack .printout.text -side left -fill both -expand 1
 pack .printout -side bottom -fill both -expand 1
 
+# the console is open by default
+#.controls.switches.console select
+# in the case console should be turned off by default
+pack forget .printout
+
 proc pdtk_post {stuff} {
     .printout.text insert end $stuff
     .printout.text yview end-2char
@@ -419,14 +676,10 @@ proc pdtk_panelkeybindings {id panelname} {
 pdtk_standardkeybindings .
 # hacks to add standard key bindings to the Pd window
 bind . <$ctrl_key-Key-a> {.printout.text tag add sel 1.0 end}
-bind . <$ctrl_key-Key-x> {tk_textCut .printout.text}
-bind . <$ctrl_key-Key-c> {tk_textCopy .printout.text}
-bind . <$ctrl_key-Key-v> {tk_textPaste .printout.text}
-# beep if someone presses these keys in the Pd window
-bind . <$ctrl_key-Key-w> {bell}
-bind . <$ctrl_key-Key-e> {bell}
-bind . <$ctrl_key-Key-s> {bell}
-bind . <$ctrl_key-Shift-Key-S> {bell}
+#bind . <$ctrl_key-Key-x> {tk_textCut .printout.text}
+#bind . <$ctrl_key-Key-c> {tk_textCopy .printout.text}
+#bind . <$ctrl_key-Key-v> {tk_textPaste .printout.text}
+bind . <$ctrl_key-Key-w> {menu_quit}
 # kludge to add window control bindings to the Pd Window
 if {$pd_nt == 2} {
 	bind . <Mod1-quoteleft>  {menu_raisenextwindow}
@@ -436,12 +689,11 @@ if {$pd_nt == 2} {
 }
 
 
-wm title . "Pd-extended"
+wm title . "Pd"
 # initial location of Pd window (+x+y)
-wm geometry . +20+70
-wm minsize . 390 90
-. configure -menu .mbar -width 587 -height 458
-
+wm geometry . +10+35
+. configure -menu .mbar -width 200 -height 150
+if { [info tclversion] >= 8.5 && $pd_nt == 0 } { wm resizable . 0 0 }
 # Intercept closing the main pd window: MP 20060413:
 wm protocol . WM_DELETE_WINDOW menu_quit
 
@@ -506,7 +758,14 @@ proc pdtk_check {canvas x message default} {
         set answer [tk_messageBox -message $x -type yesno -default $default \
             -parent $canvas -icon question]
     }
-    if {! [string compare $answer yes]}  {pd $message}
+    if {! [string compare $answer yes]}  {
+		pd $message
+		if {$canvas eq "."} {
+			focus $canvassegfault due to the way iemgui's implementation of universal color
+		} else {
+			menu_close $canvas
+		}
+	}
 }
 
 ##### ask user Save? Discard? Cancel?, and if so, send a message on to Pd ######
@@ -514,21 +773,20 @@ proc pdtk_canvas_menuclose {window reply} {
 	global pd_nt
 	raise $window
 	set filename [wm title $window]
-	set message [format {Do you want to save the changes you made in "%s"?} $filename]
+	set message [format {Do you wish to save the changes you made in "%s"?} $filename]
 	set answer [tk_messageBox -message $message -type yesnocancel -default "yes" \
 					-parent $window -icon question]
 	switch -- $answer {
-		yes { 
+		yes {
 			pd [concat $window menusave \;]
-                        if {[regexp {Untitled-[0-9]+} $filename]} {
-                        # wait until pdtk_canvas_saveas finishes and writes to
-                        # this var, otherwise the close command will be sent
-                        # immediately and the file won't get saved
-                            vwait ::untitled_directory
-                        }
+			#when quitting the application sometimes the save menu fails to show up
+			#after 250 pd $reply
+			#pd $reply
+		}
+		no {
+			pd [concat $window dirty 0 \;]
 			pd $reply
 		}
-		no {pd $reply}
 		cancel {}
 	}
 }
@@ -551,7 +809,7 @@ proc pdtk_fixwindowmenu {} {
 	.mbar.windows add separator
     .mbar.windows add command -label {parent window} -state disabled
     .mbar.windows add command -label {Pd window} -command menu_raise_console \
-		-accelerator [accel_munge "Ctrl+r"] -state disabled
+		-accelerator [accel_munge "Ctrl+;"] -state disabled
 	.mbar.windows add separator
     foreach i $menu_windowlist {
         .mbar.windows add command -label [lindex $i 0] \
@@ -634,8 +892,6 @@ proc open_file {filename} {
 		}
 	}
     if {[regexp -nocase -- "\.(pd|pat|mxt)$" $basename]} {
-        . configure -cursor watch
-        .printout.text configure -cursor watch
         pd "pd open [pdtk_enquote $basename] [pdtk_enquote $directory] ;"
         set pd_opendir $directory
     }
@@ -651,19 +907,28 @@ catch {
 ################## the "Message" menu command #########################
 proc menu_send {} {
     global pd_nt ctrl_key
-    destroy .sendpanel
-    toplevel .sendpanel -class DialogWindow
-    pdtk_standardkeybindings .sendpanel
-    entry .sendpanel.entry -textvariable send_textvariable
-    pack .sendpanel.entry -side bottom -fill both -ipadx 100
-    .sendpanel.entry select from 0
-    .sendpanel.entry select adjust end
-    bind .sendpanel <$ctrl_key-Key-w> {destroy .sendpanel}
-    bind .sendpanel <KeyPress-Escape> {destroy .sendpanel}
-    bind .sendpanel.entry <KeyPress-Return> {
-        pd [concat $send_textvariable \;]
-    }
-    focus .sendpanel.entry
+    if { [winfo exists .sendpanel.entry] } {
+        raise .sendpanel
+    } else {
+		toplevel .sendpanel
+		wm title .sendpanel {Send Message to Pd}
+		wm resizable .sendpanel 0 0
+		match_linux_wm [list .sendpanel configure]
+		pdtk_standardkeybindings .sendpanel
+		match_linux_wm [list entry .sendpanel.entry \
+			-textvariable send_textvariable]
+		pack .sendpanel.entry -side bottom -fill both -ipadx 100 -padx 3 -pady 5
+		if { [info tclversion] < 8.5 } {
+			.sendpanel.entry select from 0
+			.sendpanel.entry select adjust end
+		}
+		bind .sendpanel <$ctrl_key-Key-w> {destroy .sendpanel}
+		bind .sendpanel <KeyPress-Escape> {destroy .sendpanel}
+		bind .sendpanel.entry <KeyPress-Return> {
+		    pd [concat $send_textvariable \;]
+		}
+		focus .sendpanel.entry
+	}
 }
 
 
@@ -703,7 +968,7 @@ proc menu_raise_console {} {
 	}
 }
 
-proc menu_toggle_console {} {.controls.switches.console invoke}
+proc menu_toggle_console {} { .controls.switches.console invoke }
 
 proc menu_clear_console {} {.printout.text delete 0.0 end}
 
@@ -728,24 +993,29 @@ proc menu_opentext {filename} {
     global pd_guidir
     global pd_myversion
 	global ctrl_key
-    set name [format ".help%d" $doc_number]
-    toplevel $name
-    text $name.text -relief raised -bd 2 -font text_font \
-        -yscrollcommand "$name.scroll set" -background white
-    scrollbar $name.scroll -command "$name.text yview"
-    pack $name.scroll -side right -fill y
-    pack $name.text -side left -fill both -expand 1
-    bind $name <$ctrl_key-Key-w> [concat destroy $name]
-    
-    set f [open $filename]
-    while {![eof $f]} {
-        set bigstring [read $f 1000]
-        regsub -all PD_BASEDIR $bigstring $pd_guidir bigstring2
-        regsub -all PD_VERSION $bigstring2 $pd_myversion bigstring3
-        $name.text insert end $bigstring3
-    }
-    close $f
-    set doc_number [expr $doc_number + 1] 
+    if { [winfo exists .about.text] } {
+        raise .about
+    } else {
+		destroy .about
+		toplevel .about
+		wm title .about "About Pd"
+		wm geometry .about 550x480
+		match_linux_wm [list text .about.text -relief sunken -bd 1 -font text_font \
+		    -yscrollcommand ".about.scroll set" -highlightthickness 0 -takefocus 0]
+		match_linux_wm [list scrollbar .about.scroll -command ".about.text yview"]
+		pack .about.scroll -side right -fill y
+		pack .about.text -side left -fill both -expand 1
+		bind .about <$ctrl_key-Key-w> [concat destroy .about set doc_number [expr $doc_number - 1]]
+		
+		set f [open $filename]
+		while {![eof $f]} {
+		    set bigstring [read $f 1000]
+		    regsub -all PD_BASEDIR $bigstring $pd_guidir bigstring2
+		    regsub -all PD_VERSION $bigstring2 $pd_myversion bigstring3
+		    .about.text insert end $bigstring3
+		}
+		close $f
+	}
 }
 
 # open HTML docs from the menu using the OS-default HTML viewer
@@ -758,11 +1028,13 @@ proc menu_openhtml {filename} {
                   galeon konqueror netscape lynx } {
                       set browser [lindex [auto_execok $candidate] 0]
                       if {[string length $browser]} {
+                          puts stderr [format "%s '%s'" $browser $filename]
                           exec -- sh -c [format "%s '%s'" $browser $filename] &
                           break
                       }
                   }
     } elseif {$pd_nt == 2} {
+        puts stderr [format "open '%s'" $filename]
         exec sh -c [format "open '%s'" $filename]
     } else {
         exec rundll32 url.dll,FileProtocolHandler \
@@ -814,13 +1086,14 @@ proc menu_addstd {mbar} {
         -command {menu_audio 1} 
     $mbar.audio add command -label {audio OFF} -accelerator [accel_munge "Ctrl+."] \
         -command {menu_audio 0} 
-    $mbar.audio add separator
+	$mbar.audio add separator
     for {set x 0} {$x<[llength $pd_apilist]} {incr x} {
         $mbar.audio add radiobutton -label [lindex [lindex $pd_apilist $x] 0] \
             -command {menu_audio 0} -variable pd_whichapi \
             -value [lindex [lindex $pd_apilist $x] 1]\
             -command {pd [concat pd audio-setapi $pd_whichapi \;]}
     }
+	$mbar.audio add separator
     for {set x 0} {$x<[llength $pd_midiapilist]} {incr x} {
         $mbar.audio add radiobutton -label [lindex [lindex $pd_midiapilist $x] 0] \
             -command {menu_midi 0} -variable pd_whichmidiapi \
@@ -828,13 +1101,13 @@ proc menu_addstd {mbar} {
             -command {pd [concat pd midi-setapi $pd_whichmidiapi \;]}
     }
     if {$pd_nt != 2} {
-        $mbar.audio add separator
+		$mbar.audio add separator
         $mbar.audio add command -label {Audio settings...} \
             -command {pd pd audio-properties \;}
         $mbar.audio add command -label {MIDI settings...} \
             -command {pd pd midi-properties \;}
     }
-    $mbar.audio add separator
+	$mbar.audio add separator    
     $mbar.audio add command -label {Test Audio and MIDI} \
         -command {menu_doc_open doc/7.stuff/tools testtone.pd} 
     $mbar.audio add command -label {Load Meter} \
@@ -849,7 +1122,7 @@ proc menu_addstd {mbar} {
     # See SPECIAL MENUS IN MENUBARS http://www.tcl.tk/man/tcl8.4/TkCmd/menu.htm
     if {$pd_nt == 2} {
         $mbar.apple add command -label "About Pd..." -command \
-            {menu_doc_open doc/5.reference about.pd} 
+            {menu_doc_open doc/1.manual 1.introduction.txt} 
         menu $mbar.apple.preferences -tearoff 0
         $mbar.apple add cascade -label "Preferences" -menu $mbar.apple.preferences
         $mbar.apple.preferences add command -label "Path..." \
@@ -866,11 +1139,11 @@ proc menu_addstd {mbar} {
     # the "Help" menu
     if {$pd_nt != 2} {
         $mbar.help add command -label {About Pd} \
-            -command {menu_doc_open doc/5.reference about.pd}
+            -command {menu_doc_open doc/1.manual 1.introduction.txt} 
     }
-    $mbar.help add command -label {Html ...} \
+    $mbar.help add command -label {Html} \
         -command {menu_doc_open doc/1.manual index.htm} 
-    $mbar.help add command -label {Browser ...} \
+    $mbar.help add command -label {Browser} \
         -accelerator [accel_munge "Ctrl+b"] \
         -command {::helpbrowser::open_helpbrowser}
     $mbar.help add separator
@@ -956,6 +1229,17 @@ if {$pd_nt != 2} {
 .mbar.edit add command -label {Reselect} \
         -accelerator "Ctrl+Enter" -state disabled
 .mbar.edit add separator
+.mbar.edit add command -label {Tidy Up} -accelerator [accel_munge "Ctrl+y"] -state disabled
+
+.mbar.edit add command -label {Bring To Front} \
+        -accelerator [accel_munge "Ctrl+Up"] \
+		-state disabled
+
+.mbar.edit add command -label {Send To Back} \
+        -accelerator [accel_munge "Ctrl+Down"] \
+		-state disabled
+
+.mbar.edit add separator
 if {$pd_nt == 2} { # no key command for Mac OS X
 	.mbar.edit add command -label {Text Editor} -state disabled
 } else {
@@ -963,7 +1247,14 @@ if {$pd_nt == 2} { # no key command for Mac OS X
 	-state disabled
 }
 .mbar.edit add command -label Font -state disabled
-.mbar.edit add command -label {Tidy Up} -state disabled
+
+.mbar.edit add checkbutton -label {Cord Inspector} \
+    -indicatoron false -selectcolor black \
+    -state disabled \
+    -accelerator [accel_munge "Ctrl+r"]
+
+.mbar.edit add separator
+
 .mbar.edit add command -label "Toggle console" \
 	-accelerator [accel_munge "Shift+Ctrl+r"] -command menu_toggle_console
 .mbar.edit add command -label "Clear console" \
@@ -982,11 +1273,11 @@ if {$pd_nt == 2} { # no key command for Mac OS X
 
 #################### the "Find" menu for the Pd window ##############
 
-.mbar.find add command -label Find -accelerator [accel_munge "Ctrl+f"] \
-    -state disabled
-.mbar.find add command -label {Find Again} -accelerator [accel_munge "Ctrl+g"] \
-    -state disabled
-.mbar.find add command -label {Find last error} -command {menu_finderror} 
+#.mbar.find add command -label {Find...} -accelerator [accel_munge "Ctrl+f"] \
+#    -state disabled
+#.mbar.find add command -label {Find Again} -accelerator [accel_munge "Ctrl+g"] \
+#    -state disabled
+#.mbar.find add command -label {Find last error} -command {menu_finderror} 
 
 
 #######  functions for embedding a patch into a standalone Mac OS X app #######
@@ -1011,8 +1302,8 @@ proc makeapp_createapp {appdir} {
 	}
 	file mkdir $appdir
 	file copy -- $pdapp_contents "$appdir/"
-	file rename -force -- $appdir/Contents/org.puredata.pdextended.default.plist \
-		$appdir/Contents/org.puredata.pdextended.plist
+	file rename -force -- $appdir/Contents/org.puredata.pdl2ork.default.plist \
+		$appdir/Contents/org.puredata.pdl2ork.plist
 }
 
 proc makeapp_makeinfoplist {appdir} {
@@ -1038,21 +1329,14 @@ proc makeapp_makeinfoplist {appdir} {
 }
 
 proc makeapp_copycurrentpatch {appdir patch patchname isdir} {
-	set extradir "$appdir/Contents/Resources/extra"
-	file attributes $extradir -permissions u+w
-	file mkdir "$extradir/app-auto-load"
 	if {$isdir} {
-		pdtk_post [format "Copying:%s\n  -->\t$extradir/\n" \
+		pdtk_post [format "Copying:%s\n  -->\t$appdir/Contents/Resources/extra/\n" \
 					   [file dirname $patch]]
-		set patchdir [file normalize [file dirname $patch]]
-		foreach file [glob -directory "$patchdir" -- * .*] {
-			if {"$file"!="$appdir" && "$file"!="$patchdir/." && "$file"!="$patchdir/.."} {
-				file copy -- $file "$extradir/app-auto-load/"
-			}
-		}
+		file copy -- [file dirname $patch] "$appdir/Contents/Resources/extra/"
 	} else {
-		set embedded_patch "$extradir/app-auto-load/$patchname.pd"
+		set embedded_patch "$appdir/Contents/Resources/extra/$patchname/$patchname.pd"
 		pdtk_post "Copying:$patch\n  -->\t$embedded_patch\n"
+		file mkdir "$appdir/Contents/Resources/extra/$patchname"
 		file copy -- $patch $embedded_patch
 	}
 }
@@ -1067,15 +1351,16 @@ proc makeapp_getpatchname {top_window} {
 }
 
 proc makeapp_embedprefs {appdir patch_to_open} {
-	pdtk_post "Setting up $appdir/Contents/org.puredata.pdextended.plist\n"
-	set plist [open "$appdir/Contents/org.puredata.pdextended.plist" r]
+	pdtk_post "Setting up $appdir/Contents/org.puredata.pdl2ork.plist\n"
+	set plist [open "$appdir/Contents/org.puredata.pdl2ork.plist" r]
 	set new_plist [read $plist]
 	close $plist
 	regsub -- {flags</key>.*?<string>.*?<} $new_plist \
 		"flags</key>\n\t<string>-open hcs/embed.pd -open $patch_to_open<" new_plist
-	set plist [open "$appdir/Contents/org.puredata.pdextended.plist" w]
+	set plist [open "$appdir/Contents/org.puredata.pdl2ork.plist" w]
 	puts $plist $new_plist
 	close $plist		
+
 }
 
 proc makeapp_busypanel {appdir} {
@@ -1118,7 +1403,7 @@ proc menu_makeapp {isdir} {
 			.makeapp.label configure -text "Copying current patch..."
 			makeapp_copycurrentpatch $appdir $patch $patchname $isdir
 			.makeapp.label configure -text "Setting embedded preferences..."
-			makeapp_embedprefs $appdir "app-auto-load/$patchname.pd"
+			makeapp_embedprefs $appdir "$patchname/$patchname.pd"
 			pdtk_post "$appdir is complete!\n"
 			destroy .makeapp
 		}
@@ -1126,22 +1411,16 @@ proc menu_makeapp {isdir} {
 }
 
 proc menu_save {name} {
-    if {$name eq ""} {bell;return}
-    if {[winfo toplevel $name] eq "."} {bell;return}
     pdtk_canvas_checkgeometry $name
     pd [concat $name menusave \;]
 }
 
 proc menu_saveas {name} {
-    if {$name eq ""} {bell;return}
-    if {[winfo toplevel $name] eq "."} {bell;return}
     pdtk_canvas_checkgeometry $name
     pd [concat $name menusaveas \;]
 }
 
 proc menu_print {name} {
-    if {$name eq ""} {bell;return}
-    if {[winfo toplevel $name] eq "."} {bell;return}
     set filename [tk_getSaveFile -initialfile pd.ps \
                       -defaultextension .ps \
                       -filetypes { {{postscript} {.ps}} }]
@@ -1152,8 +1431,14 @@ proc menu_print {name} {
 }
 
 proc menu_close {name} {
-    pdtk_canvas_checkgeometry $name
-    pd [concat $name menuclose 0 \;]
+	if {$name == ".texteditor.text"} { 
+		set topname [string trimright $name .text]
+		texteditor_send $name
+		destroy $topname   
+	} else {
+		pdtk_canvas_checkgeometry $name
+    	pd [concat $name menuclose 0 \;]
+	}
 }
 
 proc menu_really_close {name} {
@@ -1180,23 +1465,57 @@ proc menu_redo {name} {
 }
 
 proc menu_cut {name} {
-    pd [concat $name cut \;]
+	global copytexttocanvas
+	if {![string match .gfxstub* $name] && ![string match .printout* $name] && ![string match *entry $name]} {
+		pd [concat $name cut \;]
+		pdtk_canvas_getscroll $name.c
+		set copytexttocanvas 0
+		clipboard clear
+	} else {
+		set copytexttocanvas 1
+	}
 }
 
 proc menu_copy {name} {
-    pd [concat $name copy \;]
+	global copytexttocanvas
+	if {![string match .gfxstub* $name] && ![string match .printout* $name] && ![string match *entry $name]} {
+	    pd [concat $name copy \;]
+		set copytexttocanvas 0
+		clipboard clear
+	} else {
+		set copytexttocanvas 1
+	}
 }
 
 proc menu_paste {name} {
-    pd [concat $name paste \;]
+	global copytexttocanvas
+	#pdtk_pastetext
+	#pdtk_post "pasting..."
+	if {![string match .gfxstub* $name] && ![string match .printout* $name] && ![string match *entry $name]} {
+		if {$copytexttocanvas} {
+			pdtk_pastetext
+		} else {
+			pd [concat $name paste \;]
+			pdtk_canvas_getscroll $name.c
+		}
+	}
 }
 
+bind . <$ctrl_key-Key-x> {menu_cut .printout.text}
+bind . <$ctrl_key-Key-c> {menu_copy .printout.text}
+bind . <$ctrl_key-Key-v> {menu_paste .printout.text}
+
 proc menu_duplicate {name} {
     pd [concat $name duplicate \;]
+	pdtk_canvas_getscroll $name.c
 }
 
 proc menu_selectall {name} {
-    pd [concat $name selectall \;]
+	if {![string match .gfxstub* $name] && ![string match *entry $name]} {
+    	pd [concat $name selectall \;]
+	} else {
+		$name selection range 0 end
+	}
 }
 
 proc menu_texteditor {name} {
@@ -1208,75 +1527,103 @@ proc menu_font {name} {
 }
 
 proc menu_tidyup {name} {
+	if {[string compare $name .c]} {
+		set name [string trimright $name .c]
+	}
     pd [concat $name tidy \;]
 }
 
+## jsarlo
+proc menu_magicglass {name} {
+    pd [concat $name magicglass 0 \;]
+}
+## end jsarlo
+
 proc menu_editmode {name} {
     pd [concat $name editmode 0 \;]
 }
 
 proc menu_object {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name obj $accel \;]
 }
 
 proc menu_message {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name msg $accel \;]
 }
 
 proc menu_floatatom {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name floatatom $accel \;]
 }
 
 proc menu_symbolatom {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name symbolatom $accel \;]
 }
 
 proc menu_comment {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name text $accel \;]
 }
 
 proc menu_graph {name} {
-    pd [concat $name graph \;]
+	pd [concat $name dirty 1 \;]
+	set xdraw [expr int([$name.c canvasx 0])]
+	set ydraw [expr int([$name.c canvasy 0])]
+    pd [concat $name graph NULL 0 0 0 0 [expr $xdraw+30] [expr $ydraw+30] 0 [expr $ydraw+30]\;]
+    #pd [concat $name graph \;]
 }
 
 proc menu_array {name} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name menuarray \;]
 }
 
 ############iemlib##################
 proc menu_bng {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name bng $accel \;]
 }
 
 proc menu_toggle {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name toggle $accel \;]
 }
 
 proc menu_numbox {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name numbox $accel \;]
 }
 
 proc menu_vslider {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name vslider $accel \;]
 }
 
 proc menu_hslider {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name hslider $accel \;]
 }
 
 proc menu_hradio {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name hradio $accel \;]
 }
 
 proc menu_vradio {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name vradio $accel \;]
 }
 
 proc menu_vumeter {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name vumeter $accel \;]
 }
 
 proc menu_mycnv {name accel} {
+	pd [concat $name dirty 1 \;]
     pd [concat $name mycnv $accel \;]
 }
 
@@ -1315,6 +1662,9 @@ proc pdtk_undomenu {name undoaction redoaction} {
     if {$name != "nobody"} {
         #    unpleasant way of avoiding a more unpleasant bug situation --atl 2002.11.25
         menu_fixeditmenu $name
+		#puts stderr UNDO-[string trimleft $name .x]
+		#set pdname [string trimleft $name .x]
+		#pd [concat $name fixgop \;]
     }
 }
 
@@ -1341,9 +1691,9 @@ proc menu_fixwindowmenu {name} {
 		$name.m.windows delete 6 end
 	} else {
 		if $pd_tearoff {
-			$name.m.windows delete 4 end
+			$name.m.windows delete 5 end
 		} else {
-			$name.m.windows delete 3 end
+			$name.m.windows delete 5 end
 		}
 	}
     foreach i $menu_windowlist {
@@ -1371,43 +1721,98 @@ proc find_cancel {name} {
 }
 
 proc menu_findobject {canvas} {
-    global find_string find_canvas find_count find_wholeword
-    
-    set name [format ".find%d" $find_count]
-    set find_count [expr $find_count + 1]
-
-    set find_canvas $canvas
-    
-    toplevel $name -class DialogWindow
-	wm geometry $name =400x125+150+100
-	wm resizable $name 0 0
-	catch {wm attributes $name -topmost 1}
-
-    pdtk_panelkeybindings $name "find"
+    global find_string
+    global find_canvas
+    global find_count
+	global pd_nt
+	global pointer_x_global pointer_y_global
 
-	entry $name.entry -width 54 -font 18 -textvariable find_string \
-		-highlightthickness 2 -highlightcolor blue -relief sunken
-    focus $name.entry
-    pack $name.entry -side top -padx 10 -pady 10
-    checkbutton $name.wholeword -variable find_wholeword \
-        -text {whole word} -anchor e
-    pack $name.wholeword -side left -padx 30
+    if { [winfo exists .find.frame.entry] } {
+        raise .find
+		wm geometry .find "+$pointer_x_global+$pointer_y_global"
+    } else {
 
-    button $name.close -text "Close" -command "find_cancel $name" -width 9
-    button $name.button -text "Find" -command "find_ok $name" -width 9 -default active
-	pack $name.button $name.close -side right -padx 10 -pady 15
+		set find_canvas $canvas
+		
+		toplevel .find
+		wm title .find "Find"
+		match_linux_wm [list .find configure]
+		#wm geometry .find =400x125+150+100
+		wm geometry .find "+$pointer_x_global+$pointer_y_global"
+		wm resizable .find 0 0
+		catch {wm attributes .find -topmost 1}
+
+		pdtk_panelkeybindings .find "find"
+
+		match_linux_wm [list frame .find.frame]
+		pack .find.frame -pady 3
+		match_linux_wm [list entry .find.frame.entry -width 30 \
+			-textvariable find_string]
+		focus .find.frame.entry
+		pack .find.frame.entry -side top -padx 3 -pady 3
+
+	    match_linux_wm [list checkbutton .find.frame.wholeword \
+			-variable find_wholeword \
+	        -text {whole word}]
+		match_linux_wm [list button .find.frame.close -text "Close" \
+			-command "find_cancel .find" -width 9]
+		match_linux_wm [list button .find.frame.button -text "Find" \
+			-command "find_ok .find" \
+			-width 9 -default active]
+		pack .find.frame.button .find.frame.close .find.frame.wholeword -side right -padx 3
+	}
 }
 
 
 ############# pdtk_canvas_new -- create a new canvas ###############
 proc pdtk_canvas_new {name width height geometry editable} {
-    global pd_tearoff
+    global pd_tearoff put_tearoff
     global pd_nt
     global tcl_version
-	global canvas_fill
+    global canvas_fill
+	global colors
+
+	#retaining window-specific preferences
+	global window_prefs
+
+    # local vars for window-specific behavior
+	# visibility of menu and scrollbars, plus canvas background
+	if {![info exists ::scroll($name)]} {
+		set ::scroll($name) 1
+	}
+	if {![info exists ::menu($name)]} {
+		set ::menu($name) 1
+	}
+	if {![info exists ::canvas_color($name)]} {
+		set ::canvas_color($name) $canvas_fill
+	}
+	if {![info exists ::topmost($name)]} {
+		set ::topmost($name) 0
+	}
+	if {![info exists ::resize($name)]} {
+		set ::resize($name) 1
+	}
+	if {![info exists ::xscrollable($name)]} {
+		set ::xscrollable($name) 0
+	}
+	if {![info exists ::yscrollable($name)]} {
+		set ::yscrollable($name) 0
+	}
+	if {![info exists ::update_tick($name)]} {
+		set ::update_tick($name) 0
+	}
+
+	if {$::menu($name) == 1} {
+    	toplevel $name -menu $name.m
+	} else {
+		toplevel $name -menu ""
+	}
+
+	# initialize variable to reflect that this window has been open
+	if {![info exists ::loaded($name)]} {
+		set ::loaded($name) 1
+	}
 
-    toplevel $name -menu $name.m
-    wm group $name .
     # slide offscreen windows into view
     if {$tcl_version >= 8.4} {
         set geometry [split $geometry +]
@@ -1427,18 +1832,36 @@ proc pdtk_canvas_new {name width height geometry editable} {
         set geometry [join $geometry +] 
     }
     wm geometry $name $geometry
-    canvas $name.c -width $width -height $height -background $canvas_fill \
-		-highlightthickness 0 \
+
+	#apply window properties
+	wm resizable $name $::resize($name) $::resize($name)
+	wm attributes $name -topmost $::topmost($name)
+
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		if {$::menu($name) == 1} {
+			ttk::separator $name.eyecandy
+		}
+	}
+    canvas $name.c -width $width -height $height -background $::canvas_color($name) \
+		-highlightthickness 0 -bd 0 \
         -yscrollcommand "$name.scrollvert set" \
         -xscrollcommand "$name.scrollhort set" \
-        -scrollregion [concat 0 0 $width $height] 
+        -scrollregion [concat 0 0 $width $height]
+
+	pdtk_standardkeybindings $name.c
+
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		if {$::menu($name) == 1} {
+			pack $name.eyecandy $name.c -fill x -expand 0
+		}
+	}
 
-    scrollbar $name.scrollvert -command "$name.c yview"
-    scrollbar $name.scrollhort -command "$name.c xview" \
-        -orient horizontal
+    match_linux_wm [list scrollbar $name.scrollvert -command "$name.c yview"]
+    match_linux_wm [list scrollbar $name.scrollhort -command "$name.c xview" \
+        -orient horizontal]
 
-#    pack $name.scrollhort -side bottom -fill x
-#    pack $name.scrollvert -side right -fill y
+	#pack $name.scrollhort -side bottom -fill x
+	#pack $name.scrollvert -side right -fill y
     pack $name.c -side left -expand 1 -fill both
     wm minsize $name 50 20
     wm geometry $name $geometry
@@ -1447,8 +1870,8 @@ proc pdtk_canvas_new {name width height geometry editable} {
     # The menus are instantiated here for the patch windows.
     # For the main window, they are created on load, at the 
     # top of this file.
-    menu $name.m
-    menu $name.m.file -tearoff $pd_tearoff
+    match_linux_wm [list menu $name.m -relief flat]
+    match_linux_wm [list menu $name.m.file -tearoff $pd_tearoff]
     $name.m add cascade -label File -menu $name.m.file
 
     $name.m.file add command -label New -command {menu_new} \
@@ -1499,7 +1922,7 @@ proc pdtk_canvas_new {name width height geometry editable} {
 	}
 
     # the edit menu
-    menu $name.m.edit -postcommand [concat menu_fixeditmenu $name] -tearoff $pd_tearoff
+    match_linux_wm [list menu $name.m.edit -postcommand [concat menu_fixeditmenu $name] -tearoff $pd_tearoff]
     $name.m add cascade -label Edit -menu $name.m.edit
     
     $name.m.edit add command -label Undo -command [concat menu_undo $name] \
@@ -1533,6 +1956,21 @@ proc pdtk_canvas_new {name width height geometry editable} {
         -accelerator "Ctrl+Enter"
 
     $name.m.edit add separator
+
+    $name.m.edit add command -label {Tidy Up} \
+		-command [concat menu_tidyup $name] \
+        -accelerator [accel_munge "Ctrl+y"]
+
+    $name.m.edit add command -label {Bring To Front} \
+		-command [concat popup_action $name 3] \
+        -accelerator [accel_munge "Ctrl+Up"]
+
+    $name.m.edit add command -label {Send To Back} \
+		-command [concat popup_action $name 4] \
+        -accelerator [accel_munge "Ctrl+Down"]
+
+    $name.m.edit add separator
+
 	if {$pd_nt == 2} { # no key command on Mac OS X, conflicts with standard
 		$name.m.edit add command -label {Text Editor} \
 			-command [concat menu_texteditor $name]
@@ -1545,8 +1983,17 @@ proc pdtk_canvas_new {name width height geometry editable} {
     $name.m.edit add command -label Font \
         -command [concat menu_font $name] 
 
-    $name.m.edit add command -label {Tidy Up} \
-        -command [concat menu_tidyup $name]
+## jsarlo
+    $name.m.edit add checkbutton -label "Cord Inspector" \
+        -indicatoron false -selectcolor black \
+        -command [concat menu_magicglass $name] \
+        -accelerator [accel_munge "Ctrl+r"]
+
+    #if { $editable == 0 } {
+    #       $name.m.edit entryconfigure "Cord Inspector" -indicatoron false }
+  
+    $name.m.edit add separator
+## end jsarlo
 
     $name.m.edit add command -label "Toggle console" \
         -accelerator [accel_munge "Shift+Ctrl+r"] \
@@ -1575,20 +2022,22 @@ proc pdtk_canvas_new {name width height geometry editable} {
     # if widget is selected or not.
 
     $name.m.edit add checkbutton -label "Edit mode" \
-        -indicatoron true -selectcolor grey85 \
+        -indicatoron false -selectcolor black \
         -command [concat menu_editmode $name] \
-        -accelerator [accel_munge "Ctrl+e"]     
+        -accelerator [accel_munge "Ctrl+e"]
 
-    if { $editable == 0 } {
-        $name.m.edit entryconfigure "Edit mode" -indicatoron false 
-    }
+    $name.m.edit entryconfigure "Edit mode" -background "#7dd37d"
+
+    #if { $editable == 0 } {
+    #    $name.m.edit entryconfigure "Edit mode" -indicatoron false 
+    #}
 
     
     ############iemlib##################
 
 
     # the put menu
-    menu $name.m.put -tearoff $pd_tearoff
+    match_linux_wm [list menu $name.m.put -tearoff $put_tearoff]
     $name.m add cascade -label Put -menu $name.m.put
 
     $name.m.put add command -label Object \
@@ -1667,21 +2116,21 @@ proc pdtk_canvas_new {name width height geometry editable} {
     # handling needs to be dealt with, including this line in g_canvas.c:
     #         sys_vgui(".mbar.find delete %d\n", i);
     # <hans@at.or.at>
-    menu $name.m.find -tearoff $pd_tearoff
-    $name.m add cascade -label Find -menu $name.m.find
-
-    $name.m.find add command -label {Find...} \
-        -accelerator [accel_munge "Ctrl+f"] \
-        -command [concat menu_findobject $name] 
-    $name.m.find add command -label {Find Again} \
-        -accelerator [accel_munge "Ctrl+g"] \
-        -command [concat menu_findagain $name] 
-    $name.m.find add command -label {Find last error} \
-        -command [concat menu_finderror] 
+    #match_linux_wm [list menu $name.m.find -tearoff $put_tearoff]
+    #$name.m add cascade -label Find -menu $name.m.find
+	#
+    #$name.m.find add command -label {Find...} \
+    #    -accelerator [accel_munge "Ctrl+f"] \
+    #    -command [concat menu_findobject $name] 
+    #$name.m.find add command -label {Find Again} \
+    #    -accelerator [accel_munge "Ctrl+g"] \
+    #    -command [concat menu_findagain $name] 
+    #$name.m.find add command -label {Find last error} \
+    #    -command [concat menu_finderror] 
     
     # the window menu
-    menu $name.m.windows -postcommand [concat menu_fixwindowmenu $name] \
-        -tearoff $pd_tearoff
+    match_linux_wm [list menu $name.m.windows -postcommand \
+		[concat menu_fixwindowmenu $name] -tearoff $pd_tearoff]
 
 	if {$pd_nt == 2} {
 		$name.m.windows add command -label {Minimize} \
@@ -1697,11 +2146,11 @@ proc pdtk_canvas_new {name width height geometry editable} {
     $name.m.windows add command -label {parent window}\
         -command [concat menu_windowparent $name] 
     $name.m.windows add command -label {Pd window} -command menu_raise_console \
-		-accelerator [accel_munge "Ctrl+r"]
+		-accelerator [accel_munge "Ctrl+;"]
     $name.m.windows add separator
 
     # the audio menu
-    menu $name.m.audio -tearoff $pd_tearoff
+    match_linux_wm [list menu $name.m.audio -tearoff $pd_tearoff]
 
     if {$pd_nt != 2} {
         $name.m add cascade -label Windows -menu $name.m.windows
@@ -1716,19 +2165,24 @@ proc pdtk_canvas_new {name width height geometry editable} {
 
     # the help menu
 
-    menu $name.m.help -tearoff $pd_tearoff
+    match_linux_wm [list menu $name.m.help -tearoff $pd_tearoff]
     $name.m add cascade -label Help -menu $name.m.help
 
     menu_addstd $name.m
 
     # the popup menu
-    menu $name.popup -tearoff false
+    match_linux_wm [list menu $name.popup -tearoff false]
     $name.popup add command -label {Properties} \
         -command [concat popup_action $name 0] 
     $name.popup add command -label {Open} \
         -command [concat popup_action $name 1] 
     $name.popup add command -label {Help} \
-        -command [concat popup_action $name 2] 
+        -command [concat popup_action $name 2]
+	#$name.popup add separator
+    #$name.popup add command -label {To Front} \
+    #    -command [concat popup_action $name 3]
+    #$name.popup add command -label {To Back} \
+    #    -command [concat popup_action $name 4]
 
     # fix menu font size on Windows with tk scaling = 1
     if {$pd_nt == 1} {
@@ -1807,6 +2261,7 @@ proc pdtk_canvas_new {name width height geometry editable} {
     bind $name.c <KeyRelease> {pdtk_canvas_sendkey %W 0 %K %A 0}
     bind $name.c <Motion> {pdtk_canvas_motion %W %x %y 0}
     bind $name.c <Control-Motion> {pdtk_canvas_motion %W %x %y 2}
+	
     if {$pd_nt == 2} {
         bind $name.c <Option-Motion> {pdtk_canvas_motion %W %x %y 4}
     } else { 
@@ -1876,22 +2331,21 @@ proc pdtk_array_listview_new {id arrayName page} {
     global fontname fontweight
     set pd_array_listview_page($arrayName) $page
     set pd_array_listview_id($arrayName) $id
-    set windowName [format ".%sArrayWindow" $arrayName]
+    set windowName [format ".%s Array Window" $arrayName]
     if [winfo exists $windowName] then [destroy $windowName]
-    toplevel $windowName -class DialogWindow
-    wm group $windowName .
+    toplevel $windowName
     wm protocol $windowName WM_DELETE_WINDOW \
         "pdtk_array_listview_close $id $arrayName"
     wm title $windowName [concat $arrayName "(list view)"]
     # FIXME
-    set font 12
+    set font 9
     set $windowName.lb [listbox $windowName.lb -height 20 -width 25\
                             -selectmode extended \
                             -relief solid -background white -borderwidth 1 \
                             -font [format {{%s} %d %s} $fontname $font $fontweight]\
                             -yscrollcommand "$windowName.lb.sb set"]
-    set $windowName.lb.sb [scrollbar $windowName.lb.sb \
-                               -command "$windowName.lb yview" -orient vertical]
+    set $windowName.lb.sb [match_linux_wm [list scrollbar $windowName.lb.sb \
+                               -command "$windowName.lb yview" -orient vertical]]
     place configure $windowName.lb.sb -relheight 1 -relx 0.9 -relwidth 0.1
     pack $windowName.lb -expand 1 -fill both
     bind $windowName.lb <Double-ButtonPress-1> \
@@ -2054,15 +2508,84 @@ proc pdtk_array_listview_close {id arrayName} {
 
 proc pdtk_canvas_autoscrollbars {name x y} {
     set size [$name bbox all]
-    set x2 [lindex $size 2]
-    set y2 [lindex $size 3]
+	set x2 [lindex $size 2]
+	set y2 [lindex $size 3]
     set rootname [winfo parent $name]
-    if {$x > $x2} {pack forget $rootname.scrollhort}
-    if {$y > $y2} {pack forget $rootname.scrollvert}
-    if {$x < $x2} {pack $rootname.scrollhort -side bottom \
-                       -fill x -before $rootname.c}
-    if {$y < $y2} {pack $rootname.scrollvert -side right \
-                       -fill y -before $rootname.c}
+	if {$x > $x2} {pack forget $rootname.scrollhort}
+	if {$y > $y2} {pack forget $rootname.scrollvert}
+	if {$x < $x2} {pack $rootname.scrollhort -side bottom \
+                   -fill x -before $rootname.c}
+	if {$y < $y2} {pack $rootname.scrollvert -side right \
+                   -fill y -before $rootname.c}
+}
+
+proc pdtk_canvas_toggle_scrollbars {rootname x} {
+    if {$x == 1} {
+		set ::scroll($rootname) 1
+		set ::xscrollable($rootname) 1
+		set ::yscrollable($rootname) 1
+		if {[info exists ::loaded($rootname)]} {
+			pdtk_canvas_getscroll $rootname.c
+		}
+    } elseif {$x == 0}  {
+		set ::scroll($rootname) 0
+		set ::xscrollable($rootname) 0
+		set ::yscrollable($rootname) 0
+		if {[info exists ::loaded($rootname)]} {
+    		pack forget $rootname.scrollhort
+    		pack forget $rootname.scrollvert
+		}
+    }
+}
+
+proc pdtk_set_canvas_background {rootname color} {
+	set ::canvas_color($rootname) $color
+	if {[info exists ::loaded($rootname)]} {
+		$rootname.c configure -background $::canvas_color($rootname)
+	}
+}
+
+proc pdtk_wm_topmost {rootname x} {
+	set ::topmost($rootname) $x
+	if {[info exists ::loaded($rootname)]} {
+		wm attributes $rootname -topmost $x
+	}
+}
+
+proc pdtk_wm_resize {rootname x} {
+	set ::resize($rootname) $x
+	if {[info exists ::loaded($rootname)]} {
+		wm resizable $rootname $x $x
+	}
+}
+
+proc pdtk_toggle_console {x} {
+	if {$x==0} {
+		.controls.switches.console instate {selected} {
+			.controls.switches.console invoke
+		}
+	} elseif {$x==1} {
+		.controls.switches.console instate {!selected} {
+			.controls.switches.console invoke
+		}
+	}
+}
+
+proc pdtk_canvas_toggle_menu {rootname x} {
+    #set rootname [winfo parent $name]
+    if {$x == 1} {
+		set ::menu($rootname) 1
+		if {[info exists ::loaded($rootname)]} {
+    		$rootname configure -menu $rootname.m
+			pack $rootname.eyecandy -fill x -expand 0 -before $rootname.c
+		}
+    } elseif {$x == 0}  {
+		set ::menu($rootname) 0
+		if {[info exists ::loaded($rootname)]} {
+    		$rootname configure -menu ""
+			pack forget $rootname.eyecandy
+		}
+    }
 }
 
 proc canvastosym {name} {
@@ -2129,70 +2652,261 @@ proc pdtk_canvas_mouseup {name x y b} {
             [$name canvasy $y] $b \;]
 }
 
+proc pdtk_canvas_getscroll_ping {name} {
+	set wname [string trimright $name .c]
+	if {![winfo exists $wname]} {
+		set ::update_tick($wname) 0
+		return
+	}
+	if {$::update_tick($wname) == 2} {
+		set ::update_tick($wname) 3		
+		pdtk_canvas_getscroll $name
+	}
+	after 40 [list pdtk_canvas_getscroll_ping $name]
+}
+
 proc pdtk_canvas_getscroll {name} {
+	global pd_nt
     global pdtk_canvas_mouseup_name
     global pdtk_canvas_mouseup_xminval
     global pdtk_canvas_mouseup_xmaxval
     global pdtk_canvas_mouseup_yminval
     global pdtk_canvas_mouseup_ymaxval
 
-    #<matju> there's a bug in Tk that messes with window size while changing the cursor. trigger it seldom.
-    if {[. cget -cursor] != "$::cursor_runmode_nothing"} {. configure -cursor $::cursor_runmode_nothing}
-    .printout.text configure -cursor xterm
-
     # kludge since this gets called sometimes after a canvas is destroyed
     if {! [winfo exists $name]} {return}
-    set size [$name bbox all]
-    if {$size != ""} {
-        set xminval 0
-        set yminval 0
-        set xmaxval 100
-        set ymaxval 100
-        set x1 [lindex $size 0]
-        set x2 [lindex $size 2]
-        set y1 [lindex $size 1]
-        set y2 [lindex $size 3]
-        
-        if {$x1 < 0} {set xminval $x1}
-        if {$y1 < 0} {set yminval $y1}
-
-        if {$x2 > 100} {set xmaxval $x2}
-        if {$y2 > 100} {set ymaxval $y2}
-
-        set parentname [winfo parent $name]
-        set winwidth [winfo width $parentname]
-        set winheight [winfo height $parentname]
-        set canvaswidth [ expr {abs($xminval)+$xmaxval} ]
-        set canvasheight [ expr {abs($yminval)+$ymaxval} ]
-
-        if {$winwidth > $canvaswidth} {pack forget $parentname.scrollhort}
-        if {$winheight > $canvasheight} {pack forget $parentname.scrollvert}
-        if {$winwidth < $canvaswidth} {pack $parentname.scrollhort -fill x \
-                                           -side bottom -before $parentname.c}
-        if {$winheight < $canvasheight} {pack $parentname.scrollvert -fill y \
-                                             -side right -before $parentname.c}
-        
-        if {$pdtk_canvas_mouseup_name != $name || \
-                $pdtk_canvas_mouseup_xminval != $xminval || \
-                $pdtk_canvas_mouseup_xmaxval != $xmaxval || \
-                $pdtk_canvas_mouseup_yminval != $yminval || \
-                $pdtk_canvas_mouseup_ymaxval != $ymaxval } {
-            
-            set newsize "$xminval $yminval $xmaxval $ymaxval"
-            $name configure -scrollregion $newsize
-            set pdtk_canvas_mouseup_name $name
-            set pdtk_canvas_mouseup_xminval $xminval
-            set pdtk_canvas_mouseup_xmaxval $xmaxval
-            set pdtk_canvas_mouseup_yminval $yminval
-            set pdtk_canvas_mouseup_ymaxval $ymaxval
-        }
 
-    }
+	# waiting for refresh
+	if {$::update_tick([winfo parent $name]) == 2} {return}
+
+	# init
+	if {$::update_tick([winfo parent $name]) == 0} {
+		set ::update_tick([winfo parent $name]) 1
+		pdtk_canvas_getscroll_ping $name		
+	}
+
+	# update
+	if {$::update_tick([winfo parent $name]) == 1} {
+		set ::update_tick([winfo parent $name]) 2
+		return
+	}
+
+	# set safe defaults for font scaling in case
+	# non-standard fonts are being used
+	set font 0
+	set mult 1.553
+	set div 59.76
+
+	#ico@bukvic.net 5/18/10
+	#bbox all is not accurate when using text
+	#this is a known issue described on the URL below
+	#this is particularly obvious when using large iemlib objects
+	#so, we calculate canvas size manually
+    #set size [$name bbox all]
+
+	#borrowed from http://wiki.tcl.tk/4844
+	set x1 1.0e30; set x2 -1.0e30 ;
+	set y1 1.0e30; set y2 -1.0e30 ;
+	foreach item [$name find all] {
+	    switch -exact [$name type $item] {
+			"arc" -
+			"line" -
+			"oval" -
+			"polygon" -
+			"rectangle" {
+				set coords [$name coords $item]
+				foreach {x y} $coords {
+					if { $x < $x1 } {set x1 $x}
+					if { $x > $x2 } {set x2 $x}
+					if { $y < $y1 } {set y1 $y}
+					if { $y > $y2 } {set y2 $y}
+				}
+			}
+			"text" {
+				set size [$name bbox $item]
+				if { $pd_nt == 0 } {
+					#find out what font we're using
+					set fnt [$name itemcget $item -font]
+					#puts stderr $fnt				
+					if { [$name itemcget $item -text] != ""} {
+						if {![string match "*8*" $fnt]} {
+							#puts stderr adjusting
+							#following fixes DejaVu Sans Mono ONLY on Linux w/ Tcl/Tk 8.5
+							#other fonts require different kinds of adjustments (most likely limited
+							#to changing 59.76 to a different ratio.
+							set tempya [lindex $size 1]
+							set tempyb [lindex $size 3]
+							set height [expr ($tempyb -$tempya)]
+							set yctr [expr $tempya + ($tempyb - $tempya)/2]
+							#$name create rectangle $x1 $yctr $x2 $yctr -outline #ff0000
+
+							#YOU MAY HAVE TO CHANGE THESE WHEN PORTING TO OSX AND WINDOWS
+							if {[string match "*DejaVu*" $fnt]} {
+								set font 0
+								set mult 1.553
+								set div 59.76
+							} elseif {[string match "*helvetica*" $fnt]} {
+								set font 1
+								set mult 1.652
+								set div 63.53
+							} elseif {[string match "*times*" $fnt]} {
+								#puts stderr times
+								set font 2
+								set mult 1.7
+								set div 65.38
+							}
+							#END CHANGES
+
+							set yoffset [expr int($height / ($mult * 2))]
+
+							set tempya [expr $yctr - $yoffset]
+							set tempyb [expr $yctr + $yoffset]
+
+							#puts stderr [concat h: $height]
+							#YOU MAY HAVE TO CHANGE THESE WHEN PORTING TO OSX AND WINDOWS
+							if { $height > $div } {
+								if { $font == 0 } {
+									set topfix [expr int($height / $div + 0.5)]
+								} elseif { $font == 1 } {
+									set topfix 0
+								} elseif { $font == 2 } {
+									set topfix 0
+								}
+								if { $topfix < 3 } {
+									if { $font == 0 } {
+										set bottomfix $topfix
+									} elseif { $font == 1 } {
+										set bottomfix [expr - int($height / $div + 0.5) + 1]
+									} elseif { $font == 2 } {
+										set bottomfix [expr - int($height / $div + 0.5) + 1]
+									}
+								} else { 
+									set bottomfix 3
+								}
+							} else {
+								set topfix 0
+								set bottomfix 0
+							}
+							#END CHANGES
+
+							#puts stderr [concat topfix: $topfix bottomfix: $bottomfix]
+							foreach {xa ya xb yb} $size {
+								if { $xa < $x1 } {set x1 $xa}
+								if { $xb > $x2 } {set x2 $xb}
+								if { [expr $tempya - $topfix] < $y1 } {set y1 [expr $tempya - $topfix]}
+								if { [expr $tempyb - $topfix + $bottomfix] > $y2 } {set y2 [expr $tempyb - $topfix + $bottomfix]}
+							}
+						} else {
+							#if there is no text or it is less than 10 pixels which speeds up things
+							#for common objects while ensuring the text is not truncated
+							foreach {xa ya xb yb} $size {
+								if { $xa < $x1 } {set x1 $xa}
+								if { $xb > $x2 } {set x2 $xb}
+								if { $ya < $y1 } {set y1 $ya}
+								if { $yb > $y2 } {set y2 $yb}
+							}
+						}
+					}
+				} else {
+					#Non-Linux OSs use the old-school style
+					#Tested on both Windows and OSX and this does not work
+					#right. Given that this stuff is also font-specific,
+					#it will have to be visited some other time. Chances are
+					#similar approach should work but will also restrict
+					#its applicability to that specific font.
+					foreach {xa ya xb yb} $size {
+						if { $xa < $x1 } {set x1 $xa}
+						if { $xb > $x2 } {set x2 $xb}
+						if { $ya < $y1 } {set y1 $ya}
+						if { $yb > $y2 } {set y2 $yb}
+					}				
+				}
+			}
+	    }
+	}
+
+	set parentname [winfo parent $name]
+
+	if {$x1 != 1.0e30} {
+
+		set xminval 0
+		set yminval 0
+		set xmaxval 100
+		set ymaxval 20
+
+		#these IMO work much better than the ones below
+		#they allow for intelligent translation of the canvas
+		#rather than introducing redundant scrollbars
+		set xminval $x1
+		set yminval $y1
+
+		set xmaxval [expr $x1+($x2-$x1)]
+		set ymaxval [expr $y1+($y2-$y1)]
+
+		#if {$x1 < $xminval} {set xminval $x1}
+		#if {$y1 < $yminval} {set yminval $y1}
+
+		#if {$x2 > $xmaxval} {set xmaxval $x2}
+		#if {$y2 > $ymaxval} {set ymaxval $y2}
+
+		set winwidth [winfo width $parentname]
+		set winheight [winfo height $parentname]
+
+		set canvaswidth [ expr {abs($xmaxval-$xminval)} ]
+		set canvasheight [ expr {abs($ymaxval-$yminval)} ]
+
+		if {$::scroll($parentname) == 1} {
+			if {$winwidth > $canvaswidth} {
+				pack forget $parentname.scrollhort
+				set ::xscrollable($parentname) 0
+			}
+			if {$winheight > $canvasheight} {
+				pack forget $parentname.scrollvert
+				set ::yscrollable($parentname) 0
+			}
+			if {$winwidth < $canvaswidth} {
+				pack $parentname.scrollhort -fill x \
+					-side bottom -before $parentname.c
+				set ::xscrollable($parentname) 1
+			}
+			if {$winheight < $canvasheight} {
+				pack $parentname.scrollvert -fill y \
+					-side right -before $parentname.c
+				set ::yscrollable($parentname) 1
+			}
+		}
+	
+		if {$pdtk_canvas_mouseup_name != $name || \
+				$pdtk_canvas_mouseup_xminval != $xminval || \
+				$pdtk_canvas_mouseup_xmaxval != $xmaxval || \
+				$pdtk_canvas_mouseup_yminval != $yminval || \
+				$pdtk_canvas_mouseup_ymaxval != $ymaxval } {
+		
+			set newsize "$xminval $yminval $xmaxval $ymaxval"
+			$name configure -scrollregion $newsize
+			set pdtk_canvas_mouseup_name $name
+			set pdtk_canvas_mouseup_xminval $xminval
+			set pdtk_canvas_mouseup_xmaxval $xmaxval
+			set pdtk_canvas_mouseup_yminval $yminval
+			set pdtk_canvas_mouseup_ymaxval $ymaxval
+		}
+	} else {
+		if {$::scroll($parentname) == 1} {
+			pack forget $parentname.scrollhort
+			set ::xscrollable($parentname) 0
+			pack forget $parentname.scrollvert
+			set ::yscrollable($parentname) 0
+		}
+	}
+	set ::update_tick([winfo parent $name]) 1
     pdtk_canvas_checkgeometry [canvastosym $name]
 }
 
 proc pdtk_canvas_sendkey {name state key iso shift} {
     global pd_nt
+	global ctrl_l_down
+	global ctrl_r_down
+
 	if {$key == "BackSpace"} {
 		set iso ""
 		set key 8
@@ -2215,55 +2929,106 @@ proc pdtk_canvas_sendkey {name state key iso shift} {
     if {$iso != ""} {
         scan $iso %c key
     }
+
+	if {$key == "Control_L"} {
+		if {$state == 1} {
+			set ctrl_l_down 1
+		} else {
+			set ctrl_l_down 0
+		}
+	}
+	if {$key == "Control_R"} {
+		if {$state == 1} {
+			set ctrl_r_down 1
+		} else {
+			set ctrl_r_down 0
+		}
+	}
+
+	if {$ctrl_l_down || $ctrl_r_down} {
+		set ctrl 1
+	} else {
+		set ctrl 0
+	}
+
+	if {[string match Home $key] && $ctrl} {
+		set key "CtrlHome"
+		set state 1
+	}
+
+	if {[string match End $key] && $ctrl} {
+		set key "CtrlEnd"
+		set state 1
+	}
+
 	pd [canvastosym $name] key $state $key $shift \;
 }
 
 proc pdtk_canvas_ctrlkey {name key shift} {
     global pd_nt
+	set ignore 0
     # first get rid of ".c" suffix; we'll refer to the toplevel instead
     set topname [string trimright $name .c]
-    #   puts stderr [concat ctrl-key $key $topname]
+    # puts stderr [concat ctrl-key $key $topname $name]
+	# puts stderr [string match .controls* $name] 
+	#.printout.text .controls.* .
+
+	if {$name == "." || $name == ".printout.text" || [string match .controls* $name] || [string match .gfxstub* $name]} {
+		set ignore 1	
+	}
 
-    if {$key == "1"} {menu_object $topname 1}
-    if {$key == "2"} {menu_message $topname 1}
-    if {$key == "3"} {menu_floatatom $topname 1}
-    if {$key == "4"} {menu_symbolatom $topname 1}
-    if {$key == "5"} {menu_comment $topname 1}
+	if {!$ignore} {
+		if {$key == "1"} {menu_object $topname 1}
+		if {$key == "2"} {menu_message $topname 1}
+		if {$key == "3"} {menu_floatatom $topname 1}
+		if {$key == "4"} {menu_symbolatom $topname 1}
+		if {$key == "5"} {menu_comment $topname 1}
+    	if {$key == "Return"} {menu_reselect $topname}
+	}
     if {$key == "slash"} {menu_audio 1}
     if {$key == "period"} {menu_audio 0}
-    if {$key == "Return"} {menu_reselect $topname}
     if {$shift == 1} {
         if {$key == "q" || $key == "Q"} {menu_really_quit}
-        if {$key == "w" || $key == "W"} {menu_really_close $topname}
-        if {$key == "s" || $key == "S"} {menu_saveas $topname}
-        if {$key == "z" || $key == "Z"} {menu_redo $topname}
-        if {$key == "b" || $key == "B"} {menu_bng $topname 1}
-        if {$key == "t" || $key == "T"} {menu_toggle $topname 1}
-        if {$key == "n" || $key == "N"} {menu_numbox $topname 1}
-        if {$key == "v" || $key == "V"} {menu_vslider $topname 1}
-        if {$key == "h" || $key == "H"} {menu_hslider $topname 1}
-        if {$key == "i" || $key == "I"} {menu_hradio $topname 1}
-        if {$key == "d" || $key == "D"} {menu_vradio $topname 1}
-        if {$key == "u" || $key == "U"} {menu_vumeter $topname 1}
-        if {$key == "c" || $key == "C"} {menu_mycnv $topname 1}
         if {$key == "l" || $key == "L"} {menu_clear_console}
         if {$key == "r" || $key == "R"} {menu_toggle_console}
+		if {!$ignore} {
+	        if {$key == "w" || $key == "W"} {menu_really_close $topname}
+	        if {$key == "s" || $key == "S"} {menu_saveas $topname}
+		    if {$key == "b" || $key == "B"} {menu_bng $topname 1}
+		    if {$key == "n" || $key == "N"} {menu_numbox $topname 1}
+		    if {$key == "v" || $key == "V"} {menu_vslider $topname 1}
+		    if {$key == "h" || $key == "H"} {menu_hslider $topname 1}
+		    if {$key == "i" || $key == "I"} {menu_hradio $topname 1}
+		    if {$key == "d" || $key == "D"} {menu_vradio $topname 1}
+		    if {$key == "u" || $key == "U"} {menu_vumeter $topname 1}
+		    if {$key == "c" || $key == "C"} {menu_mycnv $topname 1}
+		    if {$key == "t" || $key == "T"} {menu_toggle $topname 1}
+		    if {$key == "z" || $key == "Z"} {menu_redo $topname}
+		}
     } else {
-        if {$key == "e" || $key == "E"} {menu_editmode $topname}
         if {$key == "q" || $key == "Q"} {menu_quit}
-        if {$key == "s" || $key == "S"} {menu_save $topname}
+		if {$key == "y" || $key == "Y"} {menu_tidyup $name}
+		if {$key == "Up"} {popup_action $name 3}
+		if {$key == "Down"} {popup_action $name 4}
         if {$key == "z" || $key == "Z"} {menu_undo $topname}
         if {$key == "b" || $key == "B"} {::helpbrowser::open_helpbrowser}
         if {$key == "n" || $key == "N"} {menu_new}
         if {$key == "o" || $key == "O"} {menu_open}
-        if {$key == "w" || $key == "W"} {menu_close $topname}
         if {$key == "p" || $key == "P"} {menu_print $topname}
-        if {$key == "r" || $key == "R"} {menu_raise_console}
+        if {$key == "semicolon"} {menu_raise_console}
         if {$key == "x" || $key == "X"} {menu_cut $topname}
         if {$key == "c" || $key == "C"} {menu_copy $topname}
         if {$key == "v" || $key == "V"} {menu_paste $topname}
-        if {$key == "d" || $key == "D"} {menu_duplicate $topname}
         if {$key == "a" || $key == "A"} {menu_selectall $topname}
+		if {!$ignore} {
+        	if {$key == "w" || $key == "W"} {menu_close $topname}
+	        if {$key == "s" || $key == "S"} {menu_save $topname}
+        	if {$key == "e" || $key == "E"} {menu_editmode $topname}
+        	if {$key == "d" || $key == "D"} {menu_duplicate $topname}
+			## jsarlo
+			if {$key == "r" || $key == "R"} {menu_magicglass $topname}
+			## end jsarlo
+		}
         if {$pd_nt == 2} { 
 			# by default, Cmd-T opens the font panel on Mac OS X
             if {$key == "t" || $key == "T"} {menu_font $topname}
@@ -2273,17 +3038,28 @@ proc pdtk_canvas_ctrlkey {name key shift} {
 			# minimize window on Mac OS X
 			if {$key == "m" || $key == "M"} {menu_send}
         }
-        if {$key == "f" || $key == "F"} {menu_findobject $topname}
-        if {$key == "g" || $key == "G"} {menu_findagain $topname}
+		if {!$ignore} {		
+        	if {$key == "f" || $key == "F"} {menu_findobject $topname}
+        	if {$key == "g" || $key == "G"} {menu_findagain $topname}
+		}
     }
 }
 
 proc pdtk_canvas_scroll {canvas xy distance} {
-    $canvas [list $xy]view scroll $distance units
+	if {$xy eq "x" && $::xscrollable([winfo parent $canvas]) == 1 || $xy eq "y" && $::yscrollable([winfo parent $canvas]) == 1 } {
+    	$canvas [list $xy]view scroll $distance units
+	}
 }
 
 proc pdtk_canvas_motion {name x y mods} {
-    #    puts stderr [concat [canvastosym $name] $name $x $y]
+	global pointer_x_local pointer_y_local pointer_x_global pointer_y_global
+	set pointer_x_local $x
+	set pointer_y_local $y
+	set pointer_x_global [expr $pointer_x_local + [winfo rootx $name]]
+	set pointer_y_global [expr $pointer_y_local + [winfo rooty $name]]
+
+ 	#puts stderr [concat $pointer_x_local $pointer_y_local $pointer_x_global $pointer_y_global]
+    #puts stderr [concat [canvastosym $name] $name $x $y]
     pd [canvastosym $name] motion [$name canvasx $x] [$name canvasy $y] $mods \;
 }
 
@@ -2330,8 +3106,8 @@ proc pdtk_canvas_saveas {name initfile initdir} {
                 set filename $filename.pd
                 if {[file exists $filename]} {
                     set answer [tk_messageBox \
-                                    \-message [concat overwrite $filename "?"] \
-                                    \-type yesno \-icon question]
+                    	\-message [concat overwrite $filename "?"] \
+                        \-type yesno \-icon question]
                     if {! [string compare $answer no]} {return}
                 }
             }
@@ -2385,7 +3161,7 @@ proc dofont_ok {name} {
 }
 
 proc pdtk_canvas_dofont {name initsize} {
-    global fontsize dofont_fontsize
+    global fontsize dofont_fontsize pd_nt
     set fontsize $initsize
     set dofont_fontsize $initsize
 
@@ -2395,39 +3171,47 @@ proc pdtk_canvas_dofont {name initsize} {
     global whichstretch
     set whichstretch 1
     
-    toplevel $name -class DialogWindow
-    wm title $name  {FONT BOMB}
+    toplevel $name
+	match_linux_wm [list $name configure]
+	wm resizable $name 0 0
+    wm title $name  {Font Settings}
     wm protocol $name WM_DELETE_WINDOW [concat dofont_cancel $name]
 
     pdtk_panelkeybindings $name dofont
     
-    frame $name.buttonframe
-    pack $name.buttonframe -side bottom -fill x -pady 2m
-    button $name.buttonframe.cancel -text {Cancel}\
-        -command "dofont_cancel $name"
-    button $name.buttonframe.ok -text {OK}\
-        -command "dofont_ok $name"
-    pack $name.buttonframe.cancel -side left -expand 1
-    pack $name.buttonframe.ok -side left -expand 1
+    match_linux_wm [list frame $name.buttonframe]
+    pack $name.buttonframe -side bottom -fill x -pady 3
+	match_linux_wm [list button $name.buttonframe.cancel -text {Cancel}\
+	    -command "dofont_cancel $name"]
+	match_linux_wm [list button $name.buttonframe.ok -text {OK}\
+	    -command "dofont_ok $name"]
+    pack $name.buttonframe.cancel -side left -expand 1 -padx 3
+    pack $name.buttonframe.ok -side left -expand 1 -padx 3
     
-    frame $name.radiof
+    match_linux_wm [list frame $name.radiof]
     pack $name.radiof -side left
     
-    label $name.radiof.label -text {Font Size:}
+    match_linux_wm [list label $name.radiof.label -text {Font Size:}]
     pack $name.radiof.label -side top
 
-    radiobutton $name.radiof.radio8 -value 8 -variable dofont_fontsize -text "8" \
-        -command [concat dofont_apply $name 8]
-    radiobutton $name.radiof.radio10 -value 10 -variable dofont_fontsize -text "10" \
-        -command [concat dofont_apply $name 10]
-    radiobutton $name.radiof.radio12 -value 12 -variable dofont_fontsize -text "12" \
-        -command [concat dofont_apply $name 12]
-    radiobutton $name.radiof.radio16 -value 16 -variable dofont_fontsize -text "16" \
-        -command [concat dofont_apply $name 16]
-    radiobutton $name.radiof.radio24 -value 24 -variable dofont_fontsize -text "24" \
-        -command [concat dofont_apply $name 24]
-    radiobutton $name.radiof.radio36 -value 36 -variable dofont_fontsize -text "36" \
-        -command [concat dofont_apply $name 36]
+    match_linux_wm [list radiobutton $name.radiof.radio8 -value 8 \
+		-variable dofont_fontsize -text "8" \
+        -command [concat dofont_apply $name 8]]
+    match_linux_wm [list radiobutton $name.radiof.radio10 -value 10 \
+		-variable dofont_fontsize -text "10" \
+        -command [concat dofont_apply $name 10]]
+    match_linux_wm [list radiobutton $name.radiof.radio12 -value 12 \
+		-variable dofont_fontsize -text "12" \
+        -command [concat dofont_apply $name 12]]
+    match_linux_wm [list radiobutton $name.radiof.radio16 -value 16 \
+		-variable dofont_fontsize -text "16" \
+        -command [concat dofont_apply $name 16]]
+    match_linux_wm [list radiobutton $name.radiof.radio24 -value 24 \
+		-variable dofont_fontsize -text "24" \
+        -command [concat dofont_apply $name 24]]
+    match_linux_wm [list radiobutton $name.radiof.radio36 -value 36 \
+		-variable dofont_fontsize -text "36" \
+        -command [concat dofont_apply $name 36]]
     pack $name.radiof.radio8 -side top -anchor w
     pack $name.radiof.radio10 -side top -anchor w
     pack $name.radiof.radio12 -side top -anchor w
@@ -2436,27 +3220,31 @@ proc pdtk_canvas_dofont {name initsize} {
     pack $name.radiof.radio36 -side top -anchor w
 
     set current_radiobutton [format "$name.radiof.radio%d" $initsize]
-    $current_radiobutton select
-
-    frame $name.stretchf
-    pack $name.stretchf -side left
-    
-    label $name.stretchf.label -text {Stretch:}
-    pack $name.stretchf.label -side top
-    
-    entry $name.stretchf.entry -textvariable stretchval -width 5
-    pack $name.stretchf.entry -side left
-
-    radiobutton $name.stretchf.radio1 \
-        -value 1 -variable whichstretch -text "X and Y"
-    radiobutton $name.stretchf.radio2 \
-        -value 2 -variable whichstretch -text "X only"
-    radiobutton $name.stretchf.radio3 \
-        -value 3 -variable whichstretch -text "Y only"
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+	    $current_radiobutton invoke
+	} else {
+	    $current_radiobutton select
+	}
 
-    pack $name.stretchf.radio1 -side top -anchor w
-    pack $name.stretchf.radio2 -side top -anchor w
-    pack $name.stretchf.radio3 -side top -anchor w
+#    match_linux_wm [list frame $name.stretchf]
+#    pack $name.stretchf -side left
+#    
+#    match_linux_wm [list label $name.stretchf.label -text {Stretch:}]
+#    pack $name.stretchf.label -side top
+#    
+#    match_linux_wm [list entry $name.stretchf.entry -textvariable stretchval -width 5]
+#    pack $name.stretchf.entry -side left
+#
+#    match_linux_wm [list radiobutton $name.stretchf.radio1 \
+#        -value 1 -variable whichstretch -text "X and Y"]
+#    match_linux_wm [list radiobutton $name.stretchf.radio2 \
+#        -value 2 -variable whichstretch -text "X only"]
+#    match_linux_wm [list radiobutton $name.stretchf.radio3 \
+#        -value 3 -variable whichstretch -text "Y only"]
+#
+#    pack $name.stretchf.radio1 -side top -anchor w
+#    pack $name.stretchf.radio2 -side top -anchor w
+#    pack $name.stretchf.radio3 -side top -anchor w
 
 }
 
@@ -2548,7 +3336,7 @@ proc pdtk_gatom_dialog {id initwidth initlo inithi \
 
     set vid [string trimleft $id .]
 
-     global pd_nt
+	global pd_nt
 
     set var_gatomwidth [concat gatomwidth_$vid]
     global $var_gatomwidth
@@ -2573,134 +3361,149 @@ proc pdtk_gatom_dialog {id initwidth initlo inithi \
     set $var_gatomsymfrom [gatom_unescape $symfrom]
     set $var_gatomsymto [gatom_unescape $symto]
 
-    toplevel $id -class DialogWindow
-    wm title $id "atom box properties"
+    toplevel $id
+    wm title $id "Atom Box Properties"
+	match_linux_wm [list $id configure] 
     wm resizable $id 0 0
+	global tmp_xpix tmp_ypix
+	wm geometry $id "+$tmp_xpix+$tmp_ypix"
     wm protocol $id WM_DELETE_WINDOW [concat dogatom_cancel $id]
 
     pdtk_panelkeybindings $id "dogatom"
 
-    frame $id.params -height 7
+    match_linux_wm [list frame $id.params -pady 3]
     pack $id.params -side top
-    label $id.params.entryname -text "width"
-    entry $id.params.entry -textvariable $var_gatomwidth -width 4
-    pack $id.params.entryname $id.params.entry -side left
-
-    labelframe $id.limits -text "limits" -padx 15 -pady 4 -borderwidth 1 \
-        -font highlight_font
-    pack $id.limits -side top -fill x
-    frame $id.limits.lower
+    match_linux_wm [list label $id.params.entryname -text "width"]
+    match_linux_wm [list entry $id.params.entry \
+		-textvariable $var_gatomwidth -width 4]
+    pack $id.params.entryname $id.params.entry -side left -pady 3
+
+    match_linux_wm [list labelframe $id.limits -text "limits" \
+		-padx 3 -pady 3 -borderwidth 1 \
+        -font highlight_font]
+    pack $id.limits -side top -fill x -padx 3
+    match_linux_wm [list frame $id.limits.lower]
     pack $id.limits.lower -side left
-    label $id.limits.lower.entryname -text "lower"
-    entry $id.limits.lower.entry -textvariable $var_gatomlo -width 8
-    pack $id.limits.lower.entryname $id.limits.lower.entry -side left
-    frame $id.limits.upper
+    match_linux_wm [list label $id.limits.lower.entryname -text "lower"]
+    match_linux_wm [list entry $id.limits.lower.entry \
+		-textvariable $var_gatomlo -width 8]
+    pack $id.limits.lower.entryname $id.limits.lower.entry -side left -padx 3 -pady 3
+    match_linux_wm [list frame $id.limits.upper]
     pack $id.limits.upper -side left
-    frame $id.limits.upper.spacer -width 20
-    label $id.limits.upper.entryname -text "upper"
-    entry $id.limits.upper.entry -textvariable $var_gatomhi -width 8
+    match_linux_wm [list frame $id.limits.upper.spacer -width 20]
+    match_linux_wm [list label $id.limits.upper.entryname -text "upper"]
+    match_linux_wm [list entry $id.limits.upper.entry \
+		-textvariable $var_gatomhi -width 8]
     pack  $id.limits.upper.spacer $id.limits.upper.entryname \
-        $id.limits.upper.entry -side left
+        $id.limits.upper.entry -side left -padx 3 -pady 3
 
-    frame $id.spacer1 -height 7
+    match_linux_wm [list frame $id.spacer1 -height 7]
     pack $id.spacer1 -side top
 
-    labelframe $id.label -text "label" -padx 5 -pady 4 -borderwidth 1 \
-        -font highlight_font
-    pack $id.label -side top -fill x
-    frame $id.label.name
+    match_linux_wm [list labelframe $id.label -text "label" \
+		-padx 5 -pady 4 -borderwidth 1 \
+        -font highlight_font]
+    pack $id.label -side top -fill x -padx 3
+    match_linux_wm [list frame $id.label.name]
     pack $id.label.name -side top
-    entry $id.label.name.entry -textvariable $var_gatomlabel -width 33
+    match_linux_wm [list entry $id.label.name.entry \
+		-textvariable $var_gatomlabel -width 35]
     pack $id.label.name.entry -side left
-    frame $id.label.radio
+    match_linux_wm [list frame $id.label.radio]
     pack $id.label.radio -side top
-    radiobutton $id.label.radio.left -value 0 \
+    match_linux_wm [list radiobutton $id.label.radio.left -value 0 \
         -variable $var_gatomwherelabel \
-        -text "left   "  -justify left
-    radiobutton $id.label.radio.right -value 1 \
+        -text "left   "]
+    match_linux_wm [list radiobutton $id.label.radio.right -value 1 \
         -variable $var_gatomwherelabel \
-        -text "right" -justify left
-    radiobutton $id.label.radio.top -value 2 \
+        -text "right"]
+    match_linux_wm [list radiobutton $id.label.radio.top -value 2 \
         -variable $var_gatomwherelabel \
-        -text "top" -justify left
-    radiobutton $id.label.radio.bottom -value 3 \
+        -text "top"]
+    match_linux_wm [list radiobutton $id.label.radio.bottom -value 3 \
         -variable $var_gatomwherelabel \
-        -text "bottom" -justify left
+        -text "bottom"]
     pack $id.label.radio.left -side left -anchor w
     pack $id.label.radio.right -side right -anchor w
     pack $id.label.radio.top -side top -anchor w
     pack $id.label.radio.bottom -side bottom -anchor w
 
-    frame $id.spacer2 -height 7
+    match_linux_wm [list frame $id.spacer2 -height 7]
     pack $id.spacer2 -side top
 
-    labelframe $id.s_r -text "messages" -padx 5 -pady 4 -borderwidth 1 \
-        -font highlight_font
-    pack $id.s_r -side top -fill x
-    frame $id.s_r.paramsymto
+    match_linux_wm [list labelframe $id.s_r \
+		-text "messages" -padx 5 -pady 4 -borderwidth 1 \
+        -font highlight_font]
+    pack $id.s_r -side top -fill x -padx 3
+    match_linux_wm [list frame $id.s_r.paramsymto]
     pack $id.s_r.paramsymto -side top -anchor e
-    label $id.s_r.paramsymto.entryname -text "send symbol"
-    entry $id.s_r.paramsymto.entry -textvariable $var_gatomsymto -width 21
-    pack $id.s_r.paramsymto.entry $id.s_r.paramsymto.entryname -side right
+    match_linux_wm [list label $id.s_r.paramsymto.entryname -text "send symbol"]
+    match_linux_wm [list entry $id.s_r.paramsymto.entry \
+		-textvariable $var_gatomsymto -width 21]
+    pack $id.s_r.paramsymto.entry $id.s_r.paramsymto.entryname -side right -pady 3
 
-    frame $id.s_r.paramsymfrom
+    match_linux_wm [list frame $id.s_r.paramsymfrom]
     pack $id.s_r.paramsymfrom -side top -anchor e
-    label $id.s_r.paramsymfrom.entryname -text "receive symbol"
-    entry $id.s_r.paramsymfrom.entry -textvariable $var_gatomsymfrom -width 21
-    pack $id.s_r.paramsymfrom.entry $id.s_r.paramsymfrom.entryname -side right
+    match_linux_wm [list label $id.s_r.paramsymfrom.entryname -text "receive symbol"]
+    match_linux_wm [list entry $id.s_r.paramsymfrom.entry \
+		-textvariable $var_gatomsymfrom -width 21]
+    pack $id.s_r.paramsymfrom.entry $id.s_r.paramsymfrom.entryname -side right -pady 3
     
-    frame $id.buttonframe -pady 5
-    pack $id.buttonframe -side top -fill x -pady 2m
-    button $id.buttonframe.cancel -text {Cancel}\
-        -command "dogatom_cancel $id"
-    pack $id.buttonframe.cancel -side left -expand 1
-    button $id.buttonframe.apply -text {Apply}\
-        -command "dogatom_apply $id"
-    pack $id.buttonframe.apply -side left -expand 1
-    button $id.buttonframe.ok -text {OK}\
-        -command "dogatom_ok $id"
-    pack $id.buttonframe.ok -side left -expand 1
-
-    $id.params.entry select from 0
-    $id.params.entry select adjust end
+    match_linux_wm [list frame $id.buttonframe -pady 5]
+    pack $id.buttonframe -side top -fill x -pady 3
+	match_linux_wm [list button $id.buttonframe.cancel -text {Cancel} \
+	    -command "dogatom_cancel $id"]
+	match_linux_wm [list button $id.buttonframe.apply -text {Apply} \
+	    -command "dogatom_apply $id"]
+	match_linux_wm [list button $id.buttonframe.ok -text {OK} \
+	    -command "dogatom_ok $id"]	
+	pack $id.buttonframe.cancel -side left -expand 1 -padx 3
+	pack $id.buttonframe.apply -side left -expand 1 -padx 3
+    pack $id.buttonframe.ok -side left -expand 1 -padx 3
+
+	if { [info tclversion] < 8.5 } {
+		$id.params.entry select from 0
+		$id.params.entry select adjust end
+	}
     focus $id.params.entry
 }
 
 ############ pdtk_canvas_popup -- popup menu for canvas #########
 
-set popup_xpix 0
-set popup_ypix 0
-
 proc popup_action {name action} {
     global popup_xpix popup_ypix
+	if {[string compare $name .c]} {
+		set name [string trimright $name .c]
+	}
 	set cmd [concat $name done-popup $action $popup_xpix $popup_ypix \;]
-	#    puts stderr $cmd
+	    #puts stderr $cmd
 	pd $cmd
 }
 
-proc pdtk_canvas_popup {mytoplevel xcanvas ycanvas hasproperties hasopen} {
-    set ::popup_xpix $xcanvas
-    set ::popup_ypix $ycanvas
-    if {$hasproperties} {
-        $mytoplevel.popup entryconfigure "Properties" -state normal
-    } else {
-        $mytoplevel.popup entryconfigure "Properties" -state disabled
-    }
-    if {$hasopen} {
-        $mytoplevel.popup entryconfigure "Open" -state normal
-    } else {
-        $mytoplevel.popup entryconfigure "Open" -state disabled
-    }
-    set tkcanvas $mytoplevel.c
-    set scrollregion [$tkcanvas cget -scrollregion]
-    # get the canvas location that is currently the top left corner in the window
-    set left_xview_pix [expr [lindex [$tkcanvas xview] 0] * [lindex $scrollregion 2]]
-    set top_yview_pix [expr [lindex [$tkcanvas yview] 0] * [lindex $scrollregion 3]]
-    # take the mouse clicks in canvas coords, add the root of the canvas
-    # window, and subtract the area that is obscured by scrolling
-    set xpopup [expr int($xcanvas + [winfo rootx $tkcanvas] - $left_xview_pix)]
-    set ypopup [expr int($ycanvas + [winfo rooty $tkcanvas] - $top_yview_pix)]
-    tk_popup $mytoplevel.popup $xpopup $ypopup 0
+proc pdtk_canvas_popup {name xpix ypix canprop canopen isobject} {
+    global popup_xpix popup_ypix
+	global tmp_xpix tmp_ypix
+	set popup_xpix $xpix
+	set popup_ypix $ypix
+    set tmp_xpix [expr $xpix - [$name.c canvasx 0] + [winfo rootx $name.c]]
+	scan $tmp_xpix %d tmp_xpix
+    set tmp_ypix [expr $ypix - [$name.c canvasy 0] + [winfo rooty $name.c]]
+	scan $tmp_ypix %d tmp_ypix
+	#puts stderr $isobject
+    if {$canprop == 0} {$name.popup entryconfigure 0 -state disabled}
+    if {$canprop == 1} {$name.popup entryconfigure 0 -state active}
+    if {$canopen == 0} {$name.popup entryconfigure 1 -state disabled}
+    if {$canopen == 1} {$name.popup entryconfigure 1 -state active}
+    if {$isobject == 0} {
+		$name.popup entryconfigure 4 -state disabled
+		$name.popup entryconfigure 5 -state disabled
+	}
+    if {$isobject == 1} {
+		$name.popup entryconfigure 4 -state active
+		$name.popup entryconfigure 5 -state active
+	}
+    tk_popup $name.popup $tmp_xpix \
+        $tmp_ypix 0
 }
 
 
@@ -2723,6 +3526,8 @@ proc iemgui_clip_dim {id} {
     set var_iemgui_min_hgt [concat iemgui_min_hgt_$vid]
     global $var_iemgui_min_hgt
     
+	#pdtk_post "iemdim: [eval concat $$var_iemgui_wdt] [eval concat $$var_iemgui_min_wdt] [eval concat $$var_iemgui_hgt] [eval concat $$var_iemgui_min_hgt]\n"
+
     if {[eval concat $$var_iemgui_wdt] < [eval concat $$var_iemgui_min_wdt]} {
         set $var_iemgui_wdt [eval concat $$var_iemgui_min_wdt]
         $id.dim.w_ent configure -textvariable $var_iemgui_wdt
@@ -2838,7 +3643,7 @@ proc iemgui_set_col_example {id} {
     global $var_iemgui_fcol
     set var_iemgui_lcol [concat iemgui_lcol_$vid]
     global $var_iemgui_lcol
-    
+
     $id.colors.sections.lb_bk configure \
         -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
         -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
@@ -2878,6 +3683,8 @@ proc iemgui_preset_col {id presetcol} {
 }
 
 proc iemgui_choose_col_bkfrlb {id} {
+	global hex_color color_applied pd_nt
+
     set vid [string trimleft $id .]
 
     set var_iemgui_l2_f1_b0 [concat iemgui_l2_f1_b0_$vid]
@@ -2888,28 +3695,73 @@ proc iemgui_choose_col_bkfrlb {id} {
     global $var_iemgui_fcol
     set var_iemgui_lcol [concat iemgui_lcol_$vid]
     global $var_iemgui_lcol
-    
-    if {[eval concat $$var_iemgui_l2_f1_b0] == 0} {
-        set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFCFCFC]
-        set helpstring [tk_chooseColor -title "Background-Color" -initialcolor [format "#%6.6x" [eval concat $$var_iemgui_bcol]]]
-        if { $helpstring != "" } {
-            set $var_iemgui_bcol [string replace $helpstring 0 0 "0x"]
-            set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFCFCFC] }
-    }
-    if {[eval concat $$var_iemgui_l2_f1_b0] == 1} {
-        set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFCFCFC]
-        set helpstring [tk_chooseColor -title "Front-Color" -initialcolor [format "#%6.6x" [eval concat $$var_iemgui_fcol]]]
-        if { $helpstring != "" } {
-            set $var_iemgui_fcol [string replace $helpstring 0 0 "0x"]
-            set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFCFCFC] }
-    }
-    if {[eval concat $$var_iemgui_l2_f1_b0] == 2} {
-        set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFCFCFC]
-        set helpstring [tk_chooseColor -title "Label-Color" -initialcolor [format "#%6.6x" [eval concat $$var_iemgui_lcol]]]
-        if { $helpstring != "" } {
-            set $var_iemgui_lcol [string replace $helpstring 0 0 "0x"]
-            set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFCFCFC] }
+
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		if {[eval concat $$var_iemgui_l2_f1_b0] == 0} {
+		    set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFFFFFF]
+			set loop [pdtk_pd_color_dlg [format "#%6.6x" \
+				[eval concat $$var_iemgui_bcol]]]
+			vwait color_applied
+			set color_applied -1
+		    set $var_iemgui_bcol [string replace $hex_color 0 0 "0x"]
+		    set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFFFFFF]
+		}
+	} else {
+		if {[eval concat $$var_iemgui_l2_f1_b0] == 0} {
+			set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFCFCFC]
+			set helpstring [tk_chooseColor -title "Custom Background Color" \
+				-initialcolor [format "#%6.6x" [eval concat $$var_iemgui_bcol]]]
+			if { $helpstring != "" } {
+			    set $var_iemgui_bcol [string replace $helpstring 0 0 "0x"]
+			    set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFCFCFC] 
+			}
+		}
     }
+
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		if {[eval concat $$var_iemgui_l2_f1_b0] == 1} {
+		    set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFFFFFF]
+			set loop [pdtk_pd_color_dlg [format "#%6.6x" \
+				[eval concat $$var_iemgui_fcol]]]
+			vwait color_applied
+			set color_applied -1
+		    set $var_iemgui_fcol [string replace $hex_color 0 0 "0x"]
+		    set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFFFFFF]
+		}
+	} else {
+		if {[eval concat $$var_iemgui_l2_f1_b0] == 1} {
+		    set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFCFCFC]
+		    set helpstring [tk_chooseColor -title "Custom Foreground Color" \
+				-initialcolor [format "#%6.6x" [eval concat $$var_iemgui_fcol]]]
+		    if { $helpstring != "" } {
+		        set $var_iemgui_fcol [string replace $helpstring 0 0 "0x"]
+		        set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFCFCFC]
+			}
+		}
+	}
+
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		if {[eval concat $$var_iemgui_l2_f1_b0] == 2} {
+		    set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFFFFFF]
+			set loop [pdtk_pd_color_dlg [format "#%6.6x" \
+				[eval concat $$var_iemgui_lcol]]]
+			vwait color_applied
+			set color_applied -1
+		    set $var_iemgui_lcol [string replace $hex_color 0 0 "0x"]
+		    set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFFFFFF]
+		}
+	} else {
+		if {[eval concat $$var_iemgui_l2_f1_b0] == 2} {
+		    set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFCFCFC]
+		    set helpstring [tk_chooseColor -title "Label-Color" \
+				-initialcolor [format "#%6.6x" [eval concat $$var_iemgui_lcol]]]
+		    if { $helpstring != "" } {
+		        set $var_iemgui_lcol [string replace $helpstring 0 0 "0x"]
+		        set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFCFCFC]
+			}
+		}
+	}
+
     iemgui_set_col_example $id
 }
 
@@ -2950,7 +3802,7 @@ proc iemgui_toggle_font {id gn_f} {
         1 { set current_font "Helvetica" }
         2 { set current_font "Times" }
     }
-    set current_font_spec "{$current_font} 12 $fontweight"
+    set current_font_spec "{$current_font} 9 $fontweight"
 
     $id.label.fontpopup_label configure -text $current_font \
         -font $current_font_spec
@@ -2990,105 +3842,118 @@ proc iemgui_stdy_jmp {id} {
 }
 
 proc iemgui_apply {id} {
-    set vid [string trimleft $id .]
+	global color_applied
+	if {$color_applied > -1 && [winfo exists .color_dlg]} {
+		destroy .color_dlg
+		set color_applied -1
+	}
 
-    set var_iemgui_wdt [concat iemgui_wdt_$vid]
-    global $var_iemgui_wdt
-    set var_iemgui_min_wdt [concat iemgui_min_wdt_$vid]
-    global $var_iemgui_min_wdt
-    set var_iemgui_hgt [concat iemgui_hgt_$vid]
-    global $var_iemgui_hgt
-    set var_iemgui_min_hgt [concat iemgui_min_hgt_$vid]
-    global $var_iemgui_min_hgt
-    set var_iemgui_min_rng [concat iemgui_min_rng_$vid]
-    global $var_iemgui_min_rng
-    set var_iemgui_max_rng [concat iemgui_max_rng_$vid]
-    global $var_iemgui_max_rng
-    set var_iemgui_lin0_log1 [concat iemgui_lin0_log1_$vid]
-    global $var_iemgui_lin0_log1
-    set var_iemgui_lilo0 [concat iemgui_lilo0_$vid]
-    global $var_iemgui_lilo0
-    set var_iemgui_lilo1 [concat iemgui_lilo1_$vid]
-    global $var_iemgui_lilo1
-    set var_iemgui_loadbang [concat iemgui_loadbang_$vid]
-    global $var_iemgui_loadbang
-    set var_iemgui_num [concat iemgui_num_$vid]
-    global $var_iemgui_num
-    set var_iemgui_steady [concat iemgui_steady_$vid]
-    global $var_iemgui_steady
-    set var_iemgui_snd [concat iemgui_snd_$vid]
-    global $var_iemgui_snd
-    set var_iemgui_rcv [concat iemgui_rcv_$vid]
-    global $var_iemgui_rcv
-    set var_iemgui_gui_nam [concat iemgui_gui_nam_$vid]
-    global $var_iemgui_gui_nam
-    set var_iemgui_gn_dx [concat iemgui_gn_dx_$vid]
-    global $var_iemgui_gn_dx
-    set var_iemgui_gn_dy [concat iemgui_gn_dy_$vid]
-    global $var_iemgui_gn_dy
-    set var_iemgui_gn_f [concat iemgui_gn_f_$vid]
-    global $var_iemgui_gn_f
-    set var_iemgui_gn_fs [concat iemgui_gn_fs_$vid]
-    global $var_iemgui_gn_fs
-    set var_iemgui_bcol [concat iemgui_bcol_$vid]
-    global $var_iemgui_bcol
-    set var_iemgui_fcol [concat iemgui_fcol_$vid]
-    global $var_iemgui_fcol
-    set var_iemgui_lcol [concat iemgui_lcol_$vid]
-    global $var_iemgui_lcol
-    
-    iemgui_clip_dim $id
-    iemgui_clip_num $id
-    iemgui_sched_rng $id
-    iemgui_verify_rng $id
-    iemgui_sched_rng $id
-    iemgui_clip_fontsize $id
-    
-    if {[eval concat $$var_iemgui_snd] == ""} {set hhhsnd "empty"} else {set hhhsnd [eval concat $$var_iemgui_snd]}
-    if {[eval concat $$var_iemgui_rcv] == ""} {set hhhrcv "empty"} else {set hhhrcv [eval concat $$var_iemgui_rcv]}
-    if {[eval concat $$var_iemgui_gui_nam] == ""} {set hhhgui_nam "empty"
-    } else {
-        set hhhgui_nam [eval concat $$var_iemgui_gui_nam]}
-
-    if {[string index $hhhsnd 0] == "$"} {
-        set hhhsnd [string replace $hhhsnd 0 0 #] }
-    if {[string index $hhhrcv 0] == "$"} {
-        set hhhrcv [string replace $hhhrcv 0 0 #] }
-    if {[string index $hhhgui_nam 0] == "$"} {
-        set hhhgui_nam [string replace $hhhgui_nam 0 0 #] }
-    
-    set hhhsnd [pdtk_unspace $hhhsnd]
-    set hhhrcv [pdtk_unspace $hhhrcv]
-    set hhhgui_nam [pdtk_unspace $hhhgui_nam]
+	set vid [string trimleft $id .]
+
+	set var_iemgui_wdt [concat iemgui_wdt_$vid]
+	global $var_iemgui_wdt
+	set var_iemgui_min_wdt [concat iemgui_min_wdt_$vid]
+	global $var_iemgui_min_wdt
+	set var_iemgui_hgt [concat iemgui_hgt_$vid]
+	global $var_iemgui_hgt
+	set var_iemgui_min_hgt [concat iemgui_min_hgt_$vid]
+	global $var_iemgui_min_hgt
+	set var_iemgui_min_rng [concat iemgui_min_rng_$vid]
+	global $var_iemgui_min_rng
+	set var_iemgui_max_rng [concat iemgui_max_rng_$vid]
+	global $var_iemgui_max_rng
+	set var_iemgui_lin0_log1 [concat iemgui_lin0_log1_$vid]
+	global $var_iemgui_lin0_log1
+	set var_iemgui_lilo0 [concat iemgui_lilo0_$vid]
+	global $var_iemgui_lilo0
+	set var_iemgui_lilo1 [concat iemgui_lilo1_$vid]
+	global $var_iemgui_lilo1
+	set var_iemgui_loadbang [concat iemgui_loadbang_$vid]
+	global $var_iemgui_loadbang
+	set var_iemgui_num [concat iemgui_num_$vid]
+	global $var_iemgui_num
+	set var_iemgui_steady [concat iemgui_steady_$vid]
+	global $var_iemgui_steady
+	set var_iemgui_snd [concat iemgui_snd_$vid]
+	global $var_iemgui_snd
+	set var_iemgui_rcv [concat iemgui_rcv_$vid]
+	global $var_iemgui_rcv
+	set var_iemgui_gui_nam [concat iemgui_gui_nam_$vid]
+	global $var_iemgui_gui_nam
+	set var_iemgui_gn_dx [concat iemgui_gn_dx_$vid]
+	global $var_iemgui_gn_dx
+	set var_iemgui_gn_dy [concat iemgui_gn_dy_$vid]
+	global $var_iemgui_gn_dy
+	set var_iemgui_gn_f [concat iemgui_gn_f_$vid]
+	global $var_iemgui_gn_f
+	set var_iemgui_gn_fs [concat iemgui_gn_fs_$vid]
+	global $var_iemgui_gn_fs
+	set var_iemgui_bcol [concat iemgui_bcol_$vid]
+	global $var_iemgui_bcol
+	set var_iemgui_fcol [concat iemgui_fcol_$vid]
+	global $var_iemgui_fcol
+	set var_iemgui_lcol [concat iemgui_lcol_$vid]
+	global $var_iemgui_lcol
+	
+	iemgui_clip_dim $id
+	iemgui_clip_num $id
+	iemgui_sched_rng $id
+	iemgui_verify_rng $id
+	iemgui_sched_rng $id
+	iemgui_clip_fontsize $id
+	
+	if {[eval concat $$var_iemgui_snd] == ""} {set hhhsnd "empty"} else {set hhhsnd [eval concat $$var_iemgui_snd]}
+	if {[eval concat $$var_iemgui_rcv] == ""} {set hhhrcv "empty"} else {set hhhrcv [eval concat $$var_iemgui_rcv]}
+	if {[eval concat $$var_iemgui_gui_nam] == ""} {set hhhgui_nam "empty"
+	} else {
+	    set hhhgui_nam [eval concat $$var_iemgui_gui_nam]}
+
+	if {[string index $hhhsnd 0] == "$"} {
+	    set hhhsnd [string replace $hhhsnd 0 0 #] }
+	if {[string index $hhhrcv 0] == "$"} {
+	    set hhhrcv [string replace $hhhrcv 0 0 #] }
+	if {[string index $hhhgui_nam 0] == "$"} {
+	    set hhhgui_nam [string replace $hhhgui_nam 0 0 #] }
+	
+	set hhhsnd [pdtk_unspace $hhhsnd]
+	set hhhrcv [pdtk_unspace $hhhrcv]
+	set hhhgui_nam [pdtk_unspace $hhhgui_nam]
 
-# make sure the offset boxes have a value
+	# make sure the offset boxes have a value
     if {[eval concat $$var_iemgui_gn_dx] eq ""} {set $var_iemgui_gn_dx 0}
     if {[eval concat $$var_iemgui_gn_dy] eq ""} {set $var_iemgui_gn_dy 0}
 
-    pd [concat $id dialog \
-            [eval concat $$var_iemgui_wdt] \
-            [eval concat $$var_iemgui_hgt] \
-            [eval concat $$var_iemgui_min_rng] \
-            [eval concat $$var_iemgui_max_rng] \
-            [eval concat $$var_iemgui_lin0_log1] \
-            [eval concat $$var_iemgui_loadbang] \
-            [eval concat $$var_iemgui_num] \
-            $hhhsnd \
-            $hhhrcv \
-            $hhhgui_nam \
-            [eval concat $$var_iemgui_gn_dx] \
-            [eval concat $$var_iemgui_gn_dy] \
-            [eval concat $$var_iemgui_gn_f] \
-            [eval concat $$var_iemgui_gn_fs] \
-            [eval concat $$var_iemgui_bcol] \
-            [eval concat $$var_iemgui_fcol] \
-            [eval concat $$var_iemgui_lcol] \
-            [eval concat $$var_iemgui_steady] \
-            \;]
+	pd [concat $id dialog \
+	        [eval concat $$var_iemgui_wdt] \
+	        [eval concat $$var_iemgui_hgt] \
+	        [eval concat $$var_iemgui_min_rng] \
+	        [eval concat $$var_iemgui_max_rng] \
+	        [eval concat $$var_iemgui_lin0_log1] \
+	        [eval concat $$var_iemgui_loadbang] \
+	        [eval concat $$var_iemgui_num] \
+	        $hhhsnd \
+	        $hhhrcv \
+	        $hhhgui_nam \
+	        [eval concat $$var_iemgui_gn_dx] \
+	        [eval concat $$var_iemgui_gn_dy] \
+	        [eval concat $$var_iemgui_gn_f] \
+	        [eval concat $$var_iemgui_gn_fs] \
+	        [eval concat $$var_iemgui_bcol] \
+	        [eval concat $$var_iemgui_fcol] \
+	        [eval concat $$var_iemgui_lcol] \
+	        [eval concat $$var_iemgui_steady] \
+	        \;]
+}
+
+proc iemgui_cancel {id} {
+	global color_applied
+	if {$color_applied > -1 && [winfo exists .color_dlg]} {
+		destroy .color_dlg
+		set color_applied -1
+	}	
+	pd [concat $id cancel \;]
 }
 
-proc iemgui_cancel {id} {pd [concat $id cancel \;]}
-
 proc iemgui_ok {id} {
     iemgui_apply $id
     iemgui_cancel $id
@@ -3105,6 +3970,7 @@ proc pdtk_iemgui_dialog {id mainheader \
                              bcol fcol lcol} {
 
     set vid [string trimleft $id .]
+
     global pd_nt
     global fontname fontweight
 
@@ -3186,42 +4052,47 @@ proc pdtk_iemgui_dialog {id mainheader \
     set $var_iemgui_gn_dx $gn_dx
     set $var_iemgui_gn_dy $gn_dy
     set $var_iemgui_gn_f $gn_f
-    set $var_iemgui_gn_fs $gn_fs
-    
+	set $var_iemgui_gn_fs $gn_fs 
+
     set $var_iemgui_bcol $bcol
     set $var_iemgui_fcol $fcol
     set $var_iemgui_lcol $lcol
     
     set $var_iemgui_l2_f1_b0 0
 
-    toplevel $id -class DialogWindow
+    toplevel $id
     wm title $id [format "%s Properties" $mainheader]
+	match_linux_wm [list $id configure]
     wm resizable $id 0 0
+	global tmp_xpix tmp_ypix
+	wm geometry $id "+$tmp_xpix+$tmp_ypix"
     wm protocol $id WM_DELETE_WINDOW [concat iemgui_cancel $id]
     
     pdtk_panelkeybindings $id "iemgui"
 
-    frame $id.dim
+    match_linux_wm [list frame $id.dim]
     pack $id.dim -side top
-    label $id.dim.head -text $dim_header
-    label $id.dim.w_lab -text $wdt_label -width 6
-    entry $id.dim.w_ent -textvariable $var_iemgui_wdt -width 5
-    label $id.dim.dummy1 -text " " -width 10
-    label $id.dim.h_lab -text $hgt_label -width 6
-    entry $id.dim.h_ent -textvariable $var_iemgui_hgt -width 5
+    match_linux_wm [list label $id.dim.head -text $dim_header]
+    match_linux_wm [list label $id.dim.w_lab -text $wdt_label -width 6]
+    match_linux_wm [list entry $id.dim.w_ent -textvariable $var_iemgui_wdt -width 5]
+    match_linux_wm [list label $id.dim.dummy1 -text " " -width 10]
+    match_linux_wm [list label $id.dim.h_lab -text $hgt_label -width 6]
+    match_linux_wm [list entry $id.dim.h_ent -textvariable $var_iemgui_hgt -width 5]
     pack $id.dim.head -side top
     pack $id.dim.w_lab $id.dim.w_ent $id.dim.dummy1 -side left
     if { $hgt_label != "empty" } {
         pack $id.dim.h_lab $id.dim.h_ent -side left}
 
-    frame $id.rng
+    match_linux_wm [list frame $id.rng]
     pack $id.rng -side top
-    label $id.rng.head -text $rng_header
-    label $id.rng.min_lab -text $min_rng_label -width 6
-    entry $id.rng.min_ent -textvariable $var_iemgui_min_rng -width 9
-    label $id.rng.dummy1 -text " " -width 1
-    label $id.rng.max_lab -text $max_rng_label -width 8
-    entry $id.rng.max_ent -textvariable $var_iemgui_max_rng -width 9
+    match_linux_wm [list label $id.rng.head -text $rng_header]
+    match_linux_wm [list label $id.rng.min_lab -text $min_rng_label -width 6]
+    match_linux_wm [list entry $id.rng.min_ent \
+		-textvariable $var_iemgui_min_rng -width 9]
+    match_linux_wm [list label $id.rng.dummy1 -text " " -width 1]
+    match_linux_wm [list label $id.rng.max_lab -text $max_rng_label -width 8]
+    match_linux_wm [list entry $id.rng.max_ent \
+		-textvariable $var_iemgui_max_rng -width 9]
     if { $rng_header != "empty" } {
         pack $id.rng.head -side top
         if { $min_rng_label != "empty" } {
@@ -3231,27 +4102,40 @@ proc pdtk_iemgui_dialog {id mainheader \
                 $id.rng.max_lab $id.rng.max_ent -side left} }
     
     if { [eval concat $$var_iemgui_lin0_log1] >= 0 || [eval concat $$var_iemgui_loadbang] >= 0 || [eval concat $$var_iemgui_num] > 0 || [eval concat $$var_iemgui_steady] >= 0 } {
-        label $id.space1 -text ""
+        match_linux_wm [list label $id.space1 -text ""]
         pack $id.space1 -side top }
 
-    frame $id.para
+    match_linux_wm [list frame $id.para]
     pack $id.para -side top
-    label $id.para.dummy2 -text "" -width 1
-    label $id.para.dummy3 -text "" -width 1
+    match_linux_wm [list label $id.para.dummy2 -text "" -width 1]
+    match_linux_wm [list label $id.para.dummy3 -text "" -width 1]
     if {[eval concat $$var_iemgui_lin0_log1] == 0} {
-        button $id.para.lilo -text [eval concat $$var_iemgui_lilo0] -width 5 -command "iemgui_lilo $id" }
+		match_linux_wm [list button $id.para.lilo -text [eval concat \
+			$$var_iemgui_lilo0] -width 7 -command "iemgui_lilo $id"]
+	}
     if {[eval concat $$var_iemgui_lin0_log1] == 1} {
-        button $id.para.lilo -text [eval concat $$var_iemgui_lilo1] -width 5 -command "iemgui_lilo $id" }
+		match_linux_wm [list button $id.para.lilo -text [eval concat \
+			$$var_iemgui_lilo1] -width 7 -command "iemgui_lilo $id"]
+	}
     if {[eval concat $$var_iemgui_loadbang] == 0} {
-        button $id.para.lb -text "no init" -width 5 -command "iemgui_lb $id" }
+		match_linux_wm [list button $id.para.lb -text "no init" \
+			-width 6 -command "iemgui_lb $id"]
+	}
     if {[eval concat $$var_iemgui_loadbang] == 1} {
-        button $id.para.lb -text "init" -width 5 -command "iemgui_lb $id" }
-    label $id.para.num_lab -text $num_label -width 9
-    entry $id.para.num_ent -textvariable $var_iemgui_num -width 4
+		match_linux_wm [list button $id.para.lb -text "init" \
+			-width 6 -command "iemgui_lb $id"]
+	}
+    match_linux_wm [list label $id.para.num_lab -text $num_label -width 9]
+    match_linux_wm [list entry $id.para.num_ent \
+		-textvariable $var_iemgui_num -width 4]
     if {[eval concat $$var_iemgui_steady] == 0} {
-        button $id.para.stdy_jmp -text "jump on click" -width 11 -command "iemgui_stdy_jmp $id" }
+        match_linux_wm [list button $id.para.stdy_jmp \
+			-text "jump on click" -width 12 -command "iemgui_stdy_jmp $id"]
+	}
     if {[eval concat $$var_iemgui_steady] == 1} {
-        button $id.para.stdy_jmp -text "steady on click" -width 11 -command "iemgui_stdy_jmp $id" }
+        match_linux_wm [list button $id.para.stdy_jmp \
+			-text "steady on click" -width 12 -command "iemgui_stdy_jmp $id"]
+	}
     if {[eval concat $$var_iemgui_lin0_log1] >= 0} {
         pack $id.para.lilo -side left -expand 1}
     if {[eval concat $$var_iemgui_loadbang] >= 0} {
@@ -3261,26 +4145,31 @@ proc pdtk_iemgui_dialog {id mainheader \
     if {[eval concat $$var_iemgui_steady] >= 0} {
         pack $id.para.dummy3 $id.para.stdy_jmp -side left -expand 1}
 
-    frame $id.spacer0 -height 4
+    match_linux_wm [list frame $id.spacer0 -height 4]
     pack $id.spacer0 -side top
     
-    labelframe $id.s_r -borderwidth 1 -pady 4 -text "messages" \
-        -font highlight_font
-    pack $id.s_r -side top -fill x -ipadx 5
-    frame $id.s_r.send
+    match_linux_wm [list labelframe $id.s_r \
+		-borderwidth 1 -pady 3 -padx 3 -text "messages" \
+        -font highlight_font]
+    pack $id.s_r -side top -fill x -padx 3 -ipadx 3 -ipady 3
+    match_linux_wm [list frame $id.s_r.send]
     pack $id.s_r.send -side top
-    label $id.s_r.send.lab -text "   send-symbol:" -width 12  -justify right
-    entry $id.s_r.send.ent -textvariable $var_iemgui_snd -width 22
+    match_linux_wm [list label $id.s_r.send.lab \
+		-text "   send-symbol:" -width 12  -justify right]
+    match_linux_wm [list entry $id.s_r.send.ent \
+		-textvariable $var_iemgui_snd -width 22]
     if { $snd != "nosndno" } {
-        pack $id.s_r.send.lab $id.s_r.send.ent -side left}
-    
-    frame $id.s_r.receive
+        pack $id.s_r.send.lab $id.s_r.send.ent -side left -pady 3
+	}    
+    match_linux_wm [list frame $id.s_r.receive]
     pack $id.s_r.receive -side top
-    label $id.s_r.receive.lab -text "receive-symbol:" -width 12 -justify right
-    entry $id.s_r.receive.ent -textvariable $var_iemgui_rcv -width 22
+    match_linux_wm [list label $id.s_r.receive.lab \
+		-text "receive-symbol:" -width 12 -justify right]
+    match_linux_wm [list entry $id.s_r.receive.ent \
+		-textvariable $var_iemgui_rcv -width 22]
     if { $rcv != "norcvno" } {
-        pack $id.s_r.receive.lab $id.s_r.receive.ent -side left}
-    
+        pack $id.s_r.receive.lab $id.s_r.receive.ent -side left
+	}    
     # get the current font name from the int given from C-space (gn_f)
     set current_font $fontname
     if {[eval concat $$var_iemgui_gn_f] == 1} \
@@ -3288,63 +4177,68 @@ proc pdtk_iemgui_dialog {id mainheader \
     if {[eval concat $$var_iemgui_gn_f] == 2} \
         { set current_font "Times" }
 
-    frame $id.spacer1 -height 7
+    match_linux_wm [list frame $id.spacer1 -height 7]
     pack $id.spacer1 -side top
     
-    labelframe $id.label -borderwidth 1 -text "label" -pady 4 \
-        -font highlight_font
-    pack $id.label -side top -fill x
-    entry $id.label.name_entry -textvariable $var_iemgui_gui_nam -width 30 \
-        -font [list $current_font 12 $fontweight]
-    pack $id.label.name_entry -side top -expand yes -fill both -padx 5
+    match_linux_wm [list labelframe $id.label \
+		-borderwidth 1 -text "label" -pady 3 -padx 3 \
+        -font highlight_font]
+    pack $id.label -side top -fill x -padx 3 -ipadx 3 -ipady 3
+    match_linux_wm [list entry $id.label.name_entry \
+		-textvariable $var_iemgui_gui_nam -width 30 \
+        -font [list $current_font 9 $fontweight]]
+    pack $id.label.name_entry -side top -expand yes -fill both -padx 5 -pady 3
     
-    frame $id.label.xy -padx 27 -pady 1
+    match_linux_wm [list frame $id.label.xy -padx 27 -pady 1]
     pack $id.label.xy -side top
-    label $id.label.xy.x_lab -text "x offset" -width 6
-    entry $id.label.xy.x_entry -textvariable $var_iemgui_gn_dx -width 5
-    label $id.label.xy.dummy1 -text " " -width 2
-    label $id.label.xy.y_lab -text "y offset" -width 6
-    entry $id.label.xy.y_entry -textvariable $var_iemgui_gn_dy -width 5
+    match_linux_wm [list label $id.label.xy.x_lab -text "x offset" -width 6]
+    match_linux_wm [list entry $id.label.xy.x_entry \
+		-textvariable $var_iemgui_gn_dx -width 5]
+    match_linux_wm [list label $id.label.xy.dummy1 -text " " -width 2]
+    match_linux_wm [list label $id.label.xy.y_lab -text "y offset" -width 6]
+    match_linux_wm [list entry $id.label.xy.y_entry \
+		-textvariable $var_iemgui_gn_dy -width 5]
     pack $id.label.xy.x_lab $id.label.xy.x_entry $id.label.xy.dummy1 \
         $id.label.xy.y_lab $id.label.xy.y_entry -side left -anchor e
-    
-    label $id.label.fontpopup_label -text $current_font \
-        -relief groove -font [list $current_font 12 $fontweight] -padx 5
-    pack $id.label.fontpopup_label -side left -anchor w -expand yes -fill x
-    label $id.label.fontsize_label -text "size" -width 4
-    entry $id.label.fontsize_entry -textvariable $var_iemgui_gn_fs -width 5
+    match_linux_wm [list label $id.label.fontpopup_label -text $current_font \
+    	-relief groove -font [list $current_font 9 $fontweight]]
+    pack $id.label.fontpopup_label -side left -anchor w -expand yes -fill x -padx 3
+    match_linux_wm [list label $id.label.fontsize_label -text "size" -width 4]
+    match_linux_wm [list entry $id.label.fontsize_entry \
+		-textvariable $var_iemgui_gn_fs -width 5]
     pack $id.label.fontsize_entry $id.label.fontsize_label \
-        -side right -anchor e -padx 5 -pady 5
-    menu $id.popup
+        -side right -anchor e -padx 5 -pady 3
+    match_linux_wm [list menu $id.popup -tearoff 0]
     $id.popup add command \
         -label $fontname \
-        -font [format {{%s} 12 %s} $fontname $fontweight] \
-        -command "iemgui_toggle_font $id 0" 
+        -font [format {{%s} 9 %s} $fontname $fontweight] \
+        -command "iemgui_toggle_font $id 0"
     $id.popup add command \
         -label "Helvetica" \
-        -font [format {Helvetica 12 %s} $fontweight] \
+        -font [format {Helvetica 9 %s} $fontweight] \
         -command "iemgui_toggle_font $id 1" 
     $id.popup add command \
         -label "Times" \
-        -font [format {Times 12 %s} $fontweight] \
+        -font [format {Times 9 %s} $fontweight] \
         -command "iemgui_toggle_font $id 2" 
     bind $id.label.fontpopup_label <Button> \
         [list tk_popup $id.popup %X %Y]
 
-    frame $id.spacer2 -height 7
+    match_linux_wm [list frame $id.spacer2 -height 7]
     pack $id.spacer2 -side top
     
-    labelframe $id.colors -borderwidth 1 -text "colors" -font highlight_font
-    pack $id.colors -fill x -ipadx 5 -ipady 4
+    match_linux_wm [list labelframe $id.colors -borderwidth 1 \
+		-text "colors" -font highlight_font -padx 3]
+    pack $id.colors -fill x -padx 3 -pady 3 -ipadx 3 -ipady 3
     
-    frame $id.colors.select
+    match_linux_wm [list frame $id.colors.select]
     pack $id.colors.select -side top
-    radiobutton $id.colors.select.radio0 -value 0 -variable \
-        $var_iemgui_l2_f1_b0 -text "background" -width 10 -justify left
-    radiobutton $id.colors.select.radio1 -value 1 -variable \
-        $var_iemgui_l2_f1_b0 -text "front" -width 5 -justify left
-    radiobutton $id.colors.select.radio2 -value 2 -variable \
-        $var_iemgui_l2_f1_b0 -text "label" -width 5 -justify left
+    match_linux_wm [list radiobutton $id.colors.select.radio0 -value 0 -variable \
+        $var_iemgui_l2_f1_b0 -text "background" -width 10]
+    match_linux_wm [list radiobutton $id.colors.select.radio1 -value 1 -variable \
+        $var_iemgui_l2_f1_b0 -text "front" -width 5]
+    match_linux_wm [list radiobutton $id.colors.select.radio2 -value 2 -variable \
+        $var_iemgui_l2_f1_b0 -text "label" -width 5]
     if { [eval concat $$var_iemgui_fcol] >= 0 } {
         pack $id.colors.select.radio0 $id.colors.select.radio1 \
             $id.colors.select.radio2 -side left
@@ -3352,44 +4246,47 @@ proc pdtk_iemgui_dialog {id mainheader \
         pack $id.colors.select.radio0 $id.colors.select.radio2 -side left \
         }
     
-    frame $id.colors.sections
+    match_linux_wm [list frame $id.colors.sections]
     pack $id.colors.sections -side top
-    button $id.colors.sections.but -text "compose color" -width 12 \
-        -command "iemgui_choose_col_bkfrlb $id"
-    pack $id.colors.sections.but -side left -anchor w -padx 10 -pady 5 \
+	# disabled until we can get themeable chooseColor dialog    
+	match_linux_wm [list button $id.colors.sections.but -text "Compose Color" \
+		-width 12 -command "iemgui_choose_col_bkfrlb $id" -underline 5]
+    pack $id.colors.sections.but -side left -anchor w -padx 3 -pady 5 \
         -expand yes -fill x
+	bind $id <Alt-KeyPress-s> [format "iemgui_choose_col_bkfrlb %s" $id]
     if { [eval concat $$var_iemgui_fcol] >= 0 } {
-        label $id.colors.sections.fr_bk -text "o=||=o" -width 6 \
+        match_linux_wm [list label $id.colors.sections.fr_bk -text "o=||=o" -width 6 \
             -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
             -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
             -foreground [format "#%6.6x" [eval concat $$var_iemgui_fcol]] \
             -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_fcol]] \
-            -font [list $current_font 12 $fontweight] -padx 2 -pady 2 -relief ridge
+            -font [list $current_font 9 $fontweight] -padx 2 -pady 2 -relief ridge]
     } else {
-        label $id.colors.sections.fr_bk -text "o=||=o" -width 6 \
+        match_linux_wm [list label $id.colors.sections.fr_bk -text "o=||=o" -width 6 \
             -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
             -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
             -foreground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
             -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
-            -font [list $current_font 12 $fontweight] -padx 2 -pady 2 -relief ridge
+            -font [list $current_font 9 $fontweight] -padx 2 -pady 2 -relief ridge]
     }
-    label $id.colors.sections.lb_bk -text "testlabel" -width 9 \
+    match_linux_wm [list label $id.colors.sections.lb_bk -text "testlabel" -width 9 \
         -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
         -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
         -foreground [format "#%6.6x" [eval concat $$var_iemgui_lcol]] \
         -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_lcol]] \
-        -font [list $current_font 12 $fontweight] -padx 2 -pady 2 -relief ridge
+        -font [list $current_font 9 $fontweight] -padx 2 -pady 2 -relief ridge]
     pack $id.colors.sections.lb_bk $id.colors.sections.fr_bk \
-        -side right -anchor e -expand yes -fill both -pady 7
+        -side right -anchor e -expand yes -fill both -pady 7 -padx 3
 
     # color scheme by Mary Ann Benedetto http://piR2.org
-    frame $id.colors.r1
+    match_linux_wm [list frame $id.colors.r1]
     pack $id.colors.r1 -side top
-    foreach i { 0 1 2 3 4 5 6 7 8 9} \
+    foreach i { 0 1 2 3 4 5 6 7 8 9 } \
         hexcol { 0xFFFFFF 0xDFDFDF 0xBBBBBB 0xFFC7C6 0xFFE3C6 \
                      0xFEFFC6 0xC6FFC7 0xc6FEFF 0xC7C6FF 0xE3C6FF } \
         {
-            label $id.colors.r1.c$i -background [format "#%6.6x" $hexcol] \
+            label $id.colors.r1.c$i \
+				-background [format "#%6.6x" $hexcol] \
                 -activebackground [format "#%6.6x" $hexcol] -relief ridge \
                 -padx 7 -pady 0
             bind $id.colors.r1.c$i <Button> [format "iemgui_preset_col %s %d" $id $hexcol] 
@@ -3398,13 +4295,14 @@ proc pdtk_iemgui_dialog {id mainheader \
         $id.colors.r1.c4 $id.colors.r1.c5 $id.colors.r1.c6 $id.colors.r1.c7 \
         $id.colors.r1.c8 $id.colors.r1.c9 -side left
     
-    frame $id.colors.r2
+    match_linux_wm [list frame $id.colors.r2]
     pack $id.colors.r2 -side top
     foreach i { 0 1 2 3 4 5 6 7 8 9 } \
         hexcol { 0x9F9F9F 0x7C7C7C 0x606060 0xFF0400 0xFF8300 \
                      0xFAFF00 0x00FF04 0x00FAFF 0x0400FF 0x9C00FF } \
         {
-            label $id.colors.r2.c$i -background [format "#%6.6x" $hexcol] \
+            label $id.colors.r2.c$i \
+				-background [format "#%6.6x" $hexcol] \
                 -activebackground [format "#%6.6x" $hexcol] -relief ridge \
                 -padx 7 -pady 0
             bind  $id.colors.r2.c$i <Button> \
@@ -3414,13 +4312,14 @@ proc pdtk_iemgui_dialog {id mainheader \
         $id.colors.r2.c4 $id.colors.r2.c5 $id.colors.r2.c6 $id.colors.r2.c7 \
         $id.colors.r2.c8 $id.colors.r2.c9 -side left
     
-    frame $id.colors.r3
+    match_linux_wm [list frame $id.colors.r3]
     pack $id.colors.r3 -side top
     foreach i { 0 1 2 3 4 5 6 7 8 9 } \
         hexcol { 0x404040 0x202020 0x000000 0x551312 0x553512 \
                      0x535512 0x0F4710 0x0E4345 0x131255 0x2F004D } \
         {
-            label $id.colors.r3.c$i -background [format "#%6.6x" $hexcol] \
+            label $id.colors.r3.c$i \
+				-background [format "#%6.6x" $hexcol] \
                 -activebackground [format "#%6.6x" $hexcol] -relief ridge \
                 -padx 7 -pady 0
             bind  $id.colors.r3.c$i <Button> \
@@ -3430,38 +4329,41 @@ proc pdtk_iemgui_dialog {id mainheader \
         $id.colors.r3.c4 $id.colors.r3.c5 $id.colors.r3.c6 $id.colors.r3.c7 \
         $id.colors.r3.c8 $id.colors.r3.c9 -side left
     
-    frame $id.cao -pady 10
+    match_linux_wm [list frame $id.cao -pady 3]
     pack $id.cao -side top
-    button $id.cao.cancel -text {Cancel} -width 6 \
-        -command "iemgui_cancel $id"
-    label $id.cao.dummy1 -text "" -width 3
-    button $id.cao.apply -text {Apply} -width 6 -command "iemgui_apply $id"
-    label $id.cao.dummy2 -text "" -width 3
-    button $id.cao.ok -text {OK} -width 6 \
-        -command "iemgui_ok $id"
+    match_linux_wm [list button $id.cao.cancel -text {Cancel} -width 6 \
+        -command "iemgui_cancel $id"]
+    match_linux_wm [list label $id.cao.dummy1 -text "" -width 3]
+    match_linux_wm [list button $id.cao.apply -text {Apply} \
+		-width 6 -command "iemgui_apply $id"]
+    match_linux_wm [list label $id.cao.dummy2 -text "" -width 3]
+    match_linux_wm [list button $id.cao.ok -text {OK} -width 6 \
+        -command "iemgui_ok $id"]
     
     pack $id.cao.cancel $id.cao.dummy1 -side left
     pack $id.cao.apply $id.cao.dummy2 -side left
     pack $id.cao.ok -side left
 
- #   if {[info tclversion] < 8.4} {
- #       bind $id <Key-Tab> {tkTabToWindow [tk_focusNext %W]}
- #       bind $id <<PrevWindow>> {tkTabToWindow [tk_focusPrev %W]}
- #   } else {
- #       bind $id <Key-Tab> {tk::TabToWindow [tk_focusNext %W]}
- #       bind $id <<PrevWindow>> {tk::TabToWindow [tk_focusPrev %W]}
- #   }
-    
-#    $id.dim.w_ent select from 0
-#    $id.dim.w_ent select adjust end
-#    focus $id.dim.w_ent
+    if {[info tclversion] < 8.4} {
+        bind $id <Key-Tab> {tkTabToWindow [tk_focusNext %W]}
+        bind $id <<PrevWindow>> {tkTabToWindow [tk_focusPrev %W]}
+    } else {
+        bind $id <Key-Tab> {tk::TabToWindow [tk_focusNext %W]}
+        bind $id <<PrevWindow>> {tk::TabToWindow [tk_focusPrev %W]}
+    }
+
+	if { [info tclversion] < 8.5 } {
+    	$id.dim.w_ent select from 0
+    	$id.dim.w_ent select adjust end  
+	}
+	focus $id.dim.w_ent
 }
 # end of change "iemlib"
 
 ############ pdtk_array_dialog -- dialog window for arrays #########
 # see comments above (pdtk_gatom_dialog) about variable name handling 
 
-proc array_apply {id} {
+proc array_apply {id canvas} {
     # strip "." from the TK id to make a variable name suffix 
     set vid [string trimleft $id .]
     # for each variable, make a local variable to hold its name...
@@ -3482,10 +4384,15 @@ proc array_apply {id} {
     set saveit [eval concat $$var_array_saveit]
     set drawasrects [eval concat $$var_array_drawasrects]
 
+	set xdraw [expr int([$canvas.c canvasx 0])]
+	set ydraw [expr int([$canvas.c canvasy 0])]
+
     pd [concat $id arraydialog $mofo \
             [eval concat $$var_array_n] \
             [expr $saveit + 2 * $drawasrects] \
             [eval concat $$var_array_otherflag] \
+			$xdraw \
+			$ydraw \
             \;]
 }
 
@@ -3500,12 +4407,12 @@ proc array_cancel {id} {
     pd $cmd
 }
 
-proc array_ok {id} {
-    array_apply $id
+proc array_ok {id canvas} {
+    array_apply $id $canvas
     array_cancel $id
 }
 
-proc pdtk_array_dialog {id name n flags newone} {
+proc pdtk_array_dialog {id name n flags newone canvas} {
     set vid [string trimleft $id .]
 
     set var_array_name [concat array_name_$vid]
@@ -3525,81 +4432,90 @@ proc pdtk_array_dialog {id name n flags newone} {
     set $var_array_drawasrects [expr ( $flags & 2 ) != 0]
     set $var_array_otherflag 0
 
-    toplevel $id -class DialogWindow
-    wm title $id {array}
+    toplevel $id
+    wm title $id {Edit Array}
+	match_linux_wm [list $id configure]
     wm resizable $id 0 0
+	global pointer_x_global pointer_y_global
+	wm geometry $id "+[expr $pointer_x_global+50]+[expr $pointer_y_global-12]"
+	wm attributes $id -topmost 1
     wm protocol $id WM_DELETE_WINDOW [concat array_cancel $id]
 
     pdtk_panelkeybindings $id "array"
 
-    frame $id.name
-    pack $id.name -side top
-    label $id.name.label -text "name"
-    entry $id.name.entry -textvariable $var_array_name
-    pack $id.name.label $id.name.entry -side left
+    match_linux_wm [list frame $id.name]
+    pack $id.name -side top -pady 3
+    match_linux_wm [list label $id.name.label -text "name"]
+    match_linux_wm [list entry $id.name.entry -textvariable $var_array_name]
+    pack $id.name.label $id.name.entry -side left -padx 3 -pady 3
 
-    frame $id.n
+    match_linux_wm [list frame $id.n]
     pack $id.n -side top
-    label $id.n.label -text "size"
-    entry $id.n.entry -textvariable $var_array_n
-    pack $id.n.label $id.n.entry -side left
+    match_linux_wm [list label $id.n.label -text "   size"]
+    match_linux_wm [list entry $id.n.entry -textvariable $var_array_n]
+    pack $id.n.label $id.n.entry -side left -padx 3
 
-    checkbutton $id.saveme -text {save contents} -variable $var_array_saveit \
-        -anchor w
-    pack $id.saveme -side top
+    match_linux_wm [list checkbutton $id.saveme -text {save contents} \
+		-variable $var_array_saveit]
+    pack $id.saveme -side top -pady 3
 
-    frame $id.drawasrects
-    pack $id.drawasrects -side top
-    radiobutton $id.drawasrects.drawasrects0 -value 0 \
+    match_linux_wm [list frame $id.drawasrects]
+    pack $id.drawasrects -side top -pady 3
+    match_linux_wm [list radiobutton $id.drawasrects.drawasrects0 -value 0 \
         -variable $var_array_drawasrects \
-        -text "draw as points"
-    radiobutton $id.drawasrects.drawasrects1 -value 1 \
+        -text "draw as points"]
+    match_linux_wm [list radiobutton $id.drawasrects.drawasrects1 -value 1 \
         -variable $var_array_drawasrects \
-        -text "polygon"
-    radiobutton $id.drawasrects.drawasrects2 -value 2 \
+        -text "polygon"]
+    match_linux_wm [list radiobutton $id.drawasrects.drawasrects2 -value 2 \
         -variable $var_array_drawasrects \
-        -text "bezier curve"
-    pack $id.drawasrects.drawasrects0 -side top -anchor w
-    pack $id.drawasrects.drawasrects1 -side top -anchor w
-    pack $id.drawasrects.drawasrects2 -side top -anchor w
-
-    if {$newone != 0} {
-        frame $id.radio
-        pack $id.radio -side top
-        radiobutton $id.radio.radio0 -value 0 \
+        -text "bezier curve"]
+    pack $id.drawasrects.drawasrects0 -side top
+    pack $id.drawasrects.drawasrects1 -side top
+    pack $id.drawasrects.drawasrects2 -side top
+
+    if {$newone != 0} { 
+        match_linux_wm [list frame $id.radio]
+        pack $id.radio -side top -pady 3
+        match_linux_wm [list radiobutton $id.radio.radio0 -value 0 \
             -variable $var_array_otherflag \
-            -text "in new graph"
-        radiobutton $id.radio.radio1 -value 1 \
+            -text "in new graph"]
+        match_linux_wm [list radiobutton $id.radio.radio1 -value 1 \
             -variable $var_array_otherflag \
-            -text "in last graph"
-        pack $id.radio.radio0 -side top -anchor w
-        pack $id.radio.radio1 -side top -anchor w
-    } else {    
-        checkbutton $id.deleteme -text {delete me} \
-            -variable $var_array_otherflag -anchor w
+            -text "in last graph"]
+        pack $id.radio.radio0 -side top
+        pack $id.radio.radio1 -side top
+    } else {
+        match_linux_wm [list checkbutton $id.deleteme -text {delete me} \
+            -variable $var_array_otherflag]
         pack $id.deleteme -side top
     }
     # jsarlo
-    if {$newone == 0} {
-      button $id.listview -text {View list}\
-        -command "array_viewlist $id"
-      pack $id.listview -side left
-    }
+    # if {$newone == 0} {
+    #    match_linux_wm [list button $id.listview -text {View list}\
+    #        -command "array_viewlist $id $name 0"]
+    #    pack $id.listview -side left
+    #}
     # end jsarlo
-    frame $id.buttonframe
-    pack $id.buttonframe -side bottom -fill x -pady 2m
-    button $id.buttonframe.cancel -text {Cancel}\
-        -command "array_cancel $id"
-    if {$newone == 0} {button $id.buttonframe.apply -text {Apply}\
-        -command "array_apply $id"}
-    button $id.buttonframe.ok -text {OK}\
-        -command "array_ok $id"
-    pack $id.buttonframe.cancel -side left -expand 1
-    if {$newone == 0} {pack $id.buttonframe.apply -side left -expand 1}
-    pack $id.buttonframe.ok -side left -expand 1
+    match_linux_wm [list frame $id.buttonframe]
+    pack $id.buttonframe -side bottom -fill x
+    match_linux_wm [list button $id.buttonframe.cancel -text {Cancel}\
+        -command "array_cancel $id"]
+    if {$newone == 0} {
+		match_linux_wm [list button \
+			$id.buttonframe.apply -text {Apply} \
+            -command "array_apply $id $canvas"]
+	}
+    match_linux_wm [list button $id.buttonframe.ok -text {OK} \
+        -command "array_ok $id $canvas"]
+    pack $id.buttonframe.cancel -side left -expand 1 -pady 3 -padx 3
+    if {$newone == 0} {pack $id.buttonframe.apply -side left -expand 1 -pady 3 -padx 3}
+    pack $id.buttonframe.ok -side left -expand 1 -pady 3 -padx 3
     
-    $id.name.entry select from 0
-    $id.name.entry select adjust end
+	if { [info tclversion] < 8.5 } {
+    	$id.name.entry select from 0
+    	$id.name.entry select adjust end
+	}
     focus $id.name.entry
 }
 
@@ -3739,6 +4655,9 @@ proc canvas_checkcommand {id} {
         if { [eval concat $$var_canvas_yscale] == 0 } {
             set $var_canvas_yscale -1
         }
+        if { [eval concat $$var_canvas_hidetext] == 1 } {
+            set $var_canvas_hidetext 0
+        }
     }
 }
 
@@ -3784,83 +4703,102 @@ proc pdtk_canvas_dialog {id xscale yscale graphme x1 y1 x2 y2 \
     set $var_canvas_xmargin $xmargin
     set $var_canvas_ymargin $ymargin
 
-    toplevel $id -class DialogWindow
-    wm title $id {canvas}
+    toplevel $id
+    wm title $id {Canvas Properties}
+	match_linux_wm [list $id configure]
+	wm resizable $id 0 0
+	global tmp_xpix tmp_ypix
+	wm geometry $id "+$tmp_xpix+$tmp_ypix"
     wm protocol $id WM_DELETE_WINDOW [concat canvas_cancel $id]
 
+
     pdtk_panelkeybindings $id "canvas"
 
-    label $id.toplabel -text "Canvas Properties"
-    pack $id.toplabel -side top
+	#superfluous repetition of window title information
+	#match_linux_wm [list label $id.toplabel -text "Canvas Properties"]
+    #pack $id.toplabel -side top
     
-    frame $id.xscale
-    pack $id.xscale -side top
-    label $id.xscale.label -text "X units per pixel"
-    entry $id.xscale.entry -textvariable $var_canvas_xscale -width 10
-    pack $id.xscale.label $id.xscale.entry -side left
-
-    frame $id.yscale
+    match_linux_wm [list frame $id.xscale]
+    pack $id.xscale -side top -pady 3
+    match_linux_wm [list label $id.xscale.label -text "X units per pixel"]
+    match_linux_wm [list entry $id.xscale.entry \
+		-textvariable $var_canvas_xscale -width 10]
+    pack $id.xscale.label $id.xscale.entry -side left -pady 3 -padx 3
+
+    match_linux_wm [list frame $id.yscale]
     pack $id.yscale -side top
-    label $id.yscale.label -text "Y units per pixel"
-    entry $id.yscale.entry -textvariable $var_canvas_yscale -width 10
-    pack $id.yscale.label $id.yscale.entry -side left
-
-    checkbutton $id.graphme -text {graph on parent} \
-        -variable $var_canvas_graphme -anchor w \
-        -command [concat canvas_checkcommand $id]
+    match_linux_wm [list label $id.yscale.label -text "Y units per pixel"]
+    match_linux_wm [list entry $id.yscale.entry \
+		-textvariable $var_canvas_yscale -width 10]
+    pack $id.yscale.label $id.yscale.entry -side left -padx 3
+
+    match_linux_wm [list checkbutton $id.graphme -text {graph on parent} \
+        -variable $var_canvas_graphme \
+        -command [concat canvas_checkcommand $id]]
     pack $id.graphme -side top
 
-    checkbutton $id.hidetext -text {hide object name and arguments} \
-        -variable $var_canvas_hidetext -anchor w \
-        -command [concat canvas_checkcommand $id]
+    match_linux_wm [list checkbutton $id.hidetext \
+		-text {hide object name and arguments} \
+        -variable $var_canvas_hidetext \
+        -command [concat canvas_checkcommand $id]]
     pack $id.hidetext -side top
 
-    frame $id.xrange
+    match_linux_wm [list frame $id.xrange]
     pack $id.xrange -side top
-    label $id.xrange.label1 -text "X range: from"
-    entry $id.xrange.entry1 -textvariable $var_canvas_x1 -width 6
-    label $id.xrange.label2 -text "to"
-    entry $id.xrange.entry2 -textvariable $var_canvas_x2 -width 6
-    label $id.xrange.label3 -text "size"
-    entry $id.xrange.entry3 -textvariable $var_canvas_xpix -width 4
-    label $id.xrange.label4 -text "margin"
-    entry $id.xrange.entry4 -textvariable $var_canvas_xmargin -width 4
+    match_linux_wm [list label $id.xrange.label1 -text "X range: from"]
+    match_linux_wm [list entry $id.xrange.entry1 \
+		-textvariable $var_canvas_x1 -width 6]
+    match_linux_wm [list label $id.xrange.label2 -text "to"]
+    match_linux_wm [list entry $id.xrange.entry2 \
+		-textvariable $var_canvas_x2 -width 6]
+    match_linux_wm [list label $id.xrange.label3 -text "size"]
+    match_linux_wm [list entry $id.xrange.entry3 \
+		-textvariable $var_canvas_xpix -width 4]
+    match_linux_wm [list label $id.xrange.label4 -text "margin"]
+    match_linux_wm [list entry $id.xrange.entry4 \
+		-textvariable $var_canvas_xmargin -width 4]
     pack $id.xrange.label1 $id.xrange.entry1 \
         $id.xrange.label2 $id.xrange.entry2 \
         $id.xrange.label3 $id.xrange.entry3 \
         $id.xrange.label4 $id.xrange.entry4 \
-        -side left
+        -side left -pady 3 -padx 3
 
-    frame $id.yrange
+    match_linux_wm [list frame $id.yrange]
     pack $id.yrange -side top
-    label $id.yrange.label1 -text "Y range: from"
-    entry $id.yrange.entry1 -textvariable $var_canvas_y1 -width 6
-    label $id.yrange.label2 -text "to"
-    entry $id.yrange.entry2 -textvariable $var_canvas_y2 -width 6
-    label $id.yrange.label3 -text "size"
-    entry $id.yrange.entry3 -textvariable $var_canvas_ypix -width 4
-    label $id.yrange.label4 -text "margin"
-    entry $id.yrange.entry4 -textvariable $var_canvas_ymargin -width 4
+    match_linux_wm [list label $id.yrange.label1 -text "Y range: from"]
+    match_linux_wm [list entry $id.yrange.entry1 \
+		-textvariable $var_canvas_y1 -width 6]
+    match_linux_wm [list label $id.yrange.label2 -text "to"]
+    match_linux_wm [list entry $id.yrange.entry2 \
+		-textvariable $var_canvas_y2 -width 6]
+    match_linux_wm [list label $id.yrange.label3 -text "size"]
+    match_linux_wm [list entry $id.yrange.entry3 \
+		-textvariable $var_canvas_ypix -width 4]
+    match_linux_wm [list label $id.yrange.label4 -text "margin"]
+    match_linux_wm [list entry $id.yrange.entry4 \
+		-textvariable $var_canvas_ymargin -width 4]
     pack $id.yrange.label1 $id.yrange.entry1 \
         $id.yrange.label2 $id.yrange.entry2 \
         $id.yrange.label3 $id.yrange.entry3 \
         $id.yrange.label4 $id.yrange.entry4 \
-        -side left
-
-    frame $id.buttonframe
-    pack $id.buttonframe -side bottom -fill x -pady 2m
-    button $id.buttonframe.cancel -text {Cancel}\
-        -command "canvas_cancel $id"
-    button $id.buttonframe.apply -text {Apply}\
-        -command "canvas_apply $id"
-    button $id.buttonframe.ok -text {OK}\
-        -command "canvas_ok $id"
-    pack $id.buttonframe.cancel -side left -expand 1
-    pack $id.buttonframe.apply -side left -expand 1
-    pack $id.buttonframe.ok -side left -expand 1
-
-    $id.xscale.entry select from 0
-    $id.xscale.entry select adjust end
+        -side left -pady 3 -padx 3
+
+    match_linux_wm [list frame $id.buttonframe]
+    pack $id.buttonframe -side bottom -fill x
+    match_linux_wm [list button $id.buttonframe.cancel -text {Cancel}\
+        -command "canvas_cancel $id"]
+    match_linux_wm [list button $id.buttonframe.apply -text {Apply}\
+        -command "canvas_apply $id"]
+    match_linux_wm [list button $id.buttonframe.ok -text {OK}\
+        -command "canvas_ok $id"]
+    pack $id.buttonframe.cancel -side left -expand 1 -pady 3 -padx 3
+    pack $id.buttonframe.apply -side left -expand 1 -pady 3 -padx 3
+    pack $id.buttonframe.ok -side left -expand 1 -pady 3 -padx 3
+
+    if { [info tclversion] < 8.5 } {
+		$id.xscale.entry select from 0
+		$id.xscale.entry select adjust end
+	}
     focus $id.xscale.entry
     canvas_checkcommand $id
 }
@@ -3894,7 +4832,9 @@ proc dodata_ok {name} {
 
 proc pdtk_data_dialog {name stuff} {
     global pd_deffont
-    toplevel $name -class DialogWindow
+	global pd_nt
+    toplevel $name
+    match_linux_wm [list $name configure]
     wm title $name {Atom}
     wm protocol $name WM_DELETE_WINDOW [concat dodata_cancel $name]
 
@@ -3902,20 +4842,21 @@ proc pdtk_data_dialog {name stuff} {
     bind $name <Control-t> [concat dodata_ok $name]
     bind $name <Control-s> [concat dodata_send $name]
 
-    frame $name.buttonframe
-    pack $name.buttonframe -side bottom -fill x -pady 2m
-    button $name.buttonframe.send -text {Send (Ctrl s)}\
-        -command [concat dodata_send $name]
-    button $name.buttonframe.ok -text {OK (Ctrl t)}\
-        -command [concat dodata_ok $name]
+    match_linux_wm [list frame $name.buttonframe]
+    pack $name.buttonframe -side bottom -fill x -pady 3
+	match_linux_wm [list button $name.buttonframe.send -text {Send (Ctrl s)}\
+    	-command [concat dodata_send $name]]
+	match_linux_wm [list button $name.buttonframe.ok -text {OK (Ctrl t)}\
+    	-command [concat dodata_ok $name]]
     pack $name.buttonframe.send -side left -expand 1
     pack $name.buttonframe.ok -side left -expand 1
 
-    text $name.text -relief raised -bd 2 -height 40 -width 60 \
-        -yscrollcommand "$name.scroll set" -font $pd_deffont
-    scrollbar $name.scroll -command "$name.text yview"
-    pack $name.scroll -side right -fill y
-    pack $name.text -side left -fill both -expand 1
+    match_linux_wm [list text $name.text -relief sunken -bd 1 -height 40 -width 60 \
+        -yscrollcommand "$name.scroll set" -font $pd_deffont \
+		-highlightthickness 0 -takefocus 0]
+    match_linux_wm [list scrollbar $name.scroll -command "$name.text yview"]
+    pack $name.scroll -side right -fill y -pady 3
+    pack $name.text -side left -fill both -expand 1 -pady 3
     $name.text insert end $stuff
     focus $name.text
 }
@@ -3923,14 +4864,28 @@ proc pdtk_data_dialog {name stuff} {
 ############ check or uncheck the "edit" menu item ##############
 #####################iemlib#######################
 proc pdtk_canvas_editval {name value} {
+	#global colors
+
     if { $value } {
-        $name.m.edit entryconfigure "Edit mode" -indicatoron true
+        $name.m.edit entryconfigure "Edit mode" -indicatoron false -background "#7dd37d"
     } else {                          
-        $name.m.edit entryconfigure "Edit mode" -indicatoron false
+        $name.m.edit entryconfigure "Edit mode" -indicatoron false -background {}
     }                                                 
 }
 #####################iemlib#######################
 
+## jsarlo
+proc pdtk_canvas_magicglassval {name value} {
+	#global colors
+
+    if { $value } {
+	$name.m.edit entryconfigure "Cord Inspector" -indicatoron false -background "#7dd37d"
+    } else {                          
+        $name.m.edit entryconfigure "Cord Inspector" -indicatoron false -background {}
+    }                                                 
+}
+## end jsarlo
+
 ############ pdtk_text_new -- create a new text object #2###########
 proc pdtk_text_new {canvasname myname x y text font color} {
     #    if {$font < 13} {set fontname [format -*-courier-bold----%d-* $font]}
@@ -3952,8 +4907,8 @@ proc pdtk_text_new {canvasname myname x y text font color} {
 
     $canvasname create text $x $y -font $typeface \
         -tags $myname -text $text -fill $color -anchor nw 
-	$canvasname bind $myname <Home> [concat $canvasname icursor $myname 0]
-	$canvasname bind $myname <End> [concat $canvasname icursor $myname end]
+	#$canvasname bind $myname <Home> [concat $canvasname icursor $myname 0]
+	#$canvasname bind $myname <End> [concat $canvasname icursor $myname end]
 	if {$pd_nt == 2} { # emacs bindings for Mac OS X
 		$canvasname bind $myname <Control-a> \
 			[concat $canvasname icursor $myname 0]
@@ -3965,7 +4920,7 @@ proc pdtk_text_new {canvasname myname x y text font color} {
 
 ################ pdtk_text_set -- change the text ##################
 proc pdtk_text_set {canvasname myname text} {
-    $canvasname itemconfig $myname -text $text
+    catch {$canvasname itemconfig $myname -text $text}
     #    pd [concat $myname size [$canvasname bbox $myname] \;]
 }
 
@@ -3984,7 +4939,7 @@ proc pdtk_pd_ctrlkey {name key shift} {
         if {$key == "n" || $key == "N"} {menu_new}
         if {$key == "o" || $key == "O"} {menu_open}
         if {$key == "q" || $key == "Q"} {menu_quit}
-        if {$key == "r" || $key == "R"} {menu_raise_console}
+        if {$key == "semicolon"} {menu_raise_console}
         if {$pd_nt != 2} {
             # Cmd-m is minimize window on Mac OS X
             if {$key == "m" || $key == "M"} {menu_send}
@@ -4020,12 +4975,7 @@ proc pdtk_pd_startup {version apilist midiapilist fontname_from_pd fontweight_fr
 	if {$pd_nt == 1} { raise . }
 
     set fontlist ""
-	if {$pd_nt != 1 && $::tcl_version eq "8.5"} {
-		set sizelist "5 6 8 9 10 12 14 16 19 25"
-	} else {
-		set sizelist "8 9 10 12 14 16 18 24 30 36"
-	}
-    foreach i $sizelist {
+    foreach i {6 6 8 9 10 12 14 18 22 29} {
         set font [format {{%s} %d %s} $fontname_from_pd $i $fontweight_from_pd]
         set pd_fontlist [linsert $pd_fontlist 100000 $font] 
         set width0 [font measure  $font x]
@@ -4054,8 +5004,8 @@ proc pdtk_pd_startup {version apilist midiapilist fontname_from_pd fontweight_fr
         global pd_macdropped pd_macready
         set pd_macready 1
         foreach file $pd_macdropped {
-            . configure -cursor watch
-            .printout.text configure -cursor watch
+            pd [concat pd open [pdtk_enquote [file tail $file]] \
+                    [pdtk_enquote  [file dirname $file]] \;]
             menu_doc_open [file dirname $file] [file tail $file]
         }
     }
@@ -4073,31 +5023,39 @@ proc pdtk_pd_meters {indb outdb inclip outclip} {
     global ctrls_inlevel ctrls_outlevel
     set ctrls_inlevel $indb
     if {$inclip == 1} {
-        .controls.inout.in.clip configure -background red
+        .controls.inout.in.clip configure -style IOErrorOn.TButton
     } else {
-        .controls.inout.in.clip configure -background grey
+        .controls.inout.in.clip configure -style IOErrorOff.TButton
     }
     set ctrls_outlevel $outdb
     if {$outclip == 1} {
-        .controls.inout.out.clip configure -background red
+        .controls.inout.out.clip configure -style IOErrorOn.TButton
     } else {
-        .controls.inout.out.clip configure -background grey
+        .controls.inout.out.clip configure -style IOErrorOff.TButton
     }
     
 }
 
 proc pdtk_pd_dio {red} {
 #    puts stderr [concat dio $red]
+	global pd_nt
     if {$red == 1} {
-        .controls.dio configure -background red -activebackground red
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			.controls.dio configure -style IOErrorOn.TButton
+		} else {
+	        .controls.dio configure -background red -activebackground red
+		}
     } else {
-        .controls.dio configure -background grey -activebackground lightgrey
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			.controls.dio configure -style IOErrorOff.TButton
+		} else {
+	        .controls.dio configure -background grey -activebackground lightgrey
+		}		
     }
         
 }
 
 ############# text editing from the "edit" menu ###################
-set edit_number 1
 
 proc texteditor_send {name} {
     set topname [string trimright $name .text]
@@ -4116,35 +5074,40 @@ proc texteditor_ok {name} {
     destroy $topname
 }
 
-
 proc pdtk_pd_texteditor {stuff} {
-    global edit_number pd_deffont
-    set name [format ".text%d" $edit_number]
-    set edit_number [expr $edit_number + 1]
-
-    toplevel $name -class DialogWindow
-    wm title $name {TEXT}
-
-    pdtk_standardkeybindings $name
-    bind $name <Control-t> {texteditor_ok %W}
-    bind $name <Control-s> {texteditor_send %W}
-
-    frame $name.buttons
-    pack $name.buttons -side bottom -fill x -pady 2m
-    button $name.buttons.send -text {Send (Ctrl s)}\
-        -command "texteditor_send $name.text"
-    button $name.buttons.ok -text {OK (Ctrl t)}\
-        -command "texteditor_ok $name.text"
-    pack $name.buttons.send -side left -expand 1
-    pack $name.buttons.ok -side left -expand 1
-
-    text $name.text -relief raised -bd 2 -height 12 -width 60 \
-        -yscrollcommand "$name.scroll set" -font $pd_deffont
-    scrollbar $name.scroll -command "$name.text yview"
-    pack $name.scroll -side right -fill y
-    pack $name.text -side left -fill both -expand 1
-    $name.text insert end $stuff
-    focus $name.text
+    global pd_deffont
+	global pd_nt
+    if { [winfo exists .texteditor.text] } {
+        raise .texteditor
+    } else {
+		set name .texteditor
+
+		toplevel $name
+		match_linux_wm [list $name configure]
+		wm title $name {Text Editor}
+
+		pdtk_standardkeybindings $name
+		bind $name <Control-t> {texteditor_ok %W}
+		bind $name <Control-s> {texteditor_send %W}
+
+		match_linux_wm [list frame $name.buttons]
+		pack $name.buttons -side bottom -fill x  
+		match_linux_wm [list button $name.buttons.send -text {Send (Ctrl s)}\
+			-command "texteditor_send $name.text"]
+		match_linux_wm [list button $name.buttons.ok -text {OK (Ctrl t)}\
+			-command "texteditor_ok $name.text"]
+		pack $name.buttons.send -side left -expand 1
+		pack $name.buttons.ok -side left -expand 1
+
+		match_linux_wm [list text $name.text -relief sunken -bd 1 -height 12 -width 60 \
+		    -yscrollcommand "$name.scroll set" -font $pd_deffont \
+			-highlightthickness 0 -takefocus 0]
+		match_linux_wm [list scrollbar $name.scroll -command "$name.text yview"]
+		pack $name.scroll -side right -fill y -pady 3
+		pack $name.text -side left -fill both -expand 1 -pady 3
+		$name.text insert end $stuff
+		focus $name.text
+	}
 }
 
 #  paste text into a text box
@@ -4311,6 +5274,7 @@ proc pdtk_audio_dialog {id indev1 indev2 indev3 indev4 \
     global audio_sr audio_advance audio_callback
     global audio_indevlist audio_outdevlist
     global pd_indev pd_outdev
+	global pd_nt
 
     set audio_indev1 $indev1
     set audio_indev2 $indev2
@@ -4343,176 +5307,248 @@ proc pdtk_audio_dialog {id indev1 indev2 indev3 indev4 \
     set audio_sr $sr
     set audio_advance $advance
     set audio_callback $callback
-    toplevel $id -class DialogWindow
-    wm group $id .
-    wm title $id {audio}
+    toplevel $id
+	match_linux_wm [list $id configure]
+    wm title $id {Audio Settings}
+	wm resizable $id 0 0
     wm protocol $id WM_DELETE_WINDOW [concat audio_cancel $id]
 
     pdtk_panelkeybindings $id "audio"
 
-    frame $id.buttonframe
-    pack $id.buttonframe -side bottom -fill x -pady 2m
-    button $id.buttonframe.cancel -text {Cancel}\
-        -command "audio_cancel $id"
-    button $id.buttonframe.apply -text {Apply}\
-        -command "audio_apply $id"
-    button $id.buttonframe.ok -text {OK}\
-        -command "audio_ok $id"
-    button $id.buttonframe.save -text {Save all settings}\
-        -command "audio_apply $id \; pd pd save-preferences \\;"
+    match_linux_wm [list frame $id.buttonframe]
+    pack $id.buttonframe -side bottom -fill x -pady 3
+	match_linux_wm [list button $id.buttonframe.cancel -text {Cancel}\
+	    -command "audio_cancel $id"]
+	match_linux_wm [list button $id.buttonframe.apply -text {Apply}\
+	    -command "audio_apply $id"]
+	match_linux_wm [list button $id.buttonframe.ok -text {OK}\
+	    -command "audio_ok $id"]
+	match_linux_wm [list button $id.buttonframe.save\
+		-text {Save all settings}\
+	    -command "audio_apply $id \; pd pd save-preferences \\;"]
     pack $id.buttonframe.cancel $id.buttonframe.apply $id.buttonframe.ok \
-        $id.buttonframe.save -side left -expand 1
+        $id.buttonframe.save -side left -expand 1 -padx 3
     
-        # sample rate and advance
-    frame $id.srf
+    # sample rate and advance
+    match_linux_wm [list frame $id.srf]
     pack $id.srf -side top
     
-    label $id.srf.l1 -text "sample rate:"
-    entry $id.srf.x1 -textvariable audio_sr -width 7
-    label $id.srf.l2 -text "delay (msec):"
-    entry $id.srf.x2 -textvariable audio_advance -width 4
-    pack $id.srf.l1 $id.srf.x1 $id.srf.l2 $id.srf.x2 -side left
+    match_linux_wm [list label $id.srf.l1 -text "sample rate:"]
+    match_linux_wm [list entry $id.srf.x1 -textvariable audio_sr -width 7]
+    match_linux_wm [list label $id.srf.l2 -text "delay (msec):"]
+    match_linux_wm [list entry $id.srf.x2 -textvariable audio_advance -width 4]
+    pack $id.srf.l1 $id.srf.x1 $id.srf.l2 $id.srf.x2 -side left -pady 3
     if {$audio_callback >= 0} {
-        checkbutton $id.srf.x3 -variable audio_callback \
-            -text {use callbacks} -anchor e
+        match_linux_wm [list checkbutton $id.srf.x3 -variable audio_callback \
+            -text {use callbacks} -anchor e]
         pack $id.srf.x3 -side left
     }
-        # input device 1
-    frame $id.in1f
+    
+	# input device 1
+    match_linux_wm [list frame $id.in1f]
     pack $id.in1f -side top
 
-    checkbutton $id.in1f.x0 -variable audio_inenable1 \
-        -text {input device 1} -anchor e
-    button $id.in1f.x1 -text [lindex $audio_indevlist $audio_indev1] \
-        -command [list audio_popup $id $id.in1f.x1 audio_indev1 $audio_indevlist]
-    label $id.in1f.l2 -text "channels:"
-    entry $id.in1f.x2 -textvariable audio_inchan1 -width 3
-    pack $id.in1f.x0 $id.in1f.x1 $id.in1f.l2 $id.in1f.x2 -side left
+    match_linux_wm [list checkbutton $id.in1f.x0 -variable audio_inenable1 \
+        -text {input device 1  }]
 
-        # input device 2
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		match_linux_wm [list ttk::combobox $id.in1f.x1 \
+			-state readonly \
+			-values $audio_indevlist]
+		$id.in1f.x1 current 0
+	} else {
+		button $id.in1f.x1 -text \
+			[lindex $audio_indevlist $audio_indev1] \
+			-command [list audio_popup $id $id.in1f.x1 \
+			audio_indev1 $audio_indevlist]
+	}
+    match_linux_wm [list label $id.in1f.l2 -text "channels:"]
+    match_linux_wm [list entry $id.in1f.x2 -textvariable audio_inchan1 -width 3]
+    pack $id.in1f.x0 $id.in1f.x1 $id.in1f.l2 $id.in1f.x2 -side left -pady 3
+
+    # input device 2
     if {$longform && $multi > 1 && [llength $audio_indevlist] > 1} {
-        frame $id.in2f
+        match_linux_wm [list frame $id.in2f]
         pack $id.in2f -side top
 
-        checkbutton $id.in2f.x0 -variable audio_inenable2 \
-            -text {input device 2} -anchor e
-        button $id.in2f.x1 -text [lindex $audio_indevlist $audio_indev2] \
-            -command [list audio_popup $id $id.in2f.x1 audio_indev2 \
-                $audio_indevlist]
-        label $id.in2f.l2 -text "channels:"
-        entry $id.in2f.x2 -textvariable audio_inchan2 -width 3
-        pack $id.in2f.x0 $id.in2f.x1 $id.in2f.l2 $id.in2f.x2 -side left
+        match_linux_wm [list checkbutton $id.in2f.x0 -variable audio_inenable2 \
+            -text {input device 2  }]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.in2f.x1 \
+				-state readonly \
+				-values $audio_indevlist]
+			$id.in2f.x1 current 1
+		} else {
+		    button $id.in2f.x1 -text \
+				[lindex $audio_indevlist $audio_indev2] \
+		        -command [list audio_popup $id $id.in2f.x1 \
+				audio_indev2 $audio_indevlist]
+		}
+        match_linux_wm [list label $id.in2f.l2 -text "channels:"]
+        match_linux_wm [list entry $id.in2f.x2 -textvariable audio_inchan2 -width 3]
+        pack $id.in2f.x0 $id.in2f.x1 $id.in2f.l2 $id.in2f.x2 -side left -pady 3
     }
 
-        # input device 3
+    # input device 3
     if {$longform && $multi > 1 && [llength $audio_indevlist] > 2} {
-        frame $id.in3f
+        match_linux_wm [list frame $id.in3f]
         pack $id.in3f -side top
 
-        checkbutton $id.in3f.x0 -variable audio_inenable3 \
-            -text {input device 3} -anchor e
-        button $id.in3f.x1 -text [lindex $audio_indevlist $audio_indev3] \
-            -command [list audio_popup $id $id.in3f.x1 audio_indev3 \
-                $audio_indevlist]
-        label $id.in3f.l2 -text "channels:"
-        entry $id.in3f.x2 -textvariable audio_inchan3 -width 3
-        pack $id.in3f.x0 $id.in3f.x1 $id.in3f.l2 $id.in3f.x2 -side left
+        match_linux_wm [list checkbutton $id.in3f.x0 -variable audio_inenable3 \
+            -text {input device 3  }]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.in3f.x1 \
+				-state readonly \
+				-values $audio_indevlist]
+			$id.in3f.x1 current 2
+		} else {
+        	button $id.in3f.x1 -text \
+				[lindex $audio_indevlist $audio_indev3] \
+            	-command [list audio_popup $id $id.in3f.x1 \
+				audio_indev3 $audio_indevlist]
+		}
+        match_linux_wm [list label $id.in3f.l2 -text "channels:"]
+        match_linux_wm [list entry $id.in3f.x2 -textvariable audio_inchan3 -width 3]
+        pack $id.in3f.x0 $id.in3f.x1 $id.in3f.l2 $id.in3f.x2 -side left -pady 3
     }
 
-        # input device 4
+    # input device 4
     if {$longform && $multi > 1 && [llength $audio_indevlist] > 3} {
-        frame $id.in4f
+        match_linux_wm [list frame $id.in4f]
         pack $id.in4f -side top
 
-        checkbutton $id.in4f.x0 -variable audio_inenable4 \
-            -text {input device 4} -anchor e
-        button $id.in4f.x1 -text [lindex $audio_indevlist $audio_indev4] \
-            -command [list audio_popup $id $id.in4f.x1 audio_indev4 \
-                $audio_indevlist]
-        label $id.in4f.l2 -text "channels:"
-        entry $id.in4f.x2 -textvariable audio_inchan4 -width 3
-        pack $id.in4f.x0 $id.in4f.x1 $id.in4f.l2 $id.in4f.x2 -side left
+        match_linux_wm [list checkbutton $id.in4f.x0 -variable audio_inenable4 \
+            -text {input device 4  }]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.in4f.x1 \
+				-state readonly \
+				-values $audio_indevlist]
+			$id.in4f.x1 current 3
+		} else {
+		    button $id.in4f.x1 -text \
+				[lindex $audio_indevlist $audio_indev4] \
+		        -command [list audio_popup $id $id.in4f.x1 \
+				audio_indev4 $audio_indevlist]
+		}
+        match_linux_wm [list label $id.in4f.l2 -text "channels:"]
+        match_linux_wm [list entry $id.in4f.x2 -textvariable audio_inchan4 -width 3]
+        pack $id.in4f.x0 $id.in4f.x1 $id.in4f.l2 $id.in4f.x2 -side left -pady 3
     }
 
-        # output device 1
-    frame $id.out1f
+	# output device 1
+    match_linux_wm [list frame $id.out1f]
     pack $id.out1f -side top
 
-    checkbutton $id.out1f.x0 -variable audio_outenable1 \
-        -text {output device 1} -anchor e
+    match_linux_wm [list checkbutton $id.out1f.x0 -variable audio_outenable1 \
+        -text {output device 1}]
     if {$multi == 0} {
-        label $id.out1f.l1 \
-            -text "(same as input device) ..............      "
+        match_linux_wm [list label $id.out1f.l1 \
+            -text "(same as input device) ........................"]
     } else {
-        button $id.out1f.x1 -text [lindex $audio_outdevlist $audio_outdev1] \
-            -command  [list audio_popup $id $id.out1f.x1 audio_outdev1 \
-                $audio_outdevlist]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out1f.x1 \
+				-state readonly \
+				-values $audio_outdevlist]
+			$id.out1f.x1 current 0
+		} else {        		
+			button $id.out1f.x1 -text \
+				[lindex $audio_outdevlist $audio_outdev1] \
+            	-command  [list audio_popup $id $id.out1f.x1 \
+				audio_outdev1 $audio_outdevlist]
+		}
     }
-    label $id.out1f.l2 -text "channels:"
-    entry $id.out1f.x2 -textvariable audio_outchan1 -width 3
+    match_linux_wm [list label $id.out1f.l2 -text "channels:"]
+    match_linux_wm [list entry $id.out1f.x2 -textvariable audio_outchan1 -width 3]
     if {$multi == 0} {
-        pack $id.out1f.x0 $id.out1f.l1 $id.out1f.x2 -side left
+        pack $id.out1f.x0 $id.out1f.l1 $id.out1f.x2 -side left -pady 3
     } else {
-        pack $id.out1f.x0 $id.out1f.x1 $id.out1f.l2 $id.out1f.x2 -side left
+        pack $id.out1f.x0 $id.out1f.x1 $id.out1f.l2 $id.out1f.x2 -side left -pady 3
     }
 
-        # output device 2
+    # output device 2
     if {$longform && $multi > 1 && [llength $audio_outdevlist] > 1} {
-        frame $id.out2f
+        match_linux_wm [list frame $id.out2f]
         pack $id.out2f -side top
 
-        checkbutton $id.out2f.x0 -variable audio_outenable2 \
-            -text {output device 2} -anchor e
-        button $id.out2f.x1 -text [lindex $audio_outdevlist $audio_outdev2] \
-            -command \
-            [list audio_popup $id $id.out2f.x1 audio_outdev2 $audio_outdevlist]
-        label $id.out2f.l2 -text "channels:"
-        entry $id.out2f.x2 -textvariable audio_outchan2 -width 3
-        pack $id.out2f.x0 $id.out2f.x1 $id.out2f.l2 $id.out2f.x2 -side left
+        match_linux_wm [list checkbutton $id.out2f.x0 -variable audio_outenable2 \
+            -text {output device 2}]
+
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out2f.x1 \
+				-state readonly \
+				-values $audio_outdevlist]
+			$id.out2f.x1 current 1
+		} else { 
+		    button $id.out2f.x1 -text \
+				[lindex $audio_outdevlist $audio_outdev2] \
+		        -command [list audio_popup $id $id.out2f.x1 \
+				audio_outdev2 $audio_outdevlist]
+		}
+        match_linux_wm [list label $id.out2f.l2 -text "channels:"]
+        match_linux_wm [list entry $id.out2f.x2 -textvariable audio_outchan2 -width 3]
+        pack $id.out2f.x0 $id.out2f.x1 $id.out2f.l2 $id.out2f.x2 -side left -pady 3
     }
 
-        # output device 3
+    # output device 3
     if {$longform && $multi > 1 && [llength $audio_outdevlist] > 2} {
-        frame $id.out3f
+        match_linux_wm [list frame $id.out3f]
         pack $id.out3f -side top
 
-        checkbutton $id.out3f.x0 -variable audio_outenable3 \
-            -text {output device 3} -anchor e
-        button $id.out3f.x1 -text [lindex $audio_outdevlist $audio_outdev3] \
-            -command \
-            [list audio_popup $id $id.out3f.x1 audio_outdev3 $audio_outdevlist]
-        label $id.out3f.l2 -text "channels:"
-        entry $id.out3f.x2 -textvariable audio_outchan3 -width 3
-        pack $id.out3f.x0 $id.out3f.x1 $id.out3f.l2 $id.out3f.x2 -side left
+        match_linux_wm [list checkbutton $id.out3f.x0 -variable audio_outenable3 \
+            -text {output device 3}]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out3f.x1 \
+				-state readonly \
+				-values $audio_outdevlist]
+			$id.out3f.x1 current 2
+		} else {
+			button $id.out3f.x1 -text \
+				[lindex $audio_outdevlist $audio_outdev3] \
+            	-command [list audio_popup $id $id.out3f.x1 \
+				audio_outdev3 $audio_outdevlist]
+		}
+        match_linux_wm [list label $id.out3f.l2 -text "channels:"]
+        match_linux_wm [list entry $id.out3f.x2 -textvariable audio_outchan3 -width 3]
+        pack $id.out3f.x0 $id.out3f.x1 $id.out3f.l2 $id.out3f.x2 -side left -pady 3
     }
 
-        # output device 4
+    # output device 4
     if {$longform && $multi > 1 && [llength $audio_outdevlist] > 3} {
-        frame $id.out4f
+        match_linux_wm [list frame $id.out4f]
         pack $id.out4f -side top
 
-        checkbutton $id.out4f.x0 -variable audio_outenable4 \
-            -text {output device 4} -anchor e
-        button $id.out4f.x1 -text [lindex $audio_outdevlist $audio_outdev4] \
-            -command \
-            [list audio_popup $id $id.out4f.x1 audio_outdev4 $audio_outdevlist]
-        label $id.out4f.l2 -text "channels:"
-        entry $id.out4f.x2 -textvariable audio_outchan4 -width 3
-        pack $id.out4f.x0 $id.out4f.x1 $id.out4f.l2 $id.out4f.x2 -side left
+        match_linux_wm [list checkbutton $id.out4f.x0 -variable audio_outenable4 \
+            -text {output device 4}]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out4f.x1 \
+				-state readonly \
+				-values $audio_outdevlist]
+			$id.out4f.x1 current 3
+		} else {
+        	button $id.out4f.x1 -text \
+				[lindex $audio_outdevlist $audio_outdev4] \
+            	-command [list audio_popup $id $id.out4f.x1 \
+				audio_outdev4 $audio_outdevlist]
+		}
+        match_linux_wm [list label $id.out4f.l2 -text "channels:"]
+        match_linux_wm [list entry $id.out4f.x2 -textvariable audio_outchan4 -width 3]
+        pack $id.out4f.x0 $id.out4f.x1 $id.out4f.l2 $id.out4f.x2 -side left -pady 3
     }
 
-        # if not the "long form" but if "multi" is 2, make a button to
-        # restart with longform set. 
+    # if not the "long form" but if "multi" is 2, make a button to
+    # restart with longform set. 
     
     if {$longform == 0 && $multi > 1} {
-        frame $id.longbutton
+        match_linux_wm [list frame $id.longbutton]
         pack $id.longbutton -side top
-        button $id.longbutton.b -text {use multiple devices} \
-            -command  {pd pd audio-properties 1 \;}
-        pack $id.longbutton.b
+	    match_linux_wm [list button $id.longbutton.b -text \
+			{use multiple devices} -command {pd pd audio-properties 1 \;}]
+        pack $id.longbutton.b -pady 3
     }
-    $id.srf.x1 select from 0
-    $id.srf.x1 select adjust end
+	if { [info tclversion] < 8.5 } {
+		$id.srf.x1 select from 0
+		$id.srf.x1 select adjust end
+	}
     focus $id.srf.x1
 }
 
@@ -4580,6 +5616,7 @@ proc pdtk_midi_dialog {id indev1 indev2 indev3 indev4 \
     global midi_outdev1 midi_outdev2 midi_outdev3 midi_outdev4
     global midi_indevlist midi_outdevlist
     global midi_alsain midi_alsaout
+	global pd_nt
 
     set midi_indev1 $indev1
     set midi_indev2 $indev2
@@ -4592,121 +5629,179 @@ proc pdtk_midi_dialog {id indev1 indev2 indev3 indev4 \
     set midi_alsain [llength $midi_indevlist]
     set midi_alsaout [llength $midi_outdevlist]
 
-    toplevel $id -class DialogWindow
-    wm title $id {midi}
+    toplevel $id
+	match_linux_wm [list $id configure]
+	wm resizable $id 0 0
+	wm title $id {MIDI Settings}
     wm protocol $id WM_DELETE_WINDOW [concat midi_cancel $id]
 
     pdtk_panelkeybindings $id "midi"
 
-    frame $id.buttonframe
-    pack $id.buttonframe -side bottom -fill x -pady 2m
-    button $id.buttonframe.cancel -text {Cancel}\
-        -command "midi_cancel $id"
-    button $id.buttonframe.apply -text {Apply}\
-        -command "midi_apply $id"
-    button $id.buttonframe.ok -text {OK}\
-        -command "midi_ok $id"
-    pack $id.buttonframe.cancel -side left -expand 1
-    pack $id.buttonframe.apply -side left -expand 1
-    pack $id.buttonframe.ok -side left -expand 1
+    match_linux_wm [list frame $id.buttonframe]
+    pack $id.buttonframe -side bottom -fill x -pady 3
+    match_linux_wm [list button $id.buttonframe.cancel -text {Cancel}\
+        -command "midi_cancel $id"]
+    match_linux_wm [list button $id.buttonframe.apply -text {Apply}\
+        -command "midi_apply $id"]
+    match_linux_wm [list button $id.buttonframe.ok -text {OK}\
+        -command "midi_ok $id"]
+    pack $id.buttonframe.cancel -side left -expand 1 -padx 3
+    pack $id.buttonframe.apply -side left -expand 1 -padx 3
+    pack $id.buttonframe.ok -side left -expand 1 -padx 3
     
-        # input device 1
-    frame $id.in1f
+    # input device 1
+    match_linux_wm [list frame $id.in1f]
     pack $id.in1f -side top
 
-    label $id.in1f.l1 -text "input device 1:"
-    button $id.in1f.x1 -text [lindex $midi_indevlist $midi_indev1] \
-        -command [list midi_popup $id $id.in1f.x1 midi_indev1 $midi_indevlist]
-    pack $id.in1f.l1 $id.in1f.x1 -side left
+    match_linux_wm [list label $id.in1f.l1 -text "  input device 1:"]
+    if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		match_linux_wm [list ttk::combobox $id.in1f.x1 \
+			-state readonly \
+			-values $midi_indevlist]
+		$id.in1f.x1 current 0
+	} else {
+		button $id.in1f.x1 -text [lindex $midi_indevlist $midi_indev1] \
+	        -command [list midi_popup $id $id.in1f.x1 midi_indev1 \
+			$midi_indevlist]
+	}
+    pack $id.in1f.l1 $id.in1f.x1 -side left -pady 3
 
-        # input device 2
-    if {$longform && [llength $midi_indevlist] > 2} {
-        frame $id.in2f
+    # input device 2
+    if {$longform && [llength $midi_indevlist] > 1} {
+        match_linux_wm [list frame $id.in2f]
         pack $id.in2f -side top
 
-        label $id.in2f.l1 -text "input device 2:"
-        button $id.in2f.x1 -text [lindex $midi_indevlist $midi_indev2] \
-            -command [list midi_popup $id $id.in2f.x1 midi_indev2 \
-                $midi_indevlist]
-        pack $id.in2f.l1 $id.in2f.x1 -side left
+        match_linux_wm [list label $id.in2f.l1 -text "  input device 2:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.in2f.x1 \
+				-state readonly \
+				-values $midi_indevlist]
+			$id.in2f.x1 current 1
+		} else {
+		    button $id.in2f.x1 -text [lindex $midi_indevlist $midi_indev2] \
+		        -command [list midi_popup $id $id.in2f.x1 midi_indev2 \
+				$midi_indevlist]
+		}
+        pack $id.in2f.l1 $id.in2f.x1 -side left -pady 3
     }
 
-        # input device 3
-    if {$longform && [llength $midi_indevlist] > 3} {
-        frame $id.in3f
+    # input device 3
+    if {$longform && [llength $midi_indevlist] > 2} {
+        match_linux_wm [list frame $id.in3f]
         pack $id.in3f -side top
-
-        label $id.in3f.l1 -text "input device 3:"
-        button $id.in3f.x1 -text [lindex $midi_indevlist $midi_indev3] \
-            -command [list midi_popup $id $id.in3f.x1 midi_indev3 \
-                $midi_indevlist]
-        pack $id.in3f.l1 $id.in3f.x1 -side left
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.in3f.x1 \
+				-state readonly \
+				-values $midi_indevlist]
+			$id.in3f.x1 current 2
+		} else {
+		    match_linux_wm [list label $id.in3f.l1 -text "  input device 3:"]
+		    button $id.in3f.x1 -text [lindex $midi_indevlist $midi_indev3] \
+		        -command [list midi_popup $id $id.in3f.x1 midi_indev3 \
+		            $midi_indevlist]
+		}
+        pack $id.in3f.l1 $id.in3f.x1 -side left -pady 3
     }
 
-        # input device 4
-    if {$longform && [llength $midi_indevlist] > 4} {
-        frame $id.in4f
+    # input device 4
+    if {$longform && [llength $midi_indevlist] > 3} {
+        match_linux_wm [list frame $id.in4f]
         pack $id.in4f -side top
 
-        label $id.in4f.l1 -text "input device 4:"
-        button $id.in4f.x1 -text [lindex $midi_indevlist $midi_indev4] \
-            -command [list midi_popup $id $id.in4f.x1 midi_indev4 \
-                $midi_indevlist]
-        pack $id.in4f.l1 $id.in4f.x1 -side left
+        match_linux_wm [list label $id.in4f.l1 -text "  input device 4:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.in4f.x1 \
+				-state readonly \
+				-values $midi_indevlist]
+			$id.in4f.x1 current 3
+		} else {
+		    button $id.in4f.x1 -text [lindex $midi_indevlist $midi_indev4] \
+		        -command [list midi_popup $id $id.in4f.x1 midi_indev4 \
+		            $midi_indevlist]
+		}
+        pack $id.in4f.l1 $id.in4f.x1 -side left -pady 3
     }
 
-        # output device 1
-
-    frame $id.out1f
+    # output device 1
+    match_linux_wm [list frame $id.out1f]
     pack $id.out1f -side top
-    label $id.out1f.l1 -text "output device 1:"
-    button $id.out1f.x1 -text [lindex $midi_outdevlist $midi_outdev1] \
-        -command [list midi_popup $id $id.out1f.x1 midi_outdev1 \
-            $midi_outdevlist]
-    pack $id.out1f.l1 $id.out1f.x1 -side left
+    match_linux_wm [list label $id.out1f.l1 -text "output device 1:"]
+	if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+		match_linux_wm [list ttk::combobox $id.out1f.x1 \
+			-state readonly \
+			-values $midi_outdevlist]
+		$id.out1f.x1 current 0
+	} else {
+		button $id.out1f.x1 -text [lindex $midi_outdevlist $midi_outdev1] \
+		    -command [list midi_popup $id $id.out1f.x1 midi_outdev1 \
+		        $midi_outdevlist]
+	}
+    pack $id.out1f.l1 $id.out1f.x1 -side left -pady 3
 
-        # output device 2
-    if {$longform && [llength $midi_outdevlist] > 2} {
-        frame $id.out2f
+    # output device 2
+    if {$longform && [llength $midi_outdevlist] > 1} {
+        match_linux_wm [list frame $id.out2f]
         pack $id.out2f -side top
-        label $id.out2f.l1 -text "output device 2:"
-        button $id.out2f.x1 -text [lindex $midi_outdevlist $midi_outdev2] \
-            -command \
-            [list midi_popup $id $id.out2f.x1 midi_outdev2 $midi_outdevlist]
-        pack $id.out2f.l1 $id.out2f.x1 -side left
+        match_linux_wm [list label $id.out2f.l1 -text "output device 2:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out2f.x1 \
+				-state readonly \
+				-values $midi_outdevlist]
+			$id.out2f.x1 current 1
+		} else {
+		    button $id.out2f.x1 -text [lindex $midi_outdevlist $midi_outdev2] \
+		        -command [list midi_popup $id $id.out2f.x1 \
+				midi_outdev2 $midi_outdevlist]
+		}
+        pack $id.out2f.l1 $id.out2f.x1 -side left -pady 3
     }
 
-        # output device 3
-    if {$longform && [llength $midi_midi_outdevlist] > 3} {
-        frame $id.out3f
+    # output device 3
+    if {$longform && [llength $midi_outdevlist] > 2} {
+        match_linux_wm [list frame $id.out3f]
         pack $id.out3f -side top
-        label $id.out3f.l1 -text "output device 3:"
-        button $id.out3f.x1 -text [lindex $midi_outdevlist $midi_outdev3] \
-            -command \
-            [list midi_popup $id $id.out3f.x1 midi_outdev3 $midi_outdevlist]
-        pack $id.out3f.l1 $id.out3f.x1 -side left
+        match_linux_wm [list label $id.out3f.l1 -text "output device 3:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out3f.x1 \
+				-state readonly \
+				-values $midi_outdevlist]
+			$id.out3f.x1 current 2
+		} else {
+		    button $id.out3f.x1 -text [lindex $midi_outdevlist $midi_outdev3] \
+		        -command [list midi_popup $id $id.out3f.x1 \
+				midi_outdev3 $midi_outdevlist]
+		}
+        pack $id.out3f.l1 $id.out3f.x1 -side left -pady 3
     }
 
-        # output device 4
-    if {$longform && [llength $midi_midi_outdevlist] > 4} {
-        frame $id.out4f
+    # output device 4
+    if {$longform && [llength $midi_outdevlist] > 3} {
+        match_linux_wm [list frame $id.out4f]
         pack $id.out4f -side top
-        label $id.out4f.l1 -text "output device 4:"
-        button $id.out4f.x1 -text [lindex $midi_outdevlist $midi_outdev4] \
-            -command \
-            [list midi_popup $id $id.out4f.x1 midi_outdev4 $midi_outdevlist]
-        pack $id.out4f.l1 $id.out4f.x1 -side left
+        match_linux_wm [list label $id.out4f.l1 -text "output device 4:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+			match_linux_wm [list ttk::combobox $id.out4f.x1 \
+				-state readonly \
+				-values $midi_outdevlist]
+			$id.out4f.x1 current 3
+		} else {
+		    button $id.out4f.x1 -text [lindex $midi_outdevlist $midi_outdev4] \
+		        -command [list midi_popup $id $id.out4f.x1 \
+				midi_outdev4 $midi_outdevlist]
+		}
+        pack $id.out4f.l1 $id.out4f.x1 -side left -pady 3
     }
 
-        # if not the "long form" make a button to
-        # restart with longform set. 
+    # if not the "long form" make a button to
+    # restart with longform set. 
     
     if {$longform == 0} {
-        frame $id.longbutton
+        match_linux_wm [list frame $id.longbutton]
         pack $id.longbutton -side top
-        button $id.longbutton.b -text {use multiple devices} \
-            -command  {pd pd midi-properties 1 \;}
-        pack $id.longbutton.b
+		match_linux_wm [list button $id.longbutton.b \
+			-text {use multiple devices} \
+			-command  {pd pd midi-properties 1 \;}]
+        pack $id.longbutton.b -pady 3
     }
 }
 
@@ -4716,6 +5811,7 @@ proc pdtk_alsa_midi_dialog {id indev1 indev2 indev3 indev4 \
     global midi_outdev1 midi_outdev2 midi_outdev3 midi_outdev4
     global midi_indevlist midi_outdevlist
     global midi_alsain midi_alsaout
+	global pd_nt
 
     set midi_indev1 $indev1
     set midi_indev2 $indev2
@@ -4729,131 +5825,188 @@ proc pdtk_alsa_midi_dialog {id indev1 indev2 indev3 indev4 \
     set midi_alsaout [llength $midi_outdevlist]
     
     toplevel $id
-    wm group $id .
-    wm title $id {midi}
+    match_linux_wm [list $id configure]
+	wm resizable $id 0 0
+	wm title $id {MIDI Settings}
     wm protocol $id WM_DELETE_WINDOW [concat midi_cancel $id]
 
     pdtk_panelkeybindings $id "midi"
 
-    frame $id.buttonframe
-    pack $id.buttonframe -side bottom -fill x -pady 2m
-    button $id.buttonframe.cancel -text {Cancel}\
-        -command "midi_cancel $id"
-    button $id.buttonframe.apply -text {Apply}\
-        -command "midi_apply $id"
-    button $id.buttonframe.ok -text {OK}\
-        -command "midi_ok $id"
-    pack $id.buttonframe.cancel -side left -expand 1
-    pack $id.buttonframe.apply -side left -expand 1
-    pack $id.buttonframe.ok -side left -expand 1
-
-    frame $id.in1f
+    match_linux_wm [list frame $id.buttonframe]
+    pack $id.buttonframe -side bottom -fill x -pady 3
+	match_linux_wm [list button $id.buttonframe.cancel -text {Cancel}\
+	    -command "midi_cancel $id"]
+	match_linux_wm [list button $id.buttonframe.apply -text {Apply}\
+	    -command "midi_apply $id"]
+	match_linux_wm [list button $id.buttonframe.ok -text {OK}\
+	    -command "midi_ok $id"]
+    pack $id.buttonframe.cancel -side left -expand 1 -padx 3
+    pack $id.buttonframe.apply -side left -expand 1 -padx 3
+    pack $id.buttonframe.ok -side left -expand 1 -padx 3
+
+    match_linux_wm [list frame $id.in1f]
     pack $id.in1f -side top
 
-  if {$alsa == 0} {
-        # input device 1
-    label $id.in1f.l1 -text "input device 1:"
-    button $id.in1f.x1 -text [lindex $midi_indevlist $midi_indev1] \
-        -command [list midi_popup $id $id.in1f.x1 midi_indev1 $midi_indevlist]
-    pack $id.in1f.l1 $id.in1f.x1 -side left
+	if {$alsa == 0} {
+	    # input device 1
+	    match_linux_wm [list label $id.in1f.l1 -text "  input device 1:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+	    	match_linux_wm [list ttk::combobox $id.in1f.x1 \
+				-state readonly \
+		        $midi_indevlist]
+			$id.in1f.x1 current 0
+		} else {
+			button $id.in1f.x1 -text [lindex $midi_indevlist $midi_indev1] \
+		        -command [list midi_popup $id $id.in1f.x1 \
+				midi_indev1 $midi_indevlist]
+		}
+	    pack $id.in1f.l1 $id.in1f.x1 -side left -pady 3
 
         # input device 2
-    if {$longform && [llength $midi_indevlist] > 2} {
-        frame $id.in2f
-        pack $id.in2f -side top
-
-        label $id.in2f.l1 -text "input device 2:"
-        button $id.in2f.x1 -text [lindex $midi_indevlist $midi_indev2] \
-            -command [list midi_popup $id $id.in2f.x1 midi_indev2 \
-                $midi_indevlist]
-        pack $id.in2f.l1 $id.in2f.x1 -side left
-    }
-
-        # input device 3
-    if {$longform && [llength $midi_indevlist] > 3} {
-        frame $id.in3f
-        pack $id.in3f -side top
-
-        label $id.in3f.l1 -text "input device 3:"
-        button $id.in3f.x1 -text [lindex $midi_indevlist $midi_indev3] \
-            -command [list midi_popup $id $id.in3f.x1 midi_indev3 \
-                $midi_indevlist]
-        pack $id.in3f.l1 $id.in3f.x1 -side left
-    }
+		if {$longform && [llength $midi_indevlist] > 1} {
+		    match_linux_wm [list frame $id.in2f]
+		    pack $id.in2f -side top
+		    match_linux_wm [list label $id.in2f.l1 -text "  input device 2:"]
+			if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+				match_linux_wm [list ttk::combobox $id.in2f.x1 \
+					-state readonly \
+				    $midi_indevlist]
+				$id.in2f.x1 current 1
+			} else {
+				button $id.in2f.x1 -text [lindex $midi_indevlist $midi_indev2] \
+				    -command [list midi_popup $id $id.in2f.x1 midi_indev2 \
+				        $midi_indevlist]
+			}
+		    pack $id.in2f.l1 $id.in2f.x1 -side left -pady 3
+		}
 
-        # input device 4
-    if {$longform && [llength $midi_indevlist] > 4} {
-        frame $id.in4f
-        pack $id.in4f -side top
+		# input device 3
+		if {$longform && [llength $midi_indevlist] > 2} {
+		    match_linux_wm [list frame $id.in3f]
+		    pack $id.in3f -side top
+		    match_linux_wm [list label $id.in3f.l1 -text "  input device 3:"]
+			if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+				match_linux_wm [list ttk::combobox $id.in3f.x1 \
+					-state readonly \
+				    $midi_indevlist]
+				$id.in3f.x1 current 2
+			} else {
+				button $id.in3f.x1 -text [lindex $midi_indevlist $midi_indev3] \
+				    -command [list midi_popup $id $id.in3f.x1 midi_indev3 \
+				        $midi_indevlist]
+			}
+		    pack $id.in3f.l1 $id.in3f.x1 -side left -pady 3
+		}
 
-        label $id.in4f.l1 -text "input device 4:"
-        button $id.in4f.x1 -text [lindex $midi_indevlist $midi_indev4] \
-            -command [list midi_popup $id $id.in4f.x1 midi_indev4 \
-                $midi_indevlist]
-        pack $id.in4f.l1 $id.in4f.x1 -side left
-    }
+		# input device 4
+		if {$longform && [llength $midi_indevlist] > 3} {
+		    match_linux_wm [list frame $id.in4f]
+		    pack $id.in4f -side top
+		    match_linux_wm [list label $id.in4f.l1 -text "  input device 4:"]
+			if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+				match_linux_wm [list ttk::combobox $id.in4f.x1 \
+					-state readonly \
+				    $midi_indevlist]
+				$id.in4f.x1 current 3
+			} else {
+				button $id.in4f.x1 -text [lindex $midi_indevlist $midi_indev4] \
+				    -command [list midi_popup $id $id.in4f.x1 midi_indev4 \
+				        $midi_indevlist]
+			}
 
-        # output device 1
+		    pack $id.in4f.l1 $id.in4f.x1 -side left -pady 3
+		}
 
-    frame $id.out1f
-    pack $id.out1f -side top
-    label $id.out1f.l1 -text "output device 1:"
-    button $id.out1f.x1 -text [lindex $midi_outdevlist $midi_outdev1] \
-        -command [list midi_popup $id $id.out1f.x1 midi_outdev1 \
-            $midi_outdevlist]
-    pack $id.out1f.l1 $id.out1f.x1 -side left
+		# output device 1
+		match_linux_wm [list frame $id.out1f]
+		pack $id.out1f -side top
+		match_linux_wm [list label $id.out1f.l1 -text "output device 1:"]
+		if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+	    	match_linux_wm [list ttk::combobox $id.out1f.x1 \
+				-state readonly \
+		        $midi_outdevlist]
+			$id.out1f.x1 current 0
+		} else {
+			button $id.out1f.x1 -text [lindex $midi_outdevlist $midi_outdev1] \
+				-command [list midi_popup $id $id.out1f.x1 midi_outdev1 \
+				    $midi_outdevlist]
+		}
+		pack $id.out1f.l1 $id.out1f.x1 -side left -pady 3
+
+		# output device 2
+		if {$longform && [llength $midi_outdevlist] > 1} {
+		    match_linux_wm [list frame $id.out2f]
+		    pack $id.out2f -side top
+		    match_linux_wm [list label $id.out2f.l1 -text "output device 2:"]
+			if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+				match_linux_wm [list ttk::combobox $id.out2f.x1 \
+					-state readonly \
+				    $midi_outdevlist]
+				$id.out2f.x1 current 1
+			} else {
+				button $id.out2f.x1 -text [lindex $midi_outdevlist $midi_outdev2] \
+				    -command [list midi_popup $id $id.out2f.x1 \
+					midi_outdev2 $midi_outdevlist]
+			}
+		    pack $id.out2f.l1 $id.out2f.x1 -side left -pady 3
+		}
 
-        # output device 2
-    if {$longform && [llength $midi_outdevlist] > 2} {
-        frame $id.out2f
-        pack $id.out2f -side top
-        label $id.out2f.l1 -text "output device 2:"
-        button $id.out2f.x1 -text [lindex $midi_outdevlist $midi_outdev2] \
-            -command \
-            [list midi_popup $id $id.out2f.x1 midi_outdev2 $midi_outdevlist]
-        pack $id.out2f.l1 $id.out2f.x1 -side left
-    }
+		# output device 3
+		if {$longform && [llength $midi_outdevlist] > 2} {
+		    match_linux_wm [list frame $id.out3f]
+		    pack $id.out3f -side top
+		    match_linux_wm [list label $id.out3f.l1 -text "output device 3:"]
+			if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+				match_linux_wm [list ttk::combobox $id.out3f.x1 \
+					-state readonly \
+				    $midi_outdevlist]
+				$id.out3f.x1 current 2
+			} else {
+				button $id.out3f.x1 -text [lindex $midi_outdevlist $midi_outdev3] \
+				    -command [list midi_popup $id $id.out3f.x1 \
+					midi_outdev3 $midi_outdevlist]
+			}
+		    pack $id.out3f.l1 $id.out3f.x1 -side left -pady 3
+		}
 
-        # output device 3
-    if {$longform && [llength $midi_outdevlist] > 3} {
-        frame $id.out3f
-        pack $id.out3f -side top
-        label $id.out3f.l1 -text "output device 3:"
-        button $id.out3f.x1 -text [lindex $midi_outdevlist $midi_outdev3] \
-            -command \
-            [list midi_popup $id $id.out3f.x1 midi_outdev3 $midi_outdevlist]
-        pack $id.out3f.l1 $id.out3f.x1 -side left
-    }
+		# output device 4
+		if {$longform && [llength $midi_outdevlist] > 3} {
+		    match_linux_wm [list frame $id.out4f]
+		    pack $id.out4f -side top
+		    match_linux_wm [list label $id.out4f.l1 -text "output device 4:"]
+			if {[info tclversion] >= 8.5 && $pd_nt == 0} {
+				match_linux_wm [list ttk::combobox $id.out4f.x1 \
+					-state readonly \
+				    $midi_outdevlist]
+				$id.out4f.x1 current 3
+			} else {
+				button $id.out4f.x1 -text [lindex $midi_outdevlist $midi_outdev4] \
+				    -command [list midi_popup $id $id.out4f.x1 \
+					midi_outdev4 $midi_outdevlist]
+			}
+		    pack $id.out4f.l1 $id.out4f.x1 -side left -pady 3
+		}
 
-        # output device 4
-    if {$longform && [llength $midi_outdevlist] > 4} {
-        frame $id.out4f
-        pack $id.out4f -side top
-        label $id.out4f.l1 -text "output device 4:"
-        button $id.out4f.x1 -text [lindex $midi_outdevlist $midi_outdev4] \
-            -command \
-            [list midi_popup $id $id.out4f.x1 midi_outdev4 $midi_outdevlist]
-        pack $id.out4f.l1 $id.out4f.x1 -side left
-    }
+		# if not the "long form" make a button to
+		# restart with longform set. 
+		
+		if {$longform == 0} {
+		    match_linux_wm [list frame $id.longbutton]
+		    pack $id.longbutton -side top
+			match_linux_wm [list button $id.longbutton.b \
+				-text {use multiple alsa devices} \
+			    -command  {pd pd midi-properties 1 \;}]
+		    pack $id.longbutton.b -pady 3
+		}
+	}
 
-        # if not the "long form" make a button to
-        # restart with longform set. 
-    
-    if {$longform == 0} {
-        frame $id.longbutton
-        pack $id.longbutton -side top
-        button $id.longbutton.b -text {use multiple alsa devices} \
-            -command  {pd pd midi-properties 1 \;}
-        pack $id.longbutton.b
-    }
-    }
     if {$alsa} {
-        label $id.in1f.l1 -text "In Ports:"
-        entry $id.in1f.x1 -textvariable midi_alsain -width 4
-        pack $id.in1f.l1 $id.in1f.x1 -side left
-        label $id.in1f.l2 -text "Out Ports:"
-        entry $id.in1f.x2 -textvariable midi_alsaout -width 4
-        pack $id.in1f.l2 $id.in1f.x2 -side left
+        match_linux_wm [list label $id.in1f.l1 -text "In Ports:"]
+        match_linux_wm [list entry $id.in1f.x1 -textvariable midi_alsain -width 4]
+        pack $id.in1f.l1 $id.in1f.x1 -side left -pady 3
+        match_linux_wm [list label $id.in1f.l2 -text "Out Ports:"]
+        match_linux_wm [list entry $id.in1f.x2 -textvariable midi_alsaout -width 4]
+        pack $id.in1f.l2 $id.in1f.x2 -side left -pady 3
     }
 }
 
@@ -4988,16 +6141,17 @@ namespace eval ScrollBox {
     # edit_method - method to be called when we edit an existing item
     proc make { id listdata add_method edit_method } {
         global pd_nt
-        frame $id.listbox
-        listbox $id.listbox.box \
+        match_linux_wm [list frame $id.listbox]
+        match_linux_wm [list listbox $id.listbox.box \
             -selectmode browse -activestyle dotbox \
-            -yscrollcommand [list "$id.listbox.scrollbar" set]
+            -yscrollcommand [list "$id.listbox.scrollbar" set] \
+			-relief sunken -bd 1 -highlightthickness 0 -takefocus 0]
 
         # Create a scrollbar and keep it in sync with the current
         # listbox view
-        pack $id.listbox.box [scrollbar "$id.listbox.scrollbar" \
-                -command [list $id.listbox.box yview]] \
-                -side left -fill y -anchor w 
+        pack $id.listbox.box [match_linux_wm [list scrollbar "$id.listbox.scrollbar" \
+                -command [list $id.listbox.box yview]]] \
+                -side left -fill y -anchor w -pady 3
 
         # Populate the listbox widget
         foreach item $listdata {
@@ -5029,18 +6183,26 @@ namespace eval ScrollBox {
         # All widget interactions can be performed without buttons, but
         # we still need a "New..." button since the currently visible window
         # might be full (even though the user can still expand it)
-        frame $id.actions 
-        pack $id.actions -side top -padx 2m -fill x 
-        button $id.actions.add_path -text {New...} \
-            -command "ScrollBox::add_item $id $add_method"
-        button $id.actions.edit_path -text {Edit...} \
-            -command "ScrollBox::edit_item $id $edit_method"
-        button $id.actions.delete_path -text {Delete} \
-            -command "ScrollBox::delete_item $id"
-
-        pack $id.actions.delete_path -side right -pady 2m
-        pack $id.actions.edit_path -side right -pady 2m
-        pack $id.actions.add_path -side right -pady 2m
+        match_linux_wm [list frame $id.actions] 
+        pack $id.actions -side top -padx 2m -fill x
+		if { [info tclversion] >= 8.5 && $pd_nt == 0} {
+			ttk::button $id.actions.add_path -text {New...} \
+			    -command "ScrollBox::add_item $id $add_method"
+			ttk::button $id.actions.edit_path -text {Edit...} \
+			    -command "ScrollBox::edit_item $id $edit_method"
+			ttk::button $id.actions.delete_path -text {Delete} \
+			    -command "ScrollBox::delete_item $id"
+		} else {
+			button $id.actions.add_path -text {New...} \
+			    -command "ScrollBox::add_item $id $add_method"
+			button $id.actions.edit_path -text {Edit...} \
+			    -command "ScrollBox::edit_item $id $edit_method"
+			button $id.actions.delete_path -text {Delete} \
+			    -command "ScrollBox::delete_item $id"
+		}
+        pack $id.actions.delete_path -side right -pady 2m -padx 3
+        pack $id.actions.edit_path -side right -pady 2m -padx 3
+        pack $id.actions.add_path -side right -pady 2m -padx 3
 
         $id.listbox.box activate end
         $id.listbox.box selection set end
@@ -5097,8 +6259,12 @@ namespace eval dlg_ScrollBoxWindow {
     # title -- top-level title for the dialog
     # width, height -- initial width and height dimensions for the window, also minimum size
     proc make { id listdata add_method edit_method commit_method title width height } {
-        toplevel $id -class DialogWindow
+		global pd_nt
+ 
+		toplevel $id
+		match_linux_wm [list $id configure]
         wm title $id $title
+		
         wm protocol $id WM_DELETE_WINDOW [concat dlg_ScrollBoxWindow::cancel $id]
 
         # Enforce a minimum size for the window
@@ -5115,22 +6281,37 @@ namespace eval dlg_ScrollBoxWindow {
 
         # Use two frames for the buttons, since we want them both
         # bottom and right
-        frame $id.nb
+        match_linux_wm [list frame $id.nb]
         pack $id.nb -side bottom -fill x -pady 2m
 
-        frame $id.nb.buttonframe
+        match_linux_wm [list frame $id.nb.buttonframe]
         pack $id.nb.buttonframe -side right -padx 2m
 
-        button $id.nb.buttonframe.cancel -text {Cancel}\
-            -command "dlg_ScrollBoxWindow::cancel $id"
-        button $id.nb.buttonframe.apply -text {Apply}\
-            -command "dlg_ScrollBoxWindow::apply $id $commit_method"
-        button $id.nb.buttonframe.ok -text {OK}\
-            -command "dlg_ScrollBoxWindow::ok $id $commit_method"
+		if { [info tclversion] >= 8.5 && $pd_nt == 0} {
+			ttk::button $id.nb.buttonframe.cancel \
+				-text {Cancel} \
+			    -command "dlg_ScrollBoxWindow::cancel $id"
+		   	ttk::button $id.nb.buttonframe.apply \
+				-text {Apply} \
+			    -command "dlg_ScrollBoxWindow::apply $id $commit_method"
+			ttk::button $id.nb.buttonframe.ok \
+				-text {OK} \
+			    -command "dlg_ScrollBoxWindow::ok $id $commit_method"
+		} else {
+			button $id.nb.buttonframe.cancel \
+				-text {Cancel} \
+			    -command "dlg_ScrollBoxWindow::cancel $id"
+		   	button $id.nb.buttonframe.apply \
+				-text {Apply} \
+			    -command "dlg_ScrollBoxWindow::apply $id $commit_method"
+			button $id.nb.buttonframe.ok \
+				-text {OK} \
+			    -command "dlg_ScrollBoxWindow::ok $id $commit_method"
+		}
 
-        pack $id.nb.buttonframe.cancel -side left -expand 1 -padx 2m
-        pack $id.nb.buttonframe.apply -side left -expand 1 -padx 2m
-        pack $id.nb.buttonframe.ok -side left -expand 1 -padx 2m
+        pack $id.nb.buttonframe.cancel -side left -expand 1 -padx 3
+        pack $id.nb.buttonframe.apply -side left -expand 1 -padx 3
+        pack $id.nb.buttonframe.ok -side left -expand 1 -padx 3
    }
 }
 
@@ -5138,7 +6319,9 @@ namespace eval dlg_ScrollBoxWindow {
 ############ pdtk_path_dialog -- dialog window for search path #########
 namespace eval dlg_Path {
     proc choosePath { curValue title } {
-        if {! [file exist $curValue] } {set curValue "~"}
+        if {$curValue == ""} {
+            set curValue "~"
+        }
         return [tk_chooseDirectory -initialdir $curValue -title $title]
     }
 
@@ -5161,21 +6344,24 @@ namespace eval dlg_Path {
     proc init { id extrapath verbose } {
         global pd_extrapath pd_verbose
         global pd_path
+		global pd_nt
 
         set pd_extrapath $extrapath
         set pd_verbose $verbose
 
         dlg_ScrollBoxWindow::make $id $pd_path \
             dlg_Path::add dlg_Path::edit dlg_Path::commit \
-            {PD search path for patches and other files} \
+            {Pd Search Path for Patches and Other Files} \
             400 300 
 
-        frame $id.extraframe
-        pack $id.extraframe -side bottom -pady 2m
-        checkbutton $id.extraframe.extra -text {use standard extensions} \
-            -variable pd_extrapath -anchor w 
-        checkbutton $id.extraframe.verbose -text {verbose} \
-            -variable pd_verbose -anchor w 
+        match_linux_wm [list frame $id.extraframe]
+        pack $id.extraframe -side bottom -pady 3
+        match_linux_wm [list checkbutton $id.extraframe.extra \
+			-text {use standard extensions} \
+            -variable pd_extrapath]
+        match_linux_wm [list checkbutton $id.extraframe.verbose \
+			-text {verbose} \
+            -variable pd_verbose] 
         pack $id.extraframe.extra $id.extraframe.verbose \
             -side left -expand 1
     }
@@ -5246,21 +6432,26 @@ namespace eval dlg_Startup {
 
         dlg_ScrollBoxWindow::make $id $pd_startup \
             dlg_Startup::add dlg_Startup::edit dlg_Startup::commit \
-            {PD binaries to load (on next startup)} \
+            {Pd Binaries to Load (on Next Startup)} \
             400 300
 
-        label $id.entryname -text {startup flags:}
-        entry $id.entry -textvariable pd_flags -width 60
-        pdtk_standardkeybindings $id.entry
-        pack $id.entryname $id.entry -side left
-        pack $id.entry -side right -padx 2m -fill x -expand 1
+		match_linux_wm [list frame $id.startup]
+		pack $id.startup -padx 5
+        match_linux_wm [list label $id.startup.entryname -text {startup flags:}]
+        match_linux_wm [list entry $id.startup.entry -textvariable pd_flags -width 60]
+        pdtk_standardkeybindings $id.startup.entry
+        pack $id.startup.entryname $id.startup.entry -side left -padx 3
+        pack $id.startup.entry -side right -fill x -expand 1 -padx 3
 
-        frame $id.nortframe
-        pack $id.nortframe -side bottom -fill x -pady 2m
+        match_linux_wm [list frame $id.nortframe]
+        pack $id.nortframe -fill x -padx 5
         if {$pd_nt != 1} {
-            checkbutton $id.nortframe.nort -text {defeat real-time scheduling} \
-                -variable pd_nort -anchor w
+            match_linux_wm [list checkbutton $id.nortframe.nort \
+				-text {defeat real-time scheduling} \
+                -variable pd_nort]
+			pack $id.nortframe.nort -side right -padx 3
         }
+
    }
 }
 
@@ -5268,3 +6459,320 @@ proc pdtk_startup_dialog {id nort flags} {
     dlg_Startup::init $id $nort $flags
 }
 
+################## define custom'n'purty linux color picker ##################
+# by Ivica Ico Bukvic
+
+# color_applied must be exposed for iem apply and cancel 
+set color_applied -1
+
+if { [info tclversion] >= 8.5 && $pd_nt == 0 } {
+
+	set rgb_r 0
+	set rgb_g 0
+	set rgb_b 0
+
+	set hex_color "#000000"
+
+	set saved_color_1 "#999999"
+	set saved_color_2 "#777777"
+	set saved_color_3 "#555555"
+
+	proc set_color_channel {id input channel value} {
+		global rgb_r rgb_g rgb_b hex_color
+		if {$input == 1} {
+			#using scale (we will reserve input var for future widget expansion)
+			set target [expr int($value*255+0.5)]
+			switch $channel {
+				r { set rgb_r $target }
+				g { set rgb_g $target }
+				b { set rgb_b $target }
+			}		
+			$id.settings.rgb.$channel.label configure -text $target
+			
+		}
+		#prepare hex version
+		if {$rgb_r < 16} {
+			set hex_r "0[format %x $rgb_r]"
+		} else {
+			set hex_r [format %x $rgb_r]
+		}
+		if {$rgb_g < 16} {
+			set hex_g "0[format %x $rgb_g]"
+		} else {
+			set hex_g [format %x $rgb_g]
+		}
+		if {$rgb_b < 16} {
+			set hex_b "0[format %x $rgb_b]"
+		} else {
+			set hex_b [format %x $rgb_b]
+		}
+		set hex_color "#$hex_r$hex_g$hex_b"
+		$id.settings.rgb.hex.entry delete 0 end
+		$id.settings.rgb.hex.entry insert 0 $hex_color
+		$id.settings.preview.view configure -bg $hex_color
+
+		#the following is way too inefficient
+		#ttk::style configure preview.TLabel -background "$hex_color"
+	}
+
+	proc pdtk_pd_color_dlg {color} {
+		global rgb_r rgb_g rgb_b hex_color color_applied
+		global saved_color_1 saved_color_2 saved_color_3
+		global ctrl_key
+
+		if { [winfo exists .color_dlg.settings] } {
+			destroy .color_dlg
+		}
+		set color_applied 0
+
+		set name .color_dlg
+
+		#parse out incoming color
+		set hex_color $color
+
+		set char_list [split $color {}]
+		set hex_rgb_r [lindex $char_list 1][lindex $char_list 2]
+		set hex_rgb_g [lindex $char_list 3][lindex $char_list 4]
+		set hex_rgb_b [lindex $char_list 5][lindex $char_list 6]
+		set rgb_r [expr 0x$hex_rgb_r]
+		set rgb_g [expr 0x$hex_rgb_g]
+		set rgb_b [expr 0x$hex_rgb_b]
+
+		toplevel $name
+
+		wm resizable $name 0 0
+		#global tmp_xpix tmp_ypix
+		#wm geometry $name "+$tmp_xpix+$tmp_ypix"
+		match_linux_wm [list $name configure]
+		wm title $name {Compose Custom Color}
+
+		bind $name <Control-t> {texteditor_ok %W}
+		bind $name <Control-s> {texteditor_send %W}
+
+		match_linux_wm [list frame $name.settings]
+		pack $name.settings -side top
+
+		match_linux_wm [list frame $name.settings.rgb]
+		pack $name.settings.rgb -side left -fill y -padx 3 -pady 3
+		ttk::label $name.settings.rgb.title -text {color channels}
+
+		match_linux_wm [list frame $name.settings.rgb.r]
+		ttk::label $name.settings.rgb.r.title -text {R} -width 1
+		ttk::scale $name.settings.rgb.r.scale -length 285 \
+			-command "set_color_channel $name 1 r" \
+			-value [expr $rgb_r/255.0]
+		ttk::label $name.settings.rgb.r.label -width 3 -text $rgb_r -relief sunken
+		pack $name.settings.rgb.r.label $name.settings.rgb.r.scale \
+			$name.settings.rgb.r.title -side left -padx 2
+
+		match_linux_wm [list frame $name.settings.rgb.g]
+		ttk::label $name.settings.rgb.g.title -text {G} -width 1
+		ttk::scale $name.settings.rgb.g.scale -length 285 \
+			-command "set_color_channel $name 1 g" \
+			-value [expr $rgb_g/255.0]
+		ttk::label $name.settings.rgb.g.label -width 3 -text $rgb_g -relief sunken
+		pack $name.settings.rgb.g.label \
+			$name.settings.rgb.g.scale \
+			$name.settings.rgb.g.title \
+			-side left -padx 2
+
+		match_linux_wm [list frame $name.settings.rgb.b]
+		ttk::label $name.settings.rgb.b.title -text {B} -width 1
+		ttk::scale $name.settings.rgb.b.scale -length 285 \
+			-command "set_color_channel $name 1 b" \
+			-value [expr $rgb_b/255.0]
+		ttk::label $name.settings.rgb.b.label -width 3 -text $rgb_b -relief sunken
+		pack $name.settings.rgb.b.label $name.settings.rgb.b.scale \
+			$name.settings.rgb.b.title -side left -padx 2
+
+		match_linux_wm [list frame $name.settings.rgb.hex]
+		ttk::label $name.settings.rgb.hex.label -text {hex value:}
+		ttk::entry $name.settings.rgb.hex.entry -width 8 -validate focusout \
+			-validatecommand "pdtk_pd_color_from_hex $name %P"
+		$name.settings.rgb.hex.entry insert 0 $color
+		ttk::label $name.settings.rgb.hex.saved -text {recall presets:}
+		label $name.settings.rgb.hex.saved1 \
+			-text " 1 " -relief sunken -bd 1 -bg $saved_color_1
+		bind $name.settings.rgb.hex.saved1 \
+			<Button> "pdtk_pd_color_dialog_recall $name 1"
+		label $name.settings.rgb.hex.saved2 \
+			-text " 2 " -relief sunken -bd 1 -bg $saved_color_2
+		bind $name.settings.rgb.hex.saved2 \
+			<Button> "pdtk_pd_color_dialog_recall $name 2"
+		label $name.settings.rgb.hex.saved3 \
+			-text " 3 " -relief sunken -bd 1 -bg $saved_color_3
+		bind $name.settings.rgb.hex.saved3 \
+			<Button> "pdtk_pd_color_dialog_recall $name 3"
+		pack $name.settings.rgb.hex.label \
+			$name.settings.rgb.hex.entry \
+			$name.settings.rgb.hex.saved \
+			$name.settings.rgb.hex.saved1 \
+			$name.settings.rgb.hex.saved2 \
+			$name.settings.rgb.hex.saved3 \
+			-side left -padx 2
+
+		pack $name.settings.rgb.title $name.settings.rgb.r \
+			$name.settings.rgb.g $name.settings.rgb.b \
+			$name.settings.rgb.hex -side top -pady 3
+
+		match_linux_wm [list frame $name.settings.preview]
+		pack $name.settings.preview -side right -fill both \
+			-ipadx 3 -padx 3 -pady 3 -expand 1
+		ttk::label $name.settings.preview.title -text {preview}
+		label $name.settings.preview.view -bg $color -relief sunken -bd 1 \
+			-text "                         \n\n\n\n\n"
+		pack $name.settings.preview.title $name.settings.preview.view \
+			-side top -pady 3
+
+		ttk::separator $name.eyecandy
+		pack $name.eyecandy -fill x -expand 0 -pady 3
+
+		match_linux_wm [list frame $name.buttons]
+		pack $name.buttons -padx 3 -pady 3
+		ttk::button $name.buttons.cancel -text {Cancel} \
+			-command "pdtk_pd_color_dialog_cancel $name $color"
+		ttk::label $name.buttons.saveto -text {save to preset:}
+		ttk::button $name.buttons.save1 -text {1} -width 2 \
+			-command "pdtk_pd_color_dialog_save $name 1"
+		ttk::button $name.buttons.save2 -text {2} -width 2 \
+			-command "pdtk_pd_color_dialog_save $name 2"
+		ttk::button $name.buttons.save3 -text {3} -width 2 \
+			-command "pdtk_pd_color_dialog_save $name 3"
+		ttk::button $name.buttons.apply -text {Select Color} \
+			-command "pdtk_pd_color_dialog_ok $name"
+
+		pack $name.buttons.cancel \
+			$name.buttons.saveto \
+			$name.buttons.save1 \
+			$name.buttons.save2 \
+			$name.buttons.save3 \
+			$name.buttons.apply -side left -padx 3
+
+    	bind $name <KeyPress-Return> \
+			[format "pdtk_pd_color_dialog_ok %s" $name]
+    	bind $name <$ctrl_key-Key-w> \
+			[format "pdtk_pd_color_dialog_cancel %s %s" $name $color]
+		bind $name <KeyPress-Escape> \
+			[format "pdtk_pd_color_dialog_cancel %s %s" $name $color]
+
+		bind $name.settings.rgb.hex.entry <$ctrl_key-Key-x> \
+			[format "menu_cut %s" $name.settings.rgb.hex.entry]
+		bind $name.settings.rgb.hex.entry <$ctrl_key-Key-c> \
+			[format "menu_copy %s" $name.settings.rgb.hex.entry]
+		bind $name.settings.rgb.hex.entry <$ctrl_key-Key-v> \
+			[format "menu_paste %s" $name.settings.rgb.hex.entry]
+		bind $name.settings.rgb.hex.entry <$ctrl_key-Key-a> \
+			[format "menu_selectall %s" $name.settings.rgb.hex.entry]
+
+		pdtk_standardkeybindings $name
+
+		return $name
+	}
+
+	proc pdtk_pd_color_dialog_save {id num} {
+		global saved_color_1 saved_color_2 saved_color_3 hex_color
+		[concat $id.settings.rgb.hex.saved$num] configure -bg $hex_color
+		set [concat saved_color_$num] $hex_color
+	}
+
+	proc pdtk_pd_color_dialog_recall {id num} {
+		global saved_color_1 saved_color_2 saved_color_3 hex_color
+		global rgb_r rgb_g rgb_b
+		switch -- $num {
+			1	{set hex_color $saved_color_1}
+			2	{set hex_color $saved_color_2}
+			3	{set hex_color $saved_color_3}
+		}
+		set char_list [split $hex_color {}]
+		set hex_rgb_r [lindex $char_list 1][lindex $char_list 2]
+		set hex_rgb_g [lindex $char_list 3][lindex $char_list 4]
+		set hex_rgb_b [lindex $char_list 5][lindex $char_list 6]
+		set rgb_r [expr 0x$hex_rgb_r]
+		set rgb_g [expr 0x$hex_rgb_g]
+		set rgb_b [expr 0x$hex_rgb_b]
+
+		#reset widgets
+		$id.settings.rgb.r.scale configure -value [expr $rgb_r/255.0]
+		$id.settings.rgb.g.scale configure -value [expr $rgb_g/255.0]
+		$id.settings.rgb.b.scale configure -value [expr $rgb_b/255.0]
+		$id.settings.rgb.r.label configure -text $rgb_r
+		$id.settings.rgb.g.label configure -text $rgb_g
+		$id.settings.rgb.b.label configure -text $rgb_b
+		$id.settings.rgb.hex.entry delete 0 end
+		$id.settings.rgb.hex.entry insert 0 $hex_color
+		$id.settings.preview.view configure -bg $hex_color
+	}	
+
+	proc pdtk_pd_color_dialog_cancel {id color} {
+		global hex_color color_applied
+		set hex_color $color
+		destroy $id
+		set color_applied 1
+	}
+
+	proc pdtk_pd_color_dialog_ok {id} {
+		global hex_color color_applied
+		if ([string compare $hex_color [$id.settings.rgb.hex.entry get]]) {
+			pdtk_pd_color_from_hex $id [$id.settings.rgb.hex.entry get]
+		}
+		destroy $id;
+		set color_applied 1
+	}
+
+	proc pdtk_pd_color_from_hex {id color} {
+		global rgb_r rgb_g rgb_b hex_color
+
+		set hex_color $color
+
+		set char_list [split $hex_color {}]
+		set hex_rgb_r [lindex $char_list 1][lindex $char_list 2]
+		set hex_rgb_g [lindex $char_list 3][lindex $char_list 4]
+		set hex_rgb_b [lindex $char_list 5][lindex $char_list 6]
+
+		if { [catch {expr 0x$hex_rgb_r} fid] } {
+			set rgb_r 0
+			set hex_rgb_r "00"
+		} else {
+			set rgb_r [expr 0x$hex_rgb_r]
+		}
+
+		if { [catch {expr 0x$hex_rgb_g} fid] } {
+			set rgb_g 0
+			set hex_rgb_g "00"
+		} else {
+			set rgb_g [expr 0x$hex_rgb_g]
+		}
+
+		if { [catch {expr 0x$hex_rgb_b} fid] } {
+			set rgb_b 0
+			set hex_rgb_b "00"
+		} else {
+			set rgb_b [expr 0x$hex_rgb_b]
+		}
+
+		if {[string length $hex_rgb_r] < 2} {
+			set hex_rgb_r "0$hex_rgb_r"
+		}
+		if {[string length $hex_rgb_g] < 2} {
+			set hex_rgb_g "0$hex_rgb_g"
+		}
+		if {[string length $hex_rgb_b] < 2} {
+			set hex_rgb_b "0$hex_rgb_b"
+		}
+
+		set hex_color "#$hex_rgb_r$hex_rgb_g$hex_rgb_b"
+
+		#set widgets
+		$id.settings.rgb.r.scale configure -value [expr $rgb_r/255.0]
+		$id.settings.rgb.g.scale configure -value [expr $rgb_g/255.0]
+		$id.settings.rgb.b.scale configure -value [expr $rgb_b/255.0]
+		$id.settings.rgb.r.label configure -text $rgb_r
+		$id.settings.rgb.g.label configure -text $rgb_g
+		$id.settings.rgb.b.label configure -text $rgb_b
+		$id.settings.rgb.hex.entry delete 0 end
+		$id.settings.rgb.hex.entry insert 0 $hex_color
+		$id.settings.preview.view configure -bg $hex_color
+		return 0
+	}
+}
+
diff --git a/src/s_audio.c b/src/s_audio.c
index 67555ac25..cfd2c64ea 100644
--- a/src/s_audio.c
+++ b/src/s_audio.c
@@ -75,6 +75,11 @@ static int audio_nextinchans, audio_nextoutchans;
 void sched_audio_callbackfn(void);
 void sched_reopenmeplease(void);
 
+#ifdef USEAPI_JACK
+	/* needed to fix srate when using jack, inclded in s_audio_jack.c */
+extern int jack_get_srate(void);
+#endif /* JACK */
+
 static int audio_isopen(void)
 {
     return (audio_state &&
@@ -95,7 +100,14 @@ void sys_get_audio_params(
     *pnaudiooutdev = audio_naudiooutdev;
     for (i = 0; i < MAXAUDIOOUTDEV; i++)
         paudiooutdev[i] = audio_audiooutdev[i],
-            choutdev[i] = audio_audiochoutdev[i]; 
+            choutdev[i] = audio_audiochoutdev[i];
+#ifdef USEAPI_JACK
+	if (sys_audioapiopened == API_JACK) {
+		if (jack_get_srate()) {
+			audio_rate = jack_get_srate();
+		}
+	}
+#endif /* JACK */
     *prate = audio_rate;
     *padvance = audio_advance;
     *pcallback = audio_callback;
@@ -659,6 +671,12 @@ void glob_audio_properties(t_pd *dummy, t_floatarg flongform)
     sys_get_audio_params(&naudioindev, audioindev, chindev,
         &naudiooutdev, audiooutdev, choutdev, &rate, &advance, &callback);
 
+#ifdef USEAPI_JACK
+	if (sys_audioapiopened == API_JACK) {
+		sys_setchsr(audio_nextinchans, audio_nextoutchans, rate);
+	}
+#endif /* JACK */
+
     /* post("naudioindev %d naudiooutdev %d longform %f",
             naudioindev, naudiooutdev, flongform); */
     if (naudioindev > 1 || naudiooutdev > 1)
diff --git a/src/s_audio_alsa.c b/src/s_audio_alsa.c
index 328fff0c9..a5034c8dc 100644
--- a/src/s_audio_alsa.c
+++ b/src/s_audio_alsa.c
@@ -469,7 +469,7 @@ int alsa_send_dacs(void)
                 ((char *)(alsa_snd_buf))[3*j+1] = ((s>>8) & 255);
                 ((char *)(alsa_snd_buf))[3*j+2] = ((s>>16) & 255);
 #else
-                fprintf(stderr, "big endian 24-bit not supported");
+                fprintf(stderr("big endian 24-bit not supported");
 #endif
             }
             for (; i < thisdevchans; i++, ch++)
@@ -581,7 +581,7 @@ int alsa_send_dacs(void)
                         * (1./ INT32_MAX);
             }
 #else
-                fprintf(stderr, "big endian 24-bit not supported");
+                fprintf(stderr("big endian 24-bit not supported");
 #endif
         }
         else
diff --git a/src/s_audio_jack.c b/src/s_audio_jack.c
index a9e6fa7f9..77bacde54 100644
--- a/src/s_audio_jack.c
+++ b/src/s_audio_jack.c
@@ -13,7 +13,7 @@
 
 
 #define MAX_CLIENTS 100
-#define NUM_JACK_PORTS 128  /* seems like higher values give bad xrun problems */
+#define NUM_JACK_PORTS 128
 #define BUF_JACK 4096
 static jack_nframes_t jack_out_max;
 #define JACK_OUT_MAX  64
@@ -34,6 +34,11 @@ static int jack_dio_error;
 pthread_mutex_t jack_mutex;
 pthread_cond_t jack_sem;
 
+int jack_get_srate(void)
+{
+	if (jack_client) return jack_get_sample_rate (jack_client);
+	else return 0;
+}
 
 static int
 process (jack_nframes_t nframes, void *arg)
@@ -153,7 +158,7 @@ static char** jack_get_clients(void)
              * it in spot 0 put it in spot 0 and move whatever
              * was already in spot 0 to the end. */
 
-            if( strcmp( "alsa_pcm", tmp_client_name ) == 0 && num_clients > 0 )
+            if( strcmp( "system", tmp_client_name ) == 0 && num_clients > 0 )
             {
               char* tmp;
                 /* alsa_pcm goes in spot 0 */
@@ -216,7 +221,7 @@ static int jack_connect_ports(char* client)
 }
 
 
-static void pd_jack_error_callback(const char *desc) {
+void jack_error(const char *desc) {
   error("JACK error: %s", desc);
   return;
 }
@@ -233,11 +238,6 @@ jack_open_audio(int inchans, int outchans, int rate)
         int srate;
         jack_status_t status;
 
-        if(NULL==jack_client_new) {
-            fprintf(stderr,"JACK framework not available\n");
-            return 1;
-        }
-
         jack_dio_error = 0;
         
         if ((inchans == 0) && (outchans == 0)) return 0;
@@ -288,7 +288,7 @@ jack_open_audio(int inchans, int outchans, int rate)
           
           jack_set_process_callback (jack_client, process, 0);
           
-          jack_set_error_function (pd_jack_error_callback);
+          //          jack_set_error_function (jack_error);
           
 #ifdef JACK_XRUN
           jack_set_xrun_callback (jack_client, jack_xrun, NULL);
diff --git a/src/s_audio_jack_old.c b/src/s_audio_jack_old.c
new file mode 100644
index 000000000..3b96e4f84
--- /dev/null
+++ b/src/s_audio_jack_old.c
@@ -0,0 +1,434 @@
+
+
+/* ----------------------- Experimental routines for jack -------------- */
+#ifdef USEAPI_JACK
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "m_pd.h"
+#include "s_stuff.h"
+#include <jack/jack.h>
+#include <regex.h>
+
+
+#define MAX_CLIENTS 100
+#define NUM_JACK_PORTS 128
+#define BUF_JACK 4096
+static jack_nframes_t jack_out_max;
+#define JACK_OUT_MAX  64
+static jack_nframes_t jack_filled = 0;
+static t_sample jack_outbuf[NUM_JACK_PORTS*BUF_JACK];
+static t_sample jack_inbuf[NUM_JACK_PORTS*BUF_JACK];
+static int jack_started = 0;
+
+
+static jack_port_t *input_port[NUM_JACK_PORTS];
+static jack_port_t *output_port[NUM_JACK_PORTS];
+static int outport_count = 0;
+static jack_client_t *jack_client = NULL;
+char *jack_client_names[MAX_CLIENTS];
+static int jack_dio_error;
+
+
+pthread_mutex_t jack_mutex;
+pthread_cond_t jack_sem;
+
+
+static int
+process (jack_nframes_t nframes, void *arg)
+{
+        int j;
+        jack_default_audio_sample_t *out, *in;
+        
+        if (nframes > JACK_OUT_MAX) jack_out_max = nframes;
+        else jack_out_max = JACK_OUT_MAX;
+        if (jack_filled >= nframes) {
+                if (jack_filled != nframes) fprintf(stderr,"Partial read");
+                /* hmm, how to find out whether 't_sample' and 'jack_default_audio_sample_t' are actually the same type??? */
+                if(sizeof(t_sample)==sizeof(jack_default_audio_sample_t)) 
+                {
+                  for (j = 0; j < sys_outchannels;  j++) {
+                        out = jack_port_get_buffer (output_port[j], nframes);
+                        memcpy(out, jack_outbuf + (j * BUF_JACK), sizeof (jack_default_audio_sample_t) * nframes);
+                  }
+                  for (j = 0; j < sys_inchannels; j++) {
+                        in = jack_port_get_buffer( input_port[j], nframes);
+                        memcpy(jack_inbuf + (j * BUF_JACK), in, sizeof (jack_default_audio_sample_t) * nframes);
+                  }
+                } 
+                else
+                {
+                  unsigned int frame=0;
+                  t_sample*data;
+                  for (j = 0; j < sys_outchannels;  j++) {
+                        out = jack_port_get_buffer (output_port[j], nframes);
+                        data=jack_outbuf + (j * BUF_JACK);
+                        for(frame=0; frame<nframes; frame++) {
+                          *out++=*data++;
+                        }
+                  }
+                  for (j = 0; j < sys_inchannels; j++) {
+                        in = jack_port_get_buffer( input_port[j], nframes);
+                        data=jack_inbuf+(j*BUF_JACK);
+                        for(frame=0; frame<nframes; frame++) {
+                          *data++=*in++;
+                        }
+                  }
+                }
+                jack_filled -= nframes;
+        } else { /* PD could not keep up ! */
+             if (jack_started) jack_dio_error = 1;
+             for (j = 0; j < outport_count;  j++) {
+                  out = jack_port_get_buffer (output_port[j], nframes);
+                  memset(out, 0, sizeof (float) * nframes); 
+             }
+             memset(jack_outbuf,0,sizeof(jack_outbuf));
+             jack_filled = 0;
+        }
+        pthread_cond_broadcast(&jack_sem);
+        return 0;
+}
+
+static int
+jack_srate (jack_nframes_t srate, void *arg)
+{
+        sys_dacsr = srate;
+        return 0;
+}
+
+static void
+jack_shutdown (void *arg)
+{
+  verbose(1, "JACK-server shut down");
+  sys_close_audio();
+  jack_client = NULL;
+}
+
+static int jack_xrun(void* arg) {
+  verbose(1, "JACK-server xrun");
+  jack_dio_error = 1;
+  return 0;
+}
+
+
+static char** jack_get_clients(void)
+{
+    const char **jack_ports;
+    int i,j;
+    int num_clients = 0;
+    regex_t port_regex;
+    jack_ports = jack_get_ports( jack_client, "", "", 0 );
+    regcomp( &port_regex, "^[^:]*", REG_EXTENDED );
+
+    jack_client_names[0] = NULL;
+
+    /* Build a list of clients from the list of ports */
+    for( i = 0; jack_ports[i] != NULL; i++ )
+    {
+        int client_seen;
+        regmatch_t match_info;
+        char tmp_client_name[100];
+
+        /* extract the client name from the port name, using a regex
+         * that parses the clientname:portname syntax */
+        regexec( &port_regex, jack_ports[i], 1, &match_info, 0 );
+        memcpy( tmp_client_name, &jack_ports[i][match_info.rm_so],
+                match_info.rm_eo - match_info.rm_so );
+        tmp_client_name[ match_info.rm_eo - match_info.rm_so ] = '\0';
+
+        /* do we know about this port's client yet? */
+        client_seen = 0;
+
+        for( j = 0; j < num_clients; j++ )
+            if( strcmp( tmp_client_name, jack_client_names[j] ) == 0 )
+                client_seen = 1;
+
+        if( client_seen == 0 )
+        {
+            jack_client_names[num_clients] = (char*)getbytes(strlen(tmp_client_name) + 1);
+
+            /* The alsa_pcm client should go in spot 0.  If this
+             * is the alsa_pcm client AND we are NOT about to put
+             * it in spot 0 put it in spot 0 and move whatever
+             * was already in spot 0 to the end. */
+
+            if( strcmp( "system", tmp_client_name ) == 0 && num_clients > 0 )
+            {
+              char* tmp;
+                /* alsa_pcm goes in spot 0 */
+              tmp = jack_client_names[ num_clients ];
+              jack_client_names[ num_clients ] = jack_client_names[0];
+              jack_client_names[0] = tmp;
+              strcpy( jack_client_names[0], tmp_client_name);
+            }
+            else
+            {
+                /* put the new client at the end of the client list */
+                strcpy( jack_client_names[ num_clients ], tmp_client_name );
+            }
+            num_clients++;
+
+        }
+    }
+
+    /*    for (i=0;i<num_clients;i++) post("client: %s",jack_client_names[i]); */
+
+    free( jack_ports );
+    return jack_client_names;
+}
+
+/*   
+ *   Wire up all the ports of one client.
+ *
+ */
+
+static int jack_connect_ports(char* client)
+{
+  char  regex_pattern[100]; /* its always the same, ... */
+  int i;
+  const char **jack_ports;
+    
+  if (strlen(client) > 96)  return -1;
+
+  sprintf( regex_pattern, "%s:.*", client );
+
+  jack_ports = jack_get_ports( jack_client, regex_pattern,
+                               NULL, JackPortIsOutput);
+  if (jack_ports) 
+    for (i=0;jack_ports[i] != NULL && i < sys_inchannels;i++)      
+      if (jack_connect (jack_client, jack_ports[i], jack_port_name (input_port[i]))) 
+        error("JACK: cannot connect input ports %s -> %s", jack_ports[i],jack_port_name (input_port[i]));
+      
+  
+  
+  jack_ports = jack_get_ports( jack_client, regex_pattern,
+                               NULL, JackPortIsInput);
+  if (jack_ports) 
+    for (i=0;jack_ports[i] != NULL && i < sys_outchannels;i++)      
+      if (jack_connect (jack_client, jack_port_name (output_port[i]), jack_ports[i])) 
+        error("JACK: cannot connect output ports %s -> %s", jack_port_name (output_port[i]),jack_ports[i]);
+  
+  
+  
+  free(jack_ports);
+  return 0;
+}
+
+
+void jack_error(const char *desc) {
+  error("JACK error: %s", desc);
+  return;
+}
+
+
+int
+jack_open_audio(int inchans, int outchans, int rate)
+
+{
+        int j;
+        char port_name[80] = "";
+        int client_iterator = 0;
+        int new_jack = 0;
+        int srate;
+        jack_status_t status;
+
+        jack_dio_error = 0;
+        
+        if ((inchans == 0) && (outchans == 0)) return 0;
+
+        if (outchans > NUM_JACK_PORTS) {
+                error("JACK: %d output ports not supported, setting to %d",outchans, NUM_JACK_PORTS);
+                outchans = NUM_JACK_PORTS;
+        }
+
+        if (inchans > NUM_JACK_PORTS) {
+                error("JACK: %d input ports not supported, setting to %d",inchans, NUM_JACK_PORTS);
+                inchans = NUM_JACK_PORTS;
+        }
+
+        /* try to become a client of the JACK server */
+        /* if no JACK server exists, start a default one (jack_client_open() does that for us... */
+        if (!jack_client) {
+          do {
+            sprintf(port_name,"pure_data_%d",client_iterator);
+            client_iterator++;
+            /* do not try to start the jack-server...seems to make problems... */
+            jack_client = jack_client_open (port_name, JackNoStartServer, &status, NULL);
+            if (status & JackServerFailed) {
+              error("JACK: unable to connect to JACK server");
+              jack_client=NULL;
+              break;
+            }
+          } while (status & JackNameNotUnique);
+
+          if(status) {
+            if (status & JackServerStarted) {
+              post("JACK: started JACK server?");
+            } else {
+              post("JACK: jack returned status %d", status);
+            }
+          }
+          
+          if (!jack_client) { // jack spits out enough messages already, do not warn
+            sys_inchannels = sys_outchannels = 0;
+            return 1;
+          }
+          
+          jack_get_clients();
+
+          /* tell the JACK server to call `process()' whenever
+             there is work to be done.
+          */
+          
+          jack_set_process_callback (jack_client, process, 0);
+          
+          //          jack_set_error_function (jack_error);
+          
+#ifdef JACK_XRUN
+          jack_set_xrun_callback (jack_client, jack_xrun, NULL);
+#endif
+          
+          /* tell the JACK server to call `srate()' whenever
+             the sample rate of the system changes.
+          */
+          
+          jack_set_sample_rate_callback (jack_client, jack_srate, 0);
+          
+          
+          /* tell the JACK server to call `jack_shutdown()' if
+             it ever shuts down, either entirely, or if it
+             just decides to stop calling us.
+          */
+          
+          jack_on_shutdown (jack_client, jack_shutdown, 0);
+          
+          for (j=0;j<NUM_JACK_PORTS;j++) {
+               input_port[j]=NULL;
+               output_port[j] = NULL;
+          }
+          
+          new_jack = 1;
+        }
+
+        /* display the current sample rate. once the client is activated
+           (see below), you should rely on your own sample rate
+           callback (see above) for this value.
+        */
+        
+        srate = jack_get_sample_rate (jack_client);
+        sys_dacsr = srate;
+                
+        /* create the ports */
+        
+        for (j = 0; j < inchans; j++) {
+                sprintf(port_name, "input%d", j);
+                if (!input_port[j]) input_port[j] = jack_port_register (jack_client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
+                if (!input_port[j]) {
+                  error("JACK: can only register %d input ports (instead of requested %d)", j, inchans);
+                  sys_inchannels = inchans = j;
+                  break;
+                }
+        }
+
+        for (j = 0; j < outchans; j++) {
+                sprintf(port_name, "output%d", j);
+                if (!output_port[j]) output_port[j] = jack_port_register (jack_client, port_name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0);
+                if (!output_port[j]) {
+                  error("JACK: can only register %d output ports (instead of requested %d)", j, outchans);
+                  sys_outchannels = outchans = j;
+                  break;
+                }
+        } 
+        outport_count = outchans;
+
+        /* tell the JACK server that we are ready to roll */
+ 
+        if (new_jack) {
+          if (jack_activate (jack_client)) {
+            error("JACK: cannot activate client");
+            sys_inchannels = sys_outchannels = 0;
+            return 1;
+          }
+          
+          memset(jack_outbuf,0,sizeof(jack_outbuf));
+          
+          if (jack_client_names[0])
+            jack_connect_ports(jack_client_names[0]);
+
+          pthread_mutex_init(&jack_mutex,NULL);
+          pthread_cond_init(&jack_sem,NULL);
+        }
+        return 0;
+}
+
+void jack_close_audio(void) 
+
+{
+        jack_started = 0;
+}
+
+int jack_send_dacs(void)
+
+{
+        t_sample * fp;
+        int j;
+        int rtnval =  SENDDACS_YES;
+        int timenow;
+        int timeref = sys_getrealtime();
+                
+        if (!jack_client) return SENDDACS_NO;
+
+        if (!sys_inchannels && !sys_outchannels) return (SENDDACS_NO); 
+
+        if (jack_dio_error) {
+                sys_log_error(ERR_RESYNC);
+                jack_dio_error = 0;
+        }
+        if (jack_filled >= jack_out_max)
+          pthread_cond_wait(&jack_sem,&jack_mutex);
+          
+        jack_started = 1;
+
+        fp = sys_soundout;
+        for (j = 0; j < sys_outchannels; j++) {
+                memcpy(jack_outbuf + (j * BUF_JACK) + jack_filled,fp, DEFDACBLKSIZE*sizeof(t_sample));
+                fp += DEFDACBLKSIZE;  
+        }
+        fp = sys_soundin;
+        for (j = 0; j < sys_inchannels; j++) {
+                memcpy(fp, jack_inbuf + (j * BUF_JACK) + jack_filled, DEFDACBLKSIZE*sizeof(t_sample));
+                fp += DEFDACBLKSIZE;
+        }
+
+        if ((timenow = sys_getrealtime()) - timeref > 0.002)
+          {
+            rtnval = SENDDACS_SLEPT;
+          }
+
+        memset(sys_soundout,0,DEFDACBLKSIZE*sizeof(t_sample)*sys_outchannels);
+        jack_filled += DEFDACBLKSIZE;
+        return rtnval;
+}
+
+void jack_getdevs(char *indevlist, int *nindevs,
+    char *outdevlist, int *noutdevs, int *canmulti, 
+        int maxndev, int devdescsize)
+{
+    int i, ndev;
+    *canmulti = 0;  /* supports multiple devices */
+    ndev = 1;
+    for (i = 0; i < ndev; i++)
+    {
+        sprintf(indevlist + i * devdescsize, "JACK");
+        sprintf(outdevlist + i * devdescsize, "JACK");
+    }
+    *nindevs = *noutdevs = ndev;
+}
+
+void jack_listdevs( void)
+{
+    error("device listing not implemented for jack yet");
+}
+
+#endif /* JACK */
diff --git a/src/s_audio_old.c b/src/s_audio_old.c
new file mode 100644
index 000000000..67555ac25
--- /dev/null
+++ b/src/s_audio_old.c
@@ -0,0 +1,912 @@
+/* Copyright (c) 2003, Miller Puckette and others.
+* For information on usage and redistribution, and for a DISCLAIMER OF ALL
+* WARRANTIES, see the file, "LICENSE.txt," in this distribution.  */
+
+/*  machine-independent (well, mostly!) audio layer.  Stores and recalls
+    audio settings from argparse routine and from dialog window. 
+*/
+
+#include "config.h"
+
+#include "m_pd.h"
+#include "s_stuff.h"
+#include <stdio.h>
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+/* XXX Hack!!! These should be checked for independently of unistd.h ... */
+#include <sys/time.h>
+#include <sys/resource.h>
+#endif
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#define SYS_DEFAULTCH 2
+#define SYS_MAXCH 100
+typedef long t_pa_sample;
+#define SYS_SAMPLEWIDTH sizeof(t_pa_sample)
+#define SYS_BYTESPERCHAN (DEFDACBLKSIZE * SYS_SAMPLEWIDTH) 
+#define SYS_XFERSAMPS (SYS_DEFAULTCH*DEFDACBLKSIZE)
+#define SYS_XFERSIZE (SYS_SAMPLEWIDTH * SYS_XFERSAMPS)
+#define MAXNDEV 20
+#define DEVDESCSIZE 80
+
+static void audio_getdevs(char *indevlist, int *nindevs,
+    char *outdevlist, int *noutdevs, int *canmulti, int *cancallback, 
+        int maxndev, int devdescsize);
+
+    /* these are set in this file when opening audio, but then may be reduced,
+    even to zero, in the system dependent open_audio routines. */
+int sys_inchannels;
+int sys_outchannels;
+int sys_advance_samples;        /* scheduler advance in samples */
+int sys_blocksize = 0;          /* audio I/O block size in sample frames */
+int sys_audioapi = API_DEFAULT;
+int sys_audioapiopened = -1;    /* save last API opened for later closing */
+static int sys_meters;          /* true if we're metering */
+static t_sample sys_inmax;         /* max input amplitude */
+static t_sample sys_outmax;        /* max output amplitude */
+
+    /* exported variables */
+int sys_schedadvance;   /* scheduler advance in microseconds */
+t_float sys_dacsr;
+
+t_sample *sys_soundout;
+t_sample *sys_soundin;
+
+    /* the "state" is normally one if we're open and zero otherwise; 
+    but if the state is one, we still haven't necessarily opened the
+    audio hardware; see audio_isopen() below. */
+static int audio_state;
+
+    /* last requested parameters */
+static int audio_naudioindev = -1;
+static int audio_audioindev[MAXAUDIOINDEV];
+static int audio_audiochindev[MAXAUDIOINDEV];
+static int audio_naudiooutdev = -1;
+static int audio_audiooutdev[MAXAUDIOOUTDEV];
+static int audio_audiochoutdev[MAXAUDIOOUTDEV];
+static int audio_rate;
+static int audio_advance;
+static int audio_callback;
+
+static int audio_callback_is_open;  /* reflects true actual state */
+static int audio_nextinchans, audio_nextoutchans;
+void sched_audio_callbackfn(void);
+void sched_reopenmeplease(void);
+
+static int audio_isopen(void)
+{
+    return (audio_state &&
+        ((audio_naudioindev > 0 && audio_audiochindev[0] > 0) 
+            || (audio_naudiooutdev > 0 && audio_audiochoutdev[0] > 0)));
+}
+
+void sys_get_audio_params(
+    int *pnaudioindev, int *paudioindev, int *chindev,
+    int *pnaudiooutdev, int *paudiooutdev, int *choutdev,
+    int *prate, int *padvance, int *pcallback)
+{
+    int i;
+    *pnaudioindev = audio_naudioindev;
+    for (i = 0; i < MAXAUDIOINDEV; i++)
+        paudioindev[i] = audio_audioindev[i],
+            chindev[i] = audio_audiochindev[i]; 
+    *pnaudiooutdev = audio_naudiooutdev;
+    for (i = 0; i < MAXAUDIOOUTDEV; i++)
+        paudiooutdev[i] = audio_audiooutdev[i],
+            choutdev[i] = audio_audiochoutdev[i]; 
+    *prate = audio_rate;
+    *padvance = audio_advance;
+    *pcallback = audio_callback;
+}
+
+void sys_save_audio_params(
+    int naudioindev, int *audioindev, int *chindev,
+    int naudiooutdev, int *audiooutdev, int *choutdev,
+    int rate, int advance, int callback)
+{
+    int i;
+    audio_naudioindev = naudioindev;
+    for (i = 0; i < MAXAUDIOINDEV; i++)
+        audio_audioindev[i] = audioindev[i],
+            audio_audiochindev[i] = chindev[i]; 
+    audio_naudiooutdev = naudiooutdev;
+    for (i = 0; i < MAXAUDIOOUTDEV; i++)
+        audio_audiooutdev[i] = audiooutdev[i],
+            audio_audiochoutdev[i] = choutdev[i]; 
+    audio_rate = rate;
+    audio_advance = advance;
+    audio_callback = callback;
+}
+
+    /* init routines for any API which needs to set stuff up before
+    any other API gets used.  This is only true of OSS so far. */
+#ifdef USEAPI_OSS
+void oss_init(void);
+#endif
+
+static void audio_init( void)
+{
+    static int initted = 0;
+    if (initted)
+        return;
+    initted = 1;
+#ifdef USEAPI_OSS
+    oss_init();
+#endif
+} 
+
+    /* set channels and sample rate.  */
+
+void sys_setchsr(int chin, int chout, int sr)
+{
+    int nblk;
+    int inbytes = (chin ? chin : 2) *
+                (DEFDACBLKSIZE*sizeof(t_sample));
+    int outbytes = (chout ? chout : 2) *
+                (DEFDACBLKSIZE*sizeof(t_sample));
+
+    if (sys_soundin)
+        freebytes(sys_soundin, 
+            (sys_inchannels? sys_inchannels : 2) *
+                (DEFDACBLKSIZE*sizeof(t_sample)));
+    if (sys_soundout)
+        freebytes(sys_soundout, 
+            (sys_outchannels? sys_outchannels : 2) *
+                (DEFDACBLKSIZE*sizeof(t_sample)));
+    sys_inchannels = chin;
+    sys_outchannels = chout;
+    sys_dacsr = sr;
+    sys_advance_samples = (sys_schedadvance * sys_dacsr) / (1000000.);
+    if (sys_advance_samples < 3 * DEFDACBLKSIZE)
+        sys_advance_samples = 3 * DEFDACBLKSIZE;
+
+    sys_soundin = (t_sample *)getbytes(inbytes);
+    memset(sys_soundin, 0, inbytes);
+
+    sys_soundout = (t_sample *)getbytes(outbytes);
+    memset(sys_soundout, 0, outbytes);
+
+    if (sys_verbose)
+        post("input channels = %d, output channels = %d",
+            sys_inchannels, sys_outchannels);
+    canvas_resume_dsp(canvas_suspend_dsp());
+}
+
+/* ----------------------- public routines ----------------------- */
+
+    /* set audio device settings (after cleaning up the specified device and
+    channel vectors).  The audio devices are "zero based" (i.e. "0" means the
+    first one.)  We can later re-open audio and/or show the settings on a
+    dialog window. */
+
+void sys_set_audio_settings(int naudioindev, int *audioindev, int nchindev,
+    int *chindev, int naudiooutdev, int *audiooutdev, int nchoutdev,
+    int *choutdev, int rate, int advance, int callback)
+{
+    int i, *ip;
+    int defaultchannels = SYS_DEFAULTCH;
+    int inchans, outchans, nrealindev, nrealoutdev;
+    int realindev[MAXAUDIOINDEV], realoutdev[MAXAUDIOOUTDEV];
+    int realinchans[MAXAUDIOINDEV], realoutchans[MAXAUDIOOUTDEV];
+
+    char indevlist[MAXNDEV*DEVDESCSIZE], outdevlist[MAXNDEV*DEVDESCSIZE];
+    int indevs = 0, outdevs = 0, canmulti = 0, cancallback = 0;
+    audio_getdevs(indevlist, &indevs, outdevlist, &outdevs, &canmulti,
+        &cancallback, MAXNDEV, DEVDESCSIZE);
+
+    if (rate < 1)
+        rate = DEFAULTSRATE;
+    if (advance <= 0)
+        advance = DEFAULTADVANCE;
+     audio_init();
+        /* Since the channel vector might be longer than the
+        audio device vector, or vice versa, we fill the shorter one
+        in to match the longer one.  Also, if both are empty, we fill in
+        one device (the default) and two channels. */ 
+    if (naudioindev == -1)
+    {           /* no input audio devices specified */
+        if (nchindev == -1)
+        {
+            if (indevs >= 1)
+            {
+                nchindev=1;
+                chindev[0] = defaultchannels;
+                naudioindev = 1;
+                audioindev[0] = DEFAULTAUDIODEV;
+            }
+            else naudioindev = nchindev = 0;
+        }
+        else
+        {
+            for (i = 0; i < MAXAUDIOINDEV; i++)
+                audioindev[i] = i;
+            naudioindev = nchindev;
+        }
+    }
+    else
+    {
+        if (nchindev == -1)
+        {
+            nchindev = naudioindev;
+            for (i = 0; i < naudioindev; i++)
+                chindev[i] = defaultchannels;
+        }
+        else if (nchindev > naudioindev)
+        {
+            for (i = naudioindev; i < nchindev; i++)
+            {
+                if (i == 0)
+                    audioindev[0] = DEFAULTAUDIODEV;
+                else audioindev[i] = audioindev[i-1] + 1;
+            }
+            naudioindev = nchindev;
+        }
+        else if (nchindev < naudioindev)
+        {
+            for (i = nchindev; i < naudioindev; i++)
+            {
+                if (i == 0)
+                    chindev[0] = defaultchannels;
+                else chindev[i] = chindev[i-1];
+            }
+            naudioindev = nchindev;
+        }
+    }
+
+    if (naudiooutdev == -1)
+    {           /* not set */
+        if (nchoutdev == -1)
+        {
+            if (outdevs >= 1)
+            {
+                nchoutdev=1;
+                choutdev[0]=defaultchannels;
+                naudiooutdev=1;
+                audiooutdev[0] = DEFAULTAUDIODEV;
+            }
+            else nchoutdev = naudiooutdev = 0;
+        }
+        else
+        {
+            for (i = 0; i < MAXAUDIOOUTDEV; i++)
+                audiooutdev[i] = i;
+            naudiooutdev = nchoutdev;
+        }
+    }
+    else
+    {
+        if (nchoutdev == -1)
+        {
+            nchoutdev = naudiooutdev;
+            for (i = 0; i < naudiooutdev; i++)
+                choutdev[i] = defaultchannels;
+        }
+        else if (nchoutdev > naudiooutdev)
+        {
+            for (i = naudiooutdev; i < nchoutdev; i++)
+            {
+                if (i == 0)
+                    audiooutdev[0] = DEFAULTAUDIODEV;
+                else audiooutdev[i] = audiooutdev[i-1] + 1;
+            }
+            naudiooutdev = nchoutdev;
+        }
+        else if (nchoutdev < naudiooutdev)
+        {
+            for (i = nchoutdev; i < naudiooutdev; i++)
+            {
+                if (i == 0)
+                    choutdev[0] = defaultchannels;
+                else choutdev[i] = choutdev[i-1];
+            }
+            naudiooutdev = nchoutdev;
+        }
+    }
+    
+        /* count total number of input and output channels */
+    for (i = nrealindev = inchans = 0; i < naudioindev; i++)
+        if (chindev[i] > 0)
+    {
+        realinchans[nrealindev] = chindev[i];
+        realindev[nrealindev] = audioindev[i];
+        inchans += chindev[i];
+        nrealindev++;
+    }
+    for (i = nrealoutdev = outchans = 0; i < naudiooutdev; i++)
+        if (choutdev[i] > 0)
+    {
+        realoutchans[nrealoutdev] = choutdev[i];
+        realoutdev[nrealoutdev] = audiooutdev[i];
+        outchans += choutdev[i];
+        nrealoutdev++;
+    }
+    sys_schedadvance = advance * 1000;
+    sys_log_error(ERR_NOTHING);
+    audio_nextinchans = inchans;
+    audio_nextoutchans = outchans;
+    sys_save_audio_params(nrealindev, realindev, realinchans,
+        nrealoutdev, realoutdev, realoutchans, rate, advance, callback);
+}
+
+void sys_close_audio(void)
+{
+    if (sys_externalschedlib)
+    {
+        return;
+    }
+    if (!audio_isopen())
+        return;
+#ifdef USEAPI_PORTAUDIO
+    if (sys_audioapiopened == API_PORTAUDIO)
+        pa_close_audio();
+    else 
+#endif
+#ifdef USEAPI_JACK
+    if (sys_audioapiopened == API_JACK)
+        jack_close_audio();
+    else
+#endif
+#ifdef USEAPI_OSS
+    if (sys_audioapiopened == API_OSS)
+        oss_close_audio();
+    else
+#endif
+#ifdef USEAPI_ALSA
+    if (sys_audioapiopened == API_ALSA)
+        alsa_close_audio();
+    else
+#endif
+#ifdef USEAPI_MMIO
+    if (sys_audioapiopened == API_MMIO)
+        mmio_close_audio();
+    else
+#endif
+        post("sys_close_audio: unknown API %d", sys_audioapiopened);
+    sys_inchannels = sys_outchannels = 0;
+    sys_audioapiopened = -1;
+    sched_set_using_audio(SCHED_AUDIO_NONE);
+    audio_state = 0;
+    audio_callback_is_open = 0;
+}
+
+    /* open audio using whatever parameters were last used */
+void sys_reopen_audio( void)
+{
+    int naudioindev, audioindev[MAXAUDIOINDEV], chindev[MAXAUDIOINDEV];
+    int naudiooutdev, audiooutdev[MAXAUDIOOUTDEV], choutdev[MAXAUDIOOUTDEV];
+    int rate, advance, callback, outcome = 0;
+    sys_get_audio_params(&naudioindev, audioindev, chindev,
+        &naudiooutdev, audiooutdev, choutdev, &rate, &advance, &callback);
+    sys_setchsr(audio_nextinchans, audio_nextoutchans, rate);
+    if (!naudioindev && !naudiooutdev)
+    {
+        sched_set_using_audio(SCHED_AUDIO_NONE);
+        return;
+    }
+#ifdef USEAPI_PORTAUDIO
+    if (sys_audioapi == API_PORTAUDIO)
+    {
+        int blksize = (sys_blocksize ? sys_blocksize : 64);
+        outcome = pa_open_audio((naudioindev > 0 ? chindev[0] : 0),
+        (naudiooutdev > 0 ? choutdev[0] : 0), rate, sys_soundin,
+            sys_soundout, blksize, sys_advance_samples/blksize, 
+             (naudioindev > 0 ? audioindev[0] : 0),
+              (naudiooutdev > 0 ? audiooutdev[0] : 0),
+               (callback ? sched_audio_callbackfn : 0));
+    }
+    else
+#endif
+#ifdef USEAPI_JACK
+    if (sys_audioapi == API_JACK) 
+        outcome = jack_open_audio((naudioindev > 0 ? chindev[0] : 0),
+            (naudioindev > 0 ? choutdev[0] : 0), rate);
+
+    else
+#endif    
+#ifdef USEAPI_OSS
+    if (sys_audioapi == API_OSS)
+        outcome = oss_open_audio(naudioindev, audioindev, naudioindev,
+            chindev, naudiooutdev, audiooutdev, naudiooutdev, choutdev, rate);
+    else
+#endif
+#ifdef USEAPI_ALSA
+        /* for alsa, only one device is supported; it may
+        be open for both input and output. */
+    if (sys_audioapi == API_ALSA)
+        outcome = alsa_open_audio(naudioindev, audioindev, naudioindev,
+            chindev, naudiooutdev, audiooutdev, naudiooutdev, choutdev, rate);
+    else 
+#endif
+#ifdef USEAPI_MMIO
+    if (sys_audioapi == API_MMIO)
+        outcome = mmio_open_audio(naudioindev, audioindev, naudioindev,
+            chindev, naudiooutdev, audiooutdev, naudiooutdev, choutdev, rate);
+    else
+#endif
+    if (sys_audioapi == API_NONE)
+        ;
+    else post("unknown audio API specified");
+    if (outcome)    /* failed */
+    {
+        audio_state = 0;
+        sched_set_using_audio(SCHED_AUDIO_NONE);
+        sys_audioapiopened = -1;
+        audio_callback_is_open = 0;
+    }
+    else
+    {
+                /* fprintf(stderr, "started w/callback %d\n", callback); */
+        audio_state = 1;
+        sched_set_using_audio(
+            (callback ? SCHED_AUDIO_CALLBACK : SCHED_AUDIO_POLL));
+        sys_audioapiopened = sys_audioapi;
+        audio_callback_is_open = callback;
+    }
+    sys_vgui("set pd_whichapi %d\n",  (outcome == 0 ? sys_audioapi : 0));
+}
+
+int sys_send_dacs(void)
+{
+    if (sys_meters)
+    {
+        int i, n;
+        t_sample maxsamp;
+        for (i = 0, n = sys_inchannels * DEFDACBLKSIZE, maxsamp = sys_inmax;
+            i < n; i++)
+        {
+            t_sample f = sys_soundin[i];
+            if (f > maxsamp) maxsamp = f;
+            else if (-f > maxsamp) maxsamp = -f;
+        }
+        sys_inmax = maxsamp;
+        for (i = 0, n = sys_outchannels * DEFDACBLKSIZE, maxsamp = sys_outmax;
+            i < n; i++)
+        {
+            t_sample f = sys_soundout[i];
+            if (f > maxsamp) maxsamp = f;
+            else if (-f > maxsamp) maxsamp = -f;
+        }
+        sys_outmax = maxsamp;
+    }
+
+#ifdef USEAPI_PORTAUDIO
+    if (sys_audioapi == API_PORTAUDIO)
+        return (pa_send_dacs());
+    else 
+#endif
+#ifdef USEAPI_JACK
+      if (sys_audioapi == API_JACK) 
+        return (jack_send_dacs());
+    else
+#endif
+#ifdef USEAPI_OSS
+    if (sys_audioapi == API_OSS)
+        return (oss_send_dacs());
+    else
+#endif
+#ifdef USEAPI_ALSA
+    if (sys_audioapi == API_ALSA)
+        return (alsa_send_dacs());
+    else
+#endif
+#ifdef USEAPI_MMIO
+    if (sys_audioapi == API_MMIO)
+        return (mmio_send_dacs());
+    else
+#endif
+    post("unknown API");    
+    return (0);
+}
+
+t_float sys_getsr(void)
+{
+     return (sys_dacsr);
+}
+
+int sys_get_outchannels(void)
+{
+     return (sys_outchannels); 
+}
+
+int sys_get_inchannels(void) 
+{
+     return (sys_inchannels);
+}
+
+void sys_getmeters(t_sample *inmax, t_sample *outmax)
+{
+    if (inmax)
+    {
+        sys_meters = 1;
+        *inmax = sys_inmax;
+        *outmax = sys_outmax;
+    }
+    else
+        sys_meters = 0;
+    sys_inmax = sys_outmax = 0;
+}
+
+void sys_reportidle(void)
+{
+}
+
+static void audio_getdevs(char *indevlist, int *nindevs,
+    char *outdevlist, int *noutdevs, int *canmulti, int *cancallback,
+        int maxndev, int devdescsize)
+{
+    audio_init();
+    *cancallback = 0;   /* may be overridden by specific API implementation */
+#ifdef USEAPI_PORTAUDIO
+    if (sys_audioapi == API_PORTAUDIO)
+    {
+        pa_getdevs(indevlist, nindevs, outdevlist, noutdevs, canmulti,
+            maxndev, devdescsize);
+        *cancallback = 1;
+    }
+    else
+#endif
+#ifdef USEAPI_JACK
+    if (sys_audioapi == API_JACK)
+    {
+        jack_getdevs(indevlist, nindevs, outdevlist, noutdevs, canmulti,
+            maxndev, devdescsize);
+    }
+    else
+#endif
+#ifdef USEAPI_OSS
+    if (sys_audioapi == API_OSS)
+    {
+        oss_getdevs(indevlist, nindevs, outdevlist, noutdevs, canmulti,
+            maxndev, devdescsize);
+    }
+    else
+#endif
+#ifdef USEAPI_ALSA
+    if (sys_audioapi == API_ALSA)
+    {
+        alsa_getdevs(indevlist, nindevs, outdevlist, noutdevs, canmulti,
+            maxndev, devdescsize);
+    }
+    else
+#endif
+#ifdef USEAPI_MMIO
+    if (sys_audioapi == API_MMIO)
+    {
+        mmio_getdevs(indevlist, nindevs, outdevlist, noutdevs, canmulti,
+            maxndev, devdescsize);
+    }
+    else
+#endif
+    {
+            /* this shouldn't happen once all the above get filled in. */
+        int i;
+        *nindevs = *noutdevs = 3;
+        for (i = 0; i < 3; i++)
+        {
+            sprintf(indevlist + i * devdescsize, "input device #%d", i+1);
+            sprintf(outdevlist + i * devdescsize, "output device #%d", i+1);
+        }
+        *canmulti = 0;
+    }
+}
+
+
+static void sys_listaudiodevs(void )
+{
+    char indevlist[MAXNDEV*DEVDESCSIZE], outdevlist[MAXNDEV*DEVDESCSIZE];
+    int nindevs = 0, noutdevs = 0, i, canmulti = 0, cancallback = 0;
+
+    audio_getdevs(indevlist, &nindevs, outdevlist, &noutdevs, &canmulti,
+        &cancallback, MAXNDEV, DEVDESCSIZE);
+
+    if (!nindevs)
+        post("no audio input devices found");
+    else
+    {
+            /* To agree with command line flags, normally start at 1 */
+            /* But microsoft "MMIO" device list starts at 0 (the "mapper"). */
+            /* (see also sys_mmio variable in s_main.c)  */
+
+        post("audio input devices:");
+        for (i = 0; i < nindevs; i++)
+            post("%d. %s", i + (sys_audioapi != API_MMIO),
+                indevlist + i * DEVDESCSIZE);
+    }
+    if (!noutdevs)
+        post("no audio output devices found");
+    else
+    {
+        post("audio output devices:");
+        for (i = 0; i < noutdevs; i++)
+            post("%d. %s", i + (sys_audioapi != API_MMIO),
+                outdevlist + i * DEVDESCSIZE);
+    }
+    post("API number %d\n", sys_audioapi);
+}
+
+
+    /* start an audio settings dialog window */
+void glob_audio_properties(t_pd *dummy, t_floatarg flongform)
+{
+    char buf[1024 + 2 * MAXNDEV*(DEVDESCSIZE+4)];
+        /* these are the devices you're using: */
+    int naudioindev, audioindev[MAXAUDIOINDEV], chindev[MAXAUDIOINDEV];
+    int naudiooutdev, audiooutdev[MAXAUDIOOUTDEV], choutdev[MAXAUDIOOUTDEV];
+    int audioindev1, audioindev2, audioindev3, audioindev4,
+        audioinchan1, audioinchan2, audioinchan3, audioinchan4,
+        audiooutdev1, audiooutdev2, audiooutdev3, audiooutdev4,
+        audiooutchan1, audiooutchan2, audiooutchan3, audiooutchan4;
+    int rate, advance, callback;
+        /* these are all the devices on your system: */
+    char indevlist[MAXNDEV*DEVDESCSIZE], outdevlist[MAXNDEV*DEVDESCSIZE];
+    int nindevs = 0, noutdevs = 0, canmulti = 0, cancallback = 0, i;
+
+    audio_getdevs(indevlist, &nindevs, outdevlist, &noutdevs, &canmulti,
+         &cancallback, MAXNDEV, DEVDESCSIZE);
+
+    sys_gui("global audio_indevlist; set audio_indevlist {}\n");
+    for (i = 0; i < nindevs; i++)
+        sys_vgui("lappend audio_indevlist {%s}\n",
+            indevlist + i * DEVDESCSIZE);
+
+    sys_gui("global audio_outdevlist; set audio_outdevlist {}\n");
+    for (i = 0; i < noutdevs; i++)
+        sys_vgui("lappend audio_outdevlist {%s}\n",
+            outdevlist + i * DEVDESCSIZE);
+
+    sys_get_audio_params(&naudioindev, audioindev, chindev,
+        &naudiooutdev, audiooutdev, choutdev, &rate, &advance, &callback);
+
+    /* post("naudioindev %d naudiooutdev %d longform %f",
+            naudioindev, naudiooutdev, flongform); */
+    if (naudioindev > 1 || naudiooutdev > 1)
+        flongform = 1;
+
+    audioindev1 = (naudioindev > 0 &&  audioindev[0]>= 0 ? audioindev[0] : 0);
+    audioindev2 = (naudioindev > 1 &&  audioindev[1]>= 0 ? audioindev[1] : 0);
+    audioindev3 = (naudioindev > 2 &&  audioindev[2]>= 0 ? audioindev[2] : 0);
+    audioindev4 = (naudioindev > 3 &&  audioindev[3]>= 0 ? audioindev[3] : 0);
+    audioinchan1 = (naudioindev > 0 ? chindev[0] : 0);
+    audioinchan2 = (naudioindev > 1 ? chindev[1] : 0);
+    audioinchan3 = (naudioindev > 2 ? chindev[2] : 0);
+    audioinchan4 = (naudioindev > 3 ? chindev[3] : 0);
+    audiooutdev1 = (naudiooutdev > 0 && audiooutdev[0]>=0 ? audiooutdev[0] : 0);  
+    audiooutdev2 = (naudiooutdev > 1 && audiooutdev[1]>=0 ? audiooutdev[1] : 0);  
+    audiooutdev3 = (naudiooutdev > 2 && audiooutdev[2]>=0 ? audiooutdev[2] : 0);  
+    audiooutdev4 = (naudiooutdev > 3 && audiooutdev[3]>=0 ? audiooutdev[3] : 0);  
+    audiooutchan1 = (naudiooutdev > 0 ? choutdev[0] : 0);
+    audiooutchan2 = (naudiooutdev > 1 ? choutdev[1] : 0);
+    audiooutchan3 = (naudiooutdev > 2 ? choutdev[2] : 0);
+    audiooutchan4 = (naudiooutdev > 3 ? choutdev[3] : 0);
+    sprintf(buf,
+"pdtk_audio_dialog %%s \
+%d %d %d %d %d %d %d %d \
+%d %d %d %d %d %d %d %d \
+%d %d %d %d %d\n",
+        audioindev1, audioindev2, audioindev3, audioindev4, 
+        audioinchan1, audioinchan2, audioinchan3, audioinchan4, 
+        audiooutdev1, audiooutdev2, audiooutdev3, audiooutdev4,
+        audiooutchan1, audiooutchan2, audiooutchan3, audiooutchan4, 
+        rate, advance, canmulti, (cancallback ? callback : -1),
+        (flongform != 0));
+    gfxstub_deleteforkey(0);
+    gfxstub_new(&glob_pdobject, (void *)glob_audio_properties, buf);
+}
+
+extern int pa_foo;
+    /* new values from dialog window */
+void glob_audio_dialog(t_pd *dummy, t_symbol *s, int argc, t_atom *argv)
+{
+    int naudioindev, audioindev[MAXAUDIOINDEV], chindev[MAXAUDIOINDEV];
+    int naudiooutdev, audiooutdev[MAXAUDIOOUTDEV], choutdev[MAXAUDIOOUTDEV];
+    int rate, advance, audioon, i, nindev, noutdev;
+    int audioindev1, audioinchan1, audiooutdev1, audiooutchan1;
+    int newaudioindev[4], newaudioinchan[4],
+        newaudiooutdev[4], newaudiooutchan[4];
+        /* the new values the dialog came back with: */
+    int newrate = atom_getintarg(16, argc, argv);
+    int newadvance = atom_getintarg(17, argc, argv);
+    int newcallback = atom_getintarg(18, argc, argv);
+
+    for (i = 0; i < 4; i++)
+    {
+        newaudioindev[i] = atom_getintarg(i, argc, argv);
+        newaudioinchan[i] = atom_getintarg(i+4, argc, argv);
+        newaudiooutdev[i] = atom_getintarg(i+8, argc, argv);
+        newaudiooutchan[i] = atom_getintarg(i+12, argc, argv);
+    }
+
+    for (i = 0, nindev = 0; i < 4; i++)
+    {
+        if (newaudioinchan[i])
+        {
+            newaudioindev[nindev] = newaudioindev[i];
+            newaudioinchan[nindev] = newaudioinchan[i];
+            /* post("in %d %d %d", nindev,
+                newaudioindev[nindev] , newaudioinchan[nindev]); */
+            nindev++;
+        }
+    }
+    for (i = 0, noutdev = 0; i < 4; i++)
+    {
+        if (newaudiooutchan[i])
+        {
+            newaudiooutdev[noutdev] = newaudiooutdev[i];
+            newaudiooutchan[noutdev] = newaudiooutchan[i];
+            /* post("out %d %d %d", noutdev,
+                newaudiooutdev[noutdev] , newaudioinchan[noutdev]); */
+            noutdev++;
+        }
+    }
+    
+    if (newcallback < 0)
+        newcallback = 0;
+    if (!audio_callback_is_open && !newcallback)
+        sys_close_audio();
+    sys_set_audio_settings(nindev, newaudioindev, nindev, newaudioinchan,
+        noutdev, newaudiooutdev, noutdev, newaudiooutchan,
+        newrate, newadvance, (newcallback >= 0 ? newcallback : 0));
+    if (!audio_callback_is_open && !newcallback)
+        sys_reopen_audio();
+    else sched_reopenmeplease();
+}
+
+void sys_listdevs(void )
+{
+#ifdef USEAPI_PORTAUDIO
+    if (sys_audioapi == API_PORTAUDIO)
+        sys_listaudiodevs();
+    else 
+#endif
+#ifdef USEAPI_JACK
+    if (sys_audioapi == API_JACK)
+        jack_listdevs();
+    else
+#endif
+#ifdef USEAPI_OSS
+    if (sys_audioapi == API_OSS)
+        sys_listaudiodevs();
+    else
+#endif
+#ifdef USEAPI_ALSA
+    if (sys_audioapi == API_ALSA)
+        sys_listaudiodevs();
+    else
+#endif
+#ifdef USEAPI_MMIO
+    if (sys_audioapi == API_MMIO)
+        sys_listaudiodevs();
+    else
+#endif
+    post("unknown API");    
+
+    sys_listmididevs();
+}
+
+void sys_setblocksize(int n)
+{
+    if (n < 1)
+        n = 1;
+    if (n != (1 << ilog2(n)))
+        post("warning: adjusting blocksize to power of 2: %d", 
+            (n = (1 << ilog2(n))));
+    sys_blocksize = n;
+}
+
+void sys_set_audio_api(int which)
+{
+     sys_audioapi = which;
+     if (sys_verbose)
+        post("sys_audioapi %d", sys_audioapi);
+}
+
+void glob_audio_setapi(void *dummy, t_floatarg f)
+{
+    int newapi = f;
+    if (newapi)
+    {
+        if (newapi == sys_audioapi)
+        {
+            if (!audio_isopen())
+                sys_reopen_audio();
+        }
+        else
+        {
+            sys_close_audio();
+            sys_audioapi = newapi;
+                /* bash device params back to default */
+            audio_naudioindev = audio_naudiooutdev = 1;
+            audio_audioindev[0] = audio_audiooutdev[0] = DEFAULTAUDIODEV;
+            audio_audiochindev[0] = audio_audiochoutdev[0] = SYS_DEFAULTCH;
+            sys_reopen_audio();
+        }
+        glob_audio_properties(0, 0);
+    }
+    else if (audio_isopen())
+    {
+        sys_close_audio();
+    }
+}
+
+    /* start or stop the audio hardware */
+void sys_set_audio_state(int onoff)
+{
+    if (onoff)  /* start */
+    {
+        if (!audio_isopen())
+            sys_reopen_audio();    
+    }
+    else
+    {
+        if (audio_isopen())
+            sys_close_audio();
+    }
+}
+
+void sys_get_audio_apis(char *buf)
+{
+    int n = 0;
+    strcpy(buf, "{ ");
+#ifdef USEAPI_OSS
+    sprintf(buf + strlen(buf), "{OSS %d} ", API_OSS); n++;
+#endif
+#ifdef USEAPI_MMIO
+    sprintf(buf + strlen(buf), "{\"standard (MMIO)\" %d} ", API_MMIO); n++;
+#endif
+#ifdef USEAPI_ALSA
+    sprintf(buf + strlen(buf), "{ALSA %d} ", API_ALSA); n++;
+#endif
+#ifdef USEAPI_PORTAUDIO
+#ifdef MSW
+    sprintf(buf + strlen(buf),
+        "{\"ASIO (via portaudio)\" %d} ", API_PORTAUDIO);
+#else
+#ifdef OSX
+    sprintf(buf + strlen(buf),
+        "{\"standard (portaudio)\" %d} ", API_PORTAUDIO);
+#else
+    sprintf(buf + strlen(buf), "{portaudio %d} ", API_PORTAUDIO);
+#endif
+#endif
+     n++;
+#endif
+#ifdef USEAPI_JACK
+    sprintf(buf + strlen(buf), "{jack %d} ", API_JACK); n++;
+#endif
+    strcat(buf, "}");
+        /* then again, if only one API (or none) we don't offer any choice. */
+    if (n < 2)
+        strcpy(buf, "{}");
+}
+
+#ifdef USEAPI_ALSA
+void alsa_putzeros(int n);
+void alsa_getzeros(int n);
+void alsa_printstate( void);
+#endif
+
+    /* debugging */
+void glob_foo(void *dummy, t_symbol *s, int argc, t_atom *argv)
+{
+    t_symbol *arg = atom_getsymbolarg(0, argc, argv);
+    if (arg == gensym("restart"))
+        sys_reopen_audio();
+#ifdef USEAPI_ALSA
+    else if (arg == gensym("alsawrite"))
+    {
+        int n = atom_getintarg(1, argc, argv);
+        alsa_putzeros(n);
+    }
+    else if (arg == gensym("alsaread"))
+    {
+        int n = atom_getintarg(1, argc, argv);
+        alsa_getzeros(n);
+    }
+    else if (arg == gensym("print"))
+    {
+        alsa_printstate();
+    }
+#endif
+}
diff --git a/src/s_file.c b/src/s_file.c
index 67747ac58..7fe081a50 100644
--- a/src/s_file.c
+++ b/src/s_file.c
@@ -6,7 +6,7 @@
  * this file implements a mechanism for storing and retrieving preferences.
  * Should later be renamed "preferences.c" or something.
  *
- * In unix this is handled by the "~/.pdextended" file, in windows by
+ * In unix this is handled by the "~/.pdl2ork" file, in windows by
  * the registry, and in MacOS by the Preferences system.
  */
 
@@ -58,10 +58,11 @@ static void sys_initloadpreferences( void)
 	char default_prefs_file[FILENAME_MAX];
     struct stat statbuf;
 
-	snprintf(default_prefs_file, FILENAME_MAX, "%s/default.pdextended", 
+	snprintf(default_prefs_file, FILENAME_MAX, "%s/default.pdl2ork", 
 			 sys_libdir->s_name);
+
     if (homedir)
-		snprintf(user_prefs_file, FILENAME_MAX, "%s/.pdextended", homedir);
+		snprintf(user_prefs_file, FILENAME_MAX, "%s/.pdl2ork", homedir);
 	if (stat(user_prefs_file, &statbuf) == 0) 
 		strncpy(filenamebuf, user_prefs_file, FILENAME_MAX);
 	else if (stat(default_prefs_file, &statbuf) == 0)
@@ -143,7 +144,7 @@ static void sys_initsavepreferences( void)
 
     if (!homedir)
         return;
-    snprintf(filenamebuf, FILENAME_MAX, "%s/.pdextended", homedir);
+    snprintf(filenamebuf, FILENAME_MAX, "%s/.pdl2ork", homedir);
     filenamebuf[FILENAME_MAX-1] = 0;
     if ((sys_prefsavefp = fopen(filenamebuf, "w")) == NULL)
     {
@@ -230,7 +231,7 @@ static void sys_donesavepreferences( void)
 #ifdef __APPLE__
 
 // prefs file that is currently the one to save to
-static char current_prefs[FILENAME_MAX] = "org.puredata.pdextended"; 
+static char current_prefs[FILENAME_MAX] = "org.puredata.pdl2ork"; 
 
 static void sys_initloadpreferences( void)
 {
@@ -247,13 +248,13 @@ static int sys_getpreference(const char *key, char *value, int size)
 	char *homedir = getenv("HOME");
     struct stat statbuf;
 	/* the 'defaults' command expects the filename without .plist at the end */
-	snprintf(default_prefs, FILENAME_MAX, "%s/../org.puredata.pdextended.default", 
+	snprintf(default_prefs, FILENAME_MAX, "%s/../org.puredata.pdl2ork.default", 
 			 sys_libdir->s_name);
-	snprintf(embedded_prefs, FILENAME_MAX, "%s/../org.puredata.pdextended", 
+	snprintf(embedded_prefs, FILENAME_MAX, "%s/../org.puredata.pdl2ork", 
 			 sys_libdir->s_name);
 	snprintf(embedded_prefs_file, FILENAME_MAX, "%s.plist", embedded_prefs);
 	snprintf(user_prefs_file, FILENAME_MAX, 
-			 "%s/Library/Preferences/org.puredata.pdextended.plist", homedir);
+			 "%s/Library/Preferences/org.puredata.pdl2ork.plist", homedir);
 	if (stat(embedded_prefs_file, &statbuf) == 0) 
 	{
 		snprintf(cmdbuf, FILENAME_MAX + 20, 
@@ -263,14 +264,14 @@ static int sys_getpreference(const char *key, char *value, int size)
 	else if (stat(user_prefs_file, &statbuf) == 0) 
 	{
 		snprintf(cmdbuf, FILENAME_MAX + 20, 
-				 "defaults read org.puredata.pdextended %s 2> /dev/null\n", key);
-        strcpy(current_prefs, "org.puredata.pdextended");
+				 "defaults read org.puredata.pdl2ork %s 2> /dev/null\n", key);
+        strcpy(current_prefs, "org.puredata.pdl2ork");
 	}
 	else 
 	{
 		snprintf(cmdbuf, FILENAME_MAX + 20, 
 				 "defaults read '%s' %s 2> /dev/null\n", default_prefs, key);
-        strcpy(current_prefs, "org.puredata.pdextended");
+        strcpy(current_prefs, "org.puredata.pdl2ork");
 	}
     FILE *fp = popen(cmdbuf, "r");
     while (nread < size)
diff --git a/src/s_inter.c b/src/s_inter.c
index 8eba03780..6d0191a47 100644
--- a/src/s_inter.c
+++ b/src/s_inter.c
@@ -80,6 +80,8 @@ typedef int socklen_t;
 #define LOCALHOST "localhost"
 #endif
 
+#include <execinfo.h>
+
 typedef struct _fdpoll
 {
     int fdp_fd;
@@ -645,6 +647,19 @@ static void sys_trytogetmoreguibuf(int newsize)
     }
 }
 
+void blargh(void) {
+#ifdef MACOSX
+  fprintf(stderr,"unhandled exception\n");
+#else
+  int i;
+  void *array[25];
+  int nSize = backtrace(array, 25);
+  char **symbols = backtrace_symbols(array, nSize);
+  for (i=0; i<nSize; i++) fprintf(stderr,"%d: %s\n",i,symbols[i]);
+  free(symbols);
+#endif
+}
+
 void sys_vgui(char *fmt, ...)
 {
     int msglen, bytesleft, headwas, nwrote;
@@ -688,8 +703,10 @@ void sys_vgui(char *fmt, ...)
         if (msglen >= sys_guibufsize - sys_guibufhead)
             msglen = sys_guibufsize - sys_guibufhead;
     }
-    if (sys_debuglevel & DEBUG_MESSUP)
+    if (sys_debuglevel & DEBUG_MESSUP) {
+		//blargh();
         fprintf(stderr, "%s",  sys_guibuf + sys_guibufhead);
+	}
     sys_guibufhead += msglen;
     sys_bytessincelastping += msglen;
 }
diff --git a/src/s_main.c b/src/s_main.c
index ba1690175..b351474a3 100644
--- a/src/s_main.c
+++ b/src/s_main.c
@@ -80,7 +80,7 @@ int sys_extraflags;
 char sys_extraflagsstring[MAXPDSTRING];
 int sys_run_scheduler(const char *externalschedlibname,
     const char *sys_extraflagsstring);
-int sys_noautopatch = 1;    /* temporary hack to defeat new 0.42 editing */
+int sys_noautopatch = 0;    /* temporary hack to defeat new 0.42 editing */
 
     /* here the "-1" counts signify that the corresponding vector hasn't been
     specified in command line arguments; sys_set_audio_settings will detect it
@@ -478,9 +478,9 @@ void sys_findprogdir(char *progname)
             .../doc
         and in "complicated" unix installations, it's:
             .../bin/pd
-            .../lib/pd-extended/bin/pd-gui
-            .../lib/pd-extended/doc
-        To decide which, we stat .../lib/pd-extended; if that exists, we assume it's
+            .../lib/pd-l2ork/bin/pd-gui
+            .../lib/pd-l2ork/doc
+        To decide which, we stat .../lib/pd-l2ork; if that exists, we assume it's
         the complicated layout.  In MSW, it's the "simple" layout, but
         the gui program is straight wish80:
             .../bin/pd
@@ -494,15 +494,15 @@ void sys_findprogdir(char *progname)
     realpath(sbuf2, sbuf);
     strncpy(sbuf2, sbuf, FILENAME_MAX-30);
     sbuf[FILENAME_MAX-30] = 0;
-    strcat(sbuf2, "/lib/pd-extended");
+    strcat(sbuf2, "/lib/pd-l2ork");
     if (stat(sbuf2, &statbuf) >= 0)
     {
             /* complicated layout: lib dir is the one we just stat-ed above */
         sys_libdir = gensym(sbuf2);
-            /* gui lives in .../lib/pd-extended/bin */
+            /* gui lives in .../lib/pd-l2ork/bin */
         strncpy(sbuf2, sbuf, FILENAME_MAX-30);
         sbuf[FILENAME_MAX-30] = 0;
-        strcat(sbuf2, "/lib/pd-extended/bin");
+        strcat(sbuf2, "/lib/pd-l2ork/bin");
         sys_guidir = gensym(sbuf2);
     }
     else
diff --git a/src/s_print.c b/src/s_print.c
index 8a6ede435..3aacd188b 100644
--- a/src/s_print.c
+++ b/src/s_print.c
@@ -203,5 +203,4 @@ void sys_ouch(void)
 {
     if (*errobject) error("%s: %s", errobject, errstring);
     else error("%s", errstring);
-    sys_gui("bell\n");
 }
diff --git a/src/t_tkcmd.c b/src/t_tkcmd.c
index 3b0fa86d2..711a16311 100644
--- a/src/t_tkcmd.c
+++ b/src/t_tkcmd.c
@@ -380,7 +380,7 @@ static void pd_startfromgui( void)
     if (lastchar)
         snprintf(pdbuf, lastchar - arg0 + 1, "%s", arg0);
     else strcpy(pdbuf, ".");
-    strcat(pdbuf, "/../bin/pdextended");
+    strcat(pdbuf, "/../bin/pd-l2ork");
 #ifdef DEBUGCONNECT     
     fprintf(stderr, "pdbuf is %s\n", pdbuf);
 #endif
diff --git a/src/x_arithmetic.c b/src/x_arithmetic.c
index 64c1872ed..70a120c50 100644
--- a/src/x_arithmetic.c
+++ b/src/x_arithmetic.c
@@ -685,8 +685,6 @@ static void *wrap_new(void)
 {
     t_object *x = (t_object *)pd_new(wrap_class);
     outlet_new(x, &s_float);
-    pd_error(x, "A new incompatible [wrap] object was introduced in Pd 0.42.");
-    post("\tFor a backwards-compatible version, use [zexy/wrap]");
     return (x);
 }
 
diff --git a/src/x_gui.c b/src/x_gui.c
index 99337dd89..810aed60c 100644
--- a/src/x_gui.c
+++ b/src/x_gui.c
@@ -14,6 +14,9 @@ away before the panel does... */
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif
+// jsarlo
+EXTERN void magicGlass_setup(void);
+// end jsarlo
 
 /* --------------------- graphics responder  ---------------- */
 
@@ -84,6 +87,16 @@ void gfxstub_new(t_pd *owner, void *key, const char *cmd)
     sys_gui(buf);
 }
 
+int gfxstub_haveproperties(void *key) {
+    t_gfxstub *x;
+    for (x = gfxstub_list; x; x = x->x_next) {
+        if (x->x_key == key) {
+            return (t_int)x;
+		}
+	}
+	return 0;
+}
+
 static void gfxstub_offlist(t_gfxstub *x)
 {
     t_gfxstub *y1, *y2;
@@ -401,4 +414,7 @@ void x_gui_setup(void)
     openpanel_setup();
     savepanel_setup();
     key_setup();
+    // jsarlo
+    magicGlass_setup();
+    // end jsarlo
 }
diff --git a/src/x_interface.c b/src/x_interface.c
index 3c31c4c5a..231a0cf80 100644
--- a/src/x_interface.c
+++ b/src/x_interface.c
@@ -25,7 +25,6 @@ static void *print_new(t_symbol *s, int argc, t_atom *argv)
         t_binbuf *bb = binbuf_new();
         binbuf_add(bb, argc, argv);
         binbuf_gettext(bb, &buf, &bufsize);
-        buf = t_resizebytes(buf, bufsize, bufsize+1);
         buf[bufsize] = 0;
         x->x_sym = gensym(buf);
         binbuf_free(bb);
diff --git a/tcl/AppMain.tcl b/tcl/AppMain.tcl
new file mode 100644
index 000000000..b170c6f5c
--- /dev/null
+++ b/tcl/AppMain.tcl
@@ -0,0 +1,26 @@
+# This file is for the Wish.app on Mac OS X.  It is only used when a Wish.app
+# is loading embedded pd code on Mac OS X.  It is completely unused on any
+# other configuration, like when 'pd' launches Wish.app or when 'pd' is using
+# an X11 wish on Mac OS X.  GNU/Linux and Windows will never use this file.
+
+
+puts --------------------------AppMain.tcl-----------------------------------
+catch {console show}
+
+package require apple_events
+
+puts "AppMain.tcl"
+puts "argv0: $argv0"
+puts "executable: [info nameofexecutable]"
+puts "argc: $argc argv: $argv"
+
+# TODO is there anything useful to do with the psn (Process Serial Number)?
+if {[string first "-psn" [lindex $argv 0]] == 0} { 
+    set argv [lrange $argv 1 end]
+    set argc [expr $argc - 1]
+}
+
+# launch pd-gui.tcl here
+if [catch {source [file join [file dirname [info script]] pd-gui.tcl]}] { 
+    puts stderr $errorInfo
+}
diff --git a/tcl/apple_events.tcl b/tcl/apple_events.tcl
new file mode 100644
index 000000000..cfc92982b
--- /dev/null
+++ b/tcl/apple_events.tcl
@@ -0,0 +1,53 @@
+
+package provide apple_events 0.1
+
+package require wheredoesthisgo
+
+# from http://wiki.tcl.tk/12987
+
+set ::tk::mac::CGAntialiasLimit 0 ;# min line thickness to anti-alias (default: 3)
+set ::tk::mac::antialiasedtext  1 ;# enable/disable anti-aliased text
+
+# kAEOpenDocuments
+proc ::tk::mac::OpenDocument {args} {
+    foreach filename $args { 
+        puts "open_file $filename"
+        open_file $filename
+    }
+    set ::pd_menucommands::menu_open_dir [file dirname $filename]
+}
+
+# kEventAppHidden
+proc ::tk::mac::OnHide {} {
+    # TODO
+}
+
+# kEventAppShown
+proc ::tk::mac::OnShow {} {
+    # TODO
+}
+
+# kAEShowPreferences
+proc ::tk::mac::ShowPreferences {} {
+     menu_preferences_dialog
+}
+
+# kAEQuitApplication
+#proc ::tk::mac::Quit {} {
+#    # TODO sort this out... how to quit pd-gui after sending the message
+#    puts stderr "Custom exit proc"
+#    pdsend "pd verifyquit"
+#}
+
+# these I gleaned by reading the source (tkMacOSXHLEvents.c)
+proc ::tk::mac::PrintDocument {args} {
+    # TODO what's $mytoplevel here?.  I am guessing args would be the same as
+    # ::tk::mac::OpenDocument
+    #menu_print $mytoplevel
+}
+
+proc ::tk::mac::OpenApplication {} {
+}
+
+proc ::tk::mac::ReopenApplication {} {
+}
diff --git a/tcl/dialog_array.tcl b/tcl/dialog_array.tcl
new file mode 100644
index 000000000..87b2de8ce
--- /dev/null
+++ b/tcl/dialog_array.tcl
@@ -0,0 +1,328 @@
+package provide dialog_array 0.1
+
+namespace eval ::dialog_array:: {
+    namespace export pdtk_array_dialog
+    namespace export pdtk_array_listview_new
+    namespace export pdtk_array_listview_fillpage
+    namespace export pdtk_array_listview_setpage
+    namespace export pdtk_array_listview_closeWindow
+}
+
+# global variables for the listview
+array set pd_array_listview_entry {}
+array set pd_array_listview_id {}
+array set pd_array_listview_page {}
+set pd_array_listview_pagesize 0
+# this stores the state of the "save me" check button
+array set saveme_button {}
+# this stores the state of the "draw as" radio buttons
+array set drawas_button {}
+# this stores the state of the "in new graph"/"in last graph" radio buttons
+# and the "delete array" checkbutton
+array set otherflag_button {}
+
+# TODO figure out how to escape $ args so sharptodollar() isn't needed
+
+############ pdtk_array_dialog -- dialog window for arrays #########
+
+proc ::dialog_array::pdtk_array_listview_setpage {arrayName page} {
+    set ::pd_array_listview_page($arrayName) $page
+}
+
+proc ::dialog_array::listview_changepage {arrayName np} {
+    pdtk_array_listview_setpage \
+        $arrayName [expr $::pd_array_listview_page($arrayName) + $np]
+    pdtk_array_listview_fillpage $arrayName
+}
+
+proc ::dialog_array::pdtk_array_listview_fillpage {arrayName} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    set topItem [expr [lindex [$windowName.lb yview] 0] * \
+                     [$windowName.lb size]]
+    
+    if {[winfo exists $windowName]} {
+        set cmd "$::pd_array_listview_id($arrayName) \
+               arrayviewlistfillpage \
+               $::pd_array_listview_page($arrayName) \
+               $topItem"
+        
+        pdsend $cmd
+    }
+}
+
+proc ::dialog_array::pdtk_array_listview_new {id arrayName page} {
+    set ::pd_array_listview_page($arrayName) $page
+    set ::pd_array_listview_id($arrayName) $id
+    set windowName [format ".%sArrayWindow" $arrayName]
+    if [winfo exists $windowName] then [destroy $windowName]
+    toplevel $windowName -class DialogWindow
+    wm group $windowName .
+    wm protocol $windowName WM_DELETE_WINDOW \
+        "::dialog_array::listview_close $id $arrayName"
+    wm title $windowName [concat $arrayName "(list view)"]
+    # FIXME
+    set font 12
+    set $windowName.lb [listbox $windowName.lb -height 20 -width 25\
+                            -selectmode extended \
+                            -relief solid -background white -borderwidth 1 \
+                            -font [format {{%s} %d %s} $::font_family $font $::font_weight]\
+                            -yscrollcommand "$windowName.lb.sb set"]
+    set $windowName.lb.sb [scrollbar $windowName.lb.sb \
+                               -command "$windowName.lb yview" -orient vertical]
+    place configure $windowName.lb.sb -relheight 1 -relx 0.9 -relwidth 0.1
+    pack $windowName.lb -expand 1 -fill both
+    bind $windowName.lb <Double-ButtonPress-1> \
+        "::dialog_array::listview_edit $arrayName $page $font"
+    # handle copy/paste
+    switch -- $::windowingsystem {
+        "x11" {selection handle $windowName.lb \
+                   "::dialog_array::listview_lbselection $arrayName"}
+        "win32" {bind $windowName.lb <ButtonPress-3> \
+                     "::dialog_array::listview_popup $arrayName"} 
+    }
+    set $windowName.prevBtn [button $windowName.prevBtn -text "<-" \
+                                 -command "::dialog_array::listview_changepage $arrayName -1"]
+    set $windowName.nextBtn [button $windowName.nextBtn -text "->" \
+                                 -command "::dialog_array::listview_changepage $arrayName 1"]
+    pack $windowName.prevBtn -side left -ipadx 20 -pady 10 -anchor s
+    pack $windowName.nextBtn -side right -ipadx 20 -pady 10 -anchor s
+    focus $windowName
+}
+
+proc ::dialog_array::listview_lbselection {arrayName off size} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    set itemNums [$windowName.lb curselection]
+    set cbString ""
+    for {set i 0} {$i < [expr [llength $itemNums] - 1]} {incr i} {
+        set listItem [$windowName.lb get [lindex $itemNums $i]]
+        append cbString [string range $listItem \
+                             [expr [string first ") " $listItem] + 2] \
+                             end]
+        append cbString "\n"
+    }
+    set listItem [$windowName.lb get [lindex $itemNums $i]]
+    append cbString [string range $listItem \
+                         [expr [string first ") " $listItem] + 2] \
+                         end]
+    set last $cbString
+}
+
+# Win32 uses a popup menu for copy/paste
+proc ::dialog_array::listview_popup {arrayName} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    if [winfo exists $windowName.popup] then [destroy $windowName.popup]
+    menu $windowName.popup -tearoff false
+    $windowName.popup add command -label [_ "Copy"] \
+        -command "::dialog_array::listview_copy $arrayName; \
+                  destroy $windowName.popup"
+    $windowName.popup add command -label [_ "Paste"] \
+        -command "::dialog_array::listview_paste $arrayName; \
+                  destroy $windowName.popup"
+    tk_popup $windowName.popup [winfo pointerx $windowName] \
+        [winfo pointery $windowName] 0
+}
+
+proc ::dialog_array::listview_copy {arrayName} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    set itemNums [$windowName.lb curselection]
+    set cbString ""
+    for {set i 0} {$i < [expr [llength $itemNums] - 1]} {incr i} {
+        set listItem [$windowName.lb get [lindex $itemNums $i]]
+        append cbString [string range $listItem \
+                             [expr [string first ") " $listItem] + 2] \
+                             end]
+        append cbString "\n"
+    }
+    set listItem [$windowName.lb get [lindex $itemNums $i]]
+    append cbString [string range $listItem \
+                         [expr [string first ") " $listItem] + 2] \
+                         end]
+    clipboard clear
+    clipboard append $cbString
+}
+
+proc ::dialog_array::listview_paste {arrayName} {
+    set cbString [selection get -selection CLIPBOARD]
+    set lbName [format ".%sArrayWindow.lb" $arrayName]
+    set itemNum [lindex [$lbName curselection] 0]
+    set splitChars ", \n"
+    set itemString [split $cbString $splitChars]
+    set flag 1
+    for {set i 0; set counter 0} {$i < [llength $itemString]} {incr i} {
+        if {[lindex $itemString $i] ne {}} {
+            pdsend "$arrayName [expr $itemNum + \
+                                       [expr $counter + \
+                                            [expr $::pd_array_listview_pagesize \
+                                                 * $::pd_array_listview_page($arrayName)]]] \
+                    [lindex $itemString $i]"
+            incr counter
+            set flag 0
+        }
+    }
+}
+
+proc ::dialog_array::listview_edit {arrayName page font} {
+    set lbName [format ".%sArrayWindow.lb" $arrayName]
+    if {[winfo exists $lbName.entry]} {
+        ::dialog_array::listview_update_entry \
+            $arrayName $::pd_array_listview_entry($arrayName)
+        unset ::pd_array_listview_entry($arrayName)
+    }
+    set itemNum [$lbName index active]
+    set ::pd_array_listview_entry($arrayName) $itemNum
+    set bbox [$lbName bbox $itemNum]
+    set y [expr [lindex $bbox 1] - 4]
+    set $lbName.entry [entry $lbName.entry \
+                           -font [format {{%s} %d %s} $::font_family $font $::font_weight]]
+    $lbName.entry insert 0 []
+    place configure $lbName.entry -relx 0 -y $y -relwidth 1
+    lower $lbName.entry
+    focus $lbName.entry
+    bind $lbName.entry <Return> \
+        "::dialog_array::listview_update_entry $arrayName $itemNum;"
+}
+
+proc ::dialog_array::listview_update_entry {arrayName itemNum} {
+    set lbName [format ".%sArrayWindow.lb" $arrayName]
+    set splitChars ", \n"
+    set itemString [split [$lbName.entry get] $splitChars]
+    set flag 1
+    for {set i 0; set counter 0} {$i < [llength $itemString]} {incr i} {
+        if {[lindex $itemString $i] ne {}} {
+            pdsend "$arrayName [expr $itemNum + \
+                                       [expr $counter + \
+                                            [expr $::pd_array_listview_pagesize \
+                                                 * $::pd_array_listview_page($arrayName)]]] \
+                    [lindex $itemString $i]"
+            incr counter
+            set flag 0
+        }
+    }
+    pdtk_array_listview_fillpage $arrayName
+    destroy $lbName.entry
+}
+
+proc ::dialog_array::pdtk_array_listview_closeWindow {arrayName} {
+    set mytoplevel [format ".%sArrayWindow" $arrayName]
+    destroy $mytoplevel
+}
+
+proc ::dialog_array::listview_close {mytoplevel arrayName} {
+    pdtk_array_listview_closeWindow $arrayName
+    pdsend "$mytoplevel arrayviewclose"
+}
+
+proc ::dialog_array::apply {mytoplevel} {
+# TODO figure out how to ditch this escaping mechanism
+    set mofo [$mytoplevel.name.entry get]
+    if {[string index $mofo 0] == "$"} {
+        set mofo [string replace $mofo 0 0 #] }
+
+    pdsend "$mytoplevel arraydialog \
+            $mofo \
+            [$mytoplevel.size.entry get] \
+            [expr $::saveme_button($mytoplevel) + (2 * $::drawas_button($mytoplevel))] \
+            $::otherflag_button($mytoplevel)"
+}
+
+proc ::dialog_array::openlistview {mytoplevel} {
+    pdsend "$mytoplevel arrayviewlistnew"
+}
+
+proc ::dialog_array::cancel {mytoplevel} {
+    pdsend "$mytoplevel cancel"
+}
+
+proc ::dialog_array::ok {mytoplevel} {
+    ::dialog_array::apply $mytoplevel
+    ::dialog_array::cancel $mytoplevel
+}
+
+proc ::dialog_array::pdtk_array_dialog {mytoplevel name size flags newone} {
+puts "::dialog_array::pdtk_array_dialog {$mytoplevel $name $size $flags $newone}"
+    if {[winfo exists $mytoplevel]} {
+        wm deiconify $mytoplevel
+        raise $mytoplevel
+    } else {
+        create_dialog $mytoplevel $newone
+    }
+
+    $mytoplevel.name.entry insert 0 $name
+    $mytoplevel.size.entry insert 0 $size
+    set ::saveme_button($mytoplevel) [expr $flags & 1]
+    set ::drawas_button($mytoplevel) [expr ( $flags & 6 ) >> 1]
+    set ::otherflag_button($mytoplevel) 0
+# pd -> tcl
+#  2 * (int)(template_getfloat(template_findbyname(sc->sc_template), gensym("style"), x->x_scalar->sc_vec, 1)));
+
+# tcl->pd
+#    int style = ((flags & 6) >> 1);
+}
+
+proc ::dialog_array::create_dialog {mytoplevel newone} {
+    toplevel $mytoplevel -class DialogWindow
+    wm title $mytoplevel [_ "Array Properties"]
+    if {$::windowingsystem eq "aqua"} {$mytoplevel configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $mytoplevel "array"
+
+    frame $mytoplevel.name
+    pack $mytoplevel.name -side top
+    label $mytoplevel.name.label -text [_ "Name:"]
+    entry $mytoplevel.name.entry
+    pack $mytoplevel.name.label $mytoplevel.name.entry -anchor w
+
+    frame $mytoplevel.size
+    pack $mytoplevel.size -side top
+    label $mytoplevel.size.label -text [_ "Size:"]
+    entry $mytoplevel.size.entry
+    pack $mytoplevel.size.label $mytoplevel.size.entry -anchor w
+
+    checkbutton $mytoplevel.saveme -text [_ "Save contents"] \
+        -variable ::saveme_button($mytoplevel) -anchor w
+    pack $mytoplevel.saveme -side top
+
+    labelframe $mytoplevel.drawas -text [_ "Draw as:"] -padx 20 -borderwidth 1
+    pack $mytoplevel.drawas -side top -fill x
+    radiobutton $mytoplevel.drawas.points -value 0 \
+        -variable ::drawas_button($mytoplevel) -text [_ "Points"]
+    radiobutton $mytoplevel.drawas.polygon -value 1 \
+        -variable ::drawas_button($mytoplevel) -text [_ "Polygon"]
+    radiobutton $mytoplevel.drawas.bezier -value 2 \
+        -variable ::drawas_button($mytoplevel) -text [_ "Bezier curve"]
+    pack $mytoplevel.drawas.points -side top -anchor w
+    pack $mytoplevel.drawas.polygon -side top -anchor w
+    pack $mytoplevel.drawas.bezier -side top -anchor w
+
+    if {$newone != 0} {
+        labelframe $mytoplevel.radio -text [_ "Put array into:"] -padx 20 -borderwidth 1
+        pack $mytoplevel.radio -side top -fill x
+        radiobutton $mytoplevel.radio.radio0 -value 0 \
+            -variable ::otherflag_button($mytoplevel) -text [_ "New graph"]
+        radiobutton $mytoplevel.radio.radio1 -value 1 \
+            -variable ::otherflag_button($mytoplevel) -text [_ "Last graph"]
+        pack $mytoplevel.radio.radio0 -side top -anchor w
+        pack $mytoplevel.radio.radio1 -side top -anchor w
+    } else {    
+        checkbutton $mytoplevel.deletearray -text [_ "Delete array"] \
+            -variable ::otherflag_button($mytoplevel) -anchor w
+        pack $mytoplevel.deletearray -side top
+    }
+    # jsarlo
+    if {$newone == 0} {
+        button $mytoplevel.listview -text [_ "Open List View..."] \
+            -command "::dialog_array::openlistview $mytoplevel [$mytoplevel.name.entry get]"
+        pack $mytoplevel.listview -side top
+    }
+    # end jsarlo
+    frame $mytoplevel.buttonframe
+    pack $mytoplevel.buttonframe -side bottom -fill x -pady 2m
+    button $mytoplevel.buttonframe.cancel -text [_ "Cancel"] \
+        -command "::dialog_array::cancel $mytoplevel"
+    if {$newone == 0} {button $mytoplevel.buttonframe.apply -text [_ "Apply"] \
+                           -command "::dialog_array::apply $mytoplevel"}
+    button $mytoplevel.buttonframe.ok -text [_ "OK"]\
+        -command "::dialog_array::ok $mytoplevel"
+    pack $mytoplevel.buttonframe.cancel -side left -expand 1
+    if {$newone == 0} {pack $mytoplevel.buttonframe.apply -side left -expand 1}
+    pack $mytoplevel.buttonframe.ok -side left -expand 1
+}
diff --git a/tcl/dialog_audio.tcl b/tcl/dialog_audio.tcl
new file mode 100644
index 000000000..1025f66e0
--- /dev/null
+++ b/tcl/dialog_audio.tcl
@@ -0,0 +1,298 @@
+package provide dialog_audio 0.1
+
+namespace eval ::dialog_audio:: {
+    namespace export pdtk_audio_dialog
+}
+
+# TODO this panel really needs some reworking, it works but the code is
+# very unreadable
+
+####################### audio dialog ##################3
+
+proc ::dialog_audio::apply {id} {
+    global audio_indev1 audio_indev2 audio_indev3 audio_indev4 
+    global audio_inchan1 audio_inchan2 audio_inchan3 audio_inchan4
+    global audio_inenable1 audio_inenable2 audio_inenable3 audio_inenable4
+    global audio_outdev1 audio_outdev2 audio_outdev3 audio_outdev4 
+    global audio_outchan1 audio_outchan2 audio_outchan3 audio_outchan4
+    global audio_outenable1 audio_outenable2 audio_outenable3 audio_outenable4
+    global audio_sr audio_advance audio_callback
+
+    pdsend "pd audio-dialog \
+        $audio_indev1 \
+        $audio_indev2 \
+        $audio_indev3 \
+        $audio_indev4 \
+        [expr $audio_inchan1 * ( $audio_inenable1 ? 1 : -1 ) ]\
+        [expr $audio_inchan2 * ( $audio_inenable2 ? 1 : -1 ) ]\
+        [expr $audio_inchan3 * ( $audio_inenable3 ? 1 : -1 ) ]\
+        [expr $audio_inchan4 * ( $audio_inenable4 ? 1 : -1 ) ]\
+        $audio_outdev1 \
+        $audio_outdev2 \
+        $audio_outdev3 \
+        $audio_outdev4 \
+        [expr $audio_outchan1 * ( $audio_outenable1 ? 1 : -1 ) ]\
+        [expr $audio_outchan2 * ( $audio_outenable2 ? 1 : -1 ) ]\
+        [expr $audio_outchan3 * ( $audio_outenable3 ? 1 : -1 ) ]\
+        [expr $audio_outchan4 * ( $audio_outenable4 ? 1 : -1 ) ]\
+        $audio_sr \
+        $audio_advance \
+        $audio_callback"
+}
+
+proc ::dialog_audio::cancel {id} {
+    pdsend "$id cancel"
+}
+
+proc ::dialog_audio::ok {id} {
+    ::dialog_audio::apply $id
+    ::dialog_audio::cancel $id
+}
+
+# callback from popup menu
+proc audio_popup_action {buttonname varname devlist index} {
+    global audio_indevlist audio_outdevlist $varname
+    $buttonname configure -text [lindex $devlist $index]
+    set $varname $index
+}
+
+# create a popup menu
+proc audio_popup {name buttonname varname devlist} {
+    if [winfo exists $name.popup] {destroy $name.popup}
+    menu $name.popup -tearoff false
+    if {$::windowingsystem eq "win32"} {
+        $name.popup configure -font menuFont
+    }
+    for {set x 0} {$x<[llength $devlist]} {incr x} {
+        $name.popup add command -label [lindex $devlist $x] \
+            -command [list audio_popup_action \
+                          $buttonname $varname $devlist $x] 
+    }
+    tk_popup $name.popup [winfo pointerx $name] [winfo pointery $name] 0
+}
+
+# start a dialog window to select audio devices and settings.  "multi"
+# is 0 if only one device is allowed; 1 if one apiece may be specified for
+# input and output; and 2 if we can select multiple devices.  "longform"
+# (which only makes sense if "multi" is 2) asks us to make controls for
+# opening several devices; if not, we get an extra button to turn longform
+# on and restart the dialog.
+
+proc ::dialog_audio::pdtk_audio_dialog {id indev1 indev2 indev3 indev4 \
+        inchan1 inchan2 inchan3 inchan4 \
+        outdev1 outdev2 outdev3 outdev4 \
+        outchan1 outchan2 outchan3 outchan4 sr advance multi callback \
+        longform} {
+    global audio_indev1 audio_indev2 audio_indev3 audio_indev4 
+    global audio_inchan1 audio_inchan2 audio_inchan3 audio_inchan4
+    global audio_inenable1 audio_inenable2 audio_inenable3 audio_inenable4
+    global audio_outdev1 audio_outdev2 audio_outdev3 audio_outdev4
+    global audio_outchan1 audio_outchan2 audio_outchan3 audio_outchan4
+    global audio_outenable1 audio_outenable2 audio_outenable3 audio_outenable4
+    global audio_sr audio_advance audio_callback
+    global audio_indevlist audio_outdevlist
+    global pd_indev pd_outdev
+    global audio_longform
+
+    set audio_indev1 $indev1
+    set audio_indev2 $indev2
+    set audio_indev3 $indev3
+    set audio_indev4 $indev4
+
+    set audio_inchan1 [expr ( $inchan1 > 0 ? $inchan1 : -$inchan1 ) ]
+    set audio_inenable1 [expr $inchan1 > 0 ]
+    set audio_inchan2 [expr ( $inchan2 > 0 ? $inchan2 : -$inchan2 ) ]
+    set audio_inenable2 [expr $inchan2 > 0 ]
+    set audio_inchan3 [expr ( $inchan3 > 0 ? $inchan3 : -$inchan3 ) ]
+    set audio_inenable3 [expr $inchan3 > 0 ]
+    set audio_inchan4 [expr ( $inchan4 > 0 ? $inchan4 : -$inchan4 ) ]
+    set audio_inenable4 [expr $inchan4 > 0 ]
+
+    set audio_outdev1 $outdev1
+    set audio_outdev2 $outdev2
+    set audio_outdev3 $outdev3
+    set audio_outdev4 $outdev4
+
+    set audio_outchan1 [expr ( $outchan1 > 0 ? $outchan1 : -$outchan1 ) ]
+    set audio_outenable1 [expr $outchan1 > 0 ]
+    set audio_outchan2 [expr ( $outchan2 > 0 ? $outchan2 : -$outchan2 ) ]
+    set audio_outenable2 [expr $outchan2 > 0 ]
+    set audio_outchan3 [expr ( $outchan3 > 0 ? $outchan3 : -$outchan3 ) ]
+    set audio_outenable3 [expr $outchan3 > 0 ]
+    set audio_outchan4 [expr ( $outchan4 > 0 ? $outchan4 : -$outchan4 ) ]
+    set audio_outenable4 [expr $outchan4 > 0 ]
+
+    set audio_sr $sr
+    set audio_advance $advance
+    set audio_callback $callback
+
+    toplevel $id
+    wm title $id [_ "Audio Settings"]
+    if {$::windowingsystem eq "aqua"} {$id configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $id "audio"
+
+    frame $id.buttonframe
+    pack $id.buttonframe -side bottom -fill x -pady 2m
+    button $id.buttonframe.cancel -text [_ "Cancel"]\
+        -command "::dialog_audio::cancel $id"
+    button $id.buttonframe.apply -text [_ "Apply"]\
+        -command "::dialog_audio::apply $id"
+    button $id.buttonframe.ok -text [_ "OK"]\
+        -command "::dialog_audio::ok $id"
+    button $id.buttonframe.save -text [_ "Save all settings"]\
+        -command "::dialog_audio::apply $id \; pdsend \"pd save-preferences\""
+    pack $id.buttonframe.cancel $id.buttonframe.apply $id.buttonframe.ok \
+        $id.buttonframe.save -side left -expand 1
+    
+        # sample rate and advance
+    frame $id.srf
+    pack $id.srf -side top
+    
+    label $id.srf.l1 -text [_ "Sample rate:"]
+    entry $id.srf.x1 -textvariable audio_sr -width 7
+    label $id.srf.l2 -text [_ "Delay (msec):"]
+    entry $id.srf.x2 -textvariable audio_advance -width 4
+    pack $id.srf.l1 $id.srf.x1 $id.srf.l2 $id.srf.x2 -side left
+    if {$audio_callback >= 0} {
+        checkbutton $id.srf.x3 -variable audio_callback \
+            -text [_ "Use callbacks"] -anchor e
+        pack $id.srf.x3 -side left
+    }
+        # input device 1
+    frame $id.in1f
+    pack $id.in1f -side top
+
+    checkbutton $id.in1f.x0 -variable audio_inenable1 \
+        -text [_ "Input device 1:"] -anchor e
+    button $id.in1f.x1 -text [lindex $audio_indevlist $audio_indev1] \
+        -command [list audio_popup $id $id.in1f.x1 audio_indev1 $audio_indevlist]
+    label $id.in1f.l2 -text [_ "Channels:"]
+    entry $id.in1f.x2 -textvariable audio_inchan1 -width 3
+    pack $id.in1f.x0 $id.in1f.x1 $id.in1f.l2 $id.in1f.x2 -side left -fill x
+
+        # input device 2
+    if {$longform && $multi > 1 && [llength $audio_indevlist] > 1} {
+        frame $id.in2f
+        pack $id.in2f -side top
+
+        checkbutton $id.in2f.x0 -variable audio_inenable2 \
+            -text [_ "Input device 2:"] -anchor e
+        button $id.in2f.x1 -text [lindex $audio_indevlist $audio_indev2] \
+            -command [list audio_popup $id $id.in2f.x1 audio_indev2 \
+                $audio_indevlist]
+        label $id.in2f.l2 -text [_ "Channels:"]
+        entry $id.in2f.x2 -textvariable audio_inchan2 -width 3
+        pack $id.in2f.x0 $id.in2f.x1 $id.in2f.l2 $id.in2f.x2 -side left -fill x
+    }
+
+        # input device 3
+    if {$longform && $multi > 1 && [llength $audio_indevlist] > 2} {
+        frame $id.in3f
+        pack $id.in3f -side top
+
+        checkbutton $id.in3f.x0 -variable audio_inenable3 \
+            -text [_ "Input device 3:"] -anchor e
+        button $id.in3f.x1 -text [lindex $audio_indevlist $audio_indev3] \
+            -command [list audio_popup $id $id.in3f.x1 audio_indev3 \
+                $audio_indevlist]
+        label $id.in3f.l2 -text [_ "Channels:"]
+        entry $id.in3f.x2 -textvariable audio_inchan3 -width 3
+        pack $id.in3f.x0 $id.in3f.x1 $id.in3f.l2 $id.in3f.x2 -side left
+    }
+
+        # input device 4
+    if {$longform && $multi > 1 && [llength $audio_indevlist] > 3} {
+        frame $id.in4f
+        pack $id.in4f -side top
+
+        checkbutton $id.in4f.x0 -variable audio_inenable4 \
+            -text [_ "Input device 4:"] -anchor e
+        button $id.in4f.x1 -text [lindex $audio_indevlist $audio_indev4] \
+            -command [list audio_popup $id $id.in4f.x1 audio_indev4 \
+                $audio_indevlist]
+        label $id.in4f.l2 -text [_ "Channels:"]
+        entry $id.in4f.x2 -textvariable audio_inchan4 -width 3
+        pack $id.in4f.x0 $id.in4f.x1 $id.in4f.l2 $id.in4f.x2 -side left
+    }
+
+        # output device 1
+    frame $id.out1f
+    pack $id.out1f -side top
+
+    checkbutton $id.out1f.x0 -variable audio_outenable1 \
+        -text [_ "Output device 1:"] -anchor e
+    if {$multi == 0} {
+        label $id.out1f.l1 \
+            -text [_ "(same as input device) ..............      "]
+    } else {
+        button $id.out1f.x1 -text [lindex $audio_outdevlist $audio_outdev1] \
+            -command  [list audio_popup $id $id.out1f.x1 audio_outdev1 \
+                $audio_outdevlist]
+    }
+    label $id.out1f.l2 -text [_ "Channels:"]
+    entry $id.out1f.x2 -textvariable audio_outchan1 -width 3
+    if {$multi == 0} {
+        pack $id.out1f.x0 $id.out1f.l1 $id.out1f.x2 -side left -fill x
+    } else {
+        pack $id.out1f.x0 $id.out1f.x1 $id.out1f.l2 $id.out1f.x2 -side left -fill x
+    }
+
+        # output device 2
+    if {$longform && $multi > 1 && [llength $audio_outdevlist] > 1} {
+        frame $id.out2f
+        pack $id.out2f -side top
+
+        checkbutton $id.out2f.x0 -variable audio_outenable2 \
+            -text [_ "Output device 2:"] -anchor e
+        button $id.out2f.x1 -text [lindex $audio_outdevlist $audio_outdev2] \
+            -command \
+            [list audio_popup $id $id.out2f.x1 audio_outdev2 $audio_outdevlist]
+        label $id.out2f.l2 -text [_ "Channels:"]
+        entry $id.out2f.x2 -textvariable audio_outchan2 -width 3
+        pack $id.out2f.x0 $id.out2f.x1 $id.out2f.l2 $id.out2f.x2 -side left
+    }
+
+        # output device 3
+    if {$longform && $multi > 1 && [llength $audio_outdevlist] > 2} {
+        frame $id.out3f
+        pack $id.out3f -side top
+
+        checkbutton $id.out3f.x0 -variable audio_outenable3 \
+            -text [_ "Output device 3:"] -anchor e
+        button $id.out3f.x1 -text [lindex $audio_outdevlist $audio_outdev3] \
+            -command \
+            [list audio_popup $id $id.out3f.x1 audio_outdev3 $audio_outdevlist]
+        label $id.out3f.l2 -text [_ "Channels:"]
+        entry $id.out3f.x2 -textvariable audio_outchan3 -width 3
+        pack $id.out3f.x0 $id.out3f.x1 $id.out3f.l2 $id.out3f.x2 -side left
+    }
+
+        # output device 4
+    if {$longform && $multi > 1 && [llength $audio_outdevlist] > 3} {
+        frame $id.out4f
+        pack $id.out4f -side top
+
+        checkbutton $id.out4f.x0 -variable audio_outenable4 \
+            -text [_ "Output device 4:"] -anchor e
+        button $id.out4f.x1 -text [lindex $audio_outdevlist $audio_outdev4] \
+            -command \
+            [list audio_popup $id $id.out4f.x1 audio_outdev4 $audio_outdevlist]
+        label $id.out4f.l2 -text [_ "Channels:"]
+        entry $id.out4f.x2 -textvariable audio_outchan4 -width 3
+        pack $id.out4f.x0 $id.out4f.x1 $id.out4f.l2 $id.out4f.x2 -side left
+    }
+
+        # if not the "long form" but if "multi" is 2, make a button to
+        # restart with longform set. 
+    
+    if {$longform == 0 && $multi > 1} {
+        frame $id.longbutton
+        pack $id.longbutton -side top
+        button $id.longbutton.b -text [_ "Use multiple devices"] \
+            -command  {pdsend "pd audio-properties 1"}
+        pack $id.longbutton.b
+    }
+    $id.srf.x1 select from 0
+    $id.srf.x1 select adjust end
+    focus $id.srf.x1
+}
diff --git a/tcl/dialog_canvas.tcl b/tcl/dialog_canvas.tcl
new file mode 100644
index 000000000..06444807e
--- /dev/null
+++ b/tcl/dialog_canvas.tcl
@@ -0,0 +1,213 @@
+
+# TODO offset this panel so it doesn't overlap the pdtk_array panel
+
+package provide dialog_canvas 0.1
+
+namespace eval ::dialog_canvas:: {
+    namespace export pdtk_canvas_dialog
+}
+
+# global variables to store checkbox state on canvas properties window.  These
+# are only used in the context of getting data from the checkboxes, so they
+# aren't really useful elsewhere.  It would be nice to have them globally
+# useful, but that would mean changing the C code.
+array set graphme_button {}
+array set hidetext_button {}
+
+############# pdtk_canvas_dialog -- dialog window for canvases #################
+
+proc ::dialog_canvas::apply {mytoplevel} {
+    pdsend "$mytoplevel donecanvasdialog \
+            [$mytoplevel.scale.x.entry get] \
+            [$mytoplevel.scale.y.entry get] \
+            [expr $::graphme_button($mytoplevel) + 2 * $::hidetext_button($mytoplevel)] \
+            [$mytoplevel.range.x.from_entry get] \
+            [$mytoplevel.range.y.from_entry get] \
+            [$mytoplevel.range.x.to_entry get] \
+            [$mytoplevel.range.y.to_entry get] \
+            [$mytoplevel.range.x.size_entry get] \
+            [$mytoplevel.range.y.size_entry get] \
+            [$mytoplevel.range.x.margin_entry get] \
+            [$mytoplevel.range.y.margin_entry get]"
+}
+
+proc ::dialog_canvas::cancel {mytoplevel} {
+    pdsend "$mytoplevel cancel"
+}
+
+proc ::dialog_canvas::ok {mytoplevel} {
+    ::dialog_canvas::apply $mytoplevel
+    ::dialog_canvas::cancel $mytoplevel
+}
+
+proc ::dialog_canvas::checkcommand {mytoplevel} {
+    if { $::graphme_button($mytoplevel) != 0 } {
+        $mytoplevel.scale.x.entry configure -state disabled
+        $mytoplevel.scale.y.entry configure -state disabled
+        $mytoplevel.parent.hidetext configure -state normal
+        $mytoplevel.range.x.from_entry configure -state normal
+        $mytoplevel.range.x.to_entry configure -state normal
+        $mytoplevel.range.x.size_entry configure -state normal
+        $mytoplevel.range.x.margin_entry configure -state normal
+        $mytoplevel.range.y.from_entry configure -state normal
+        $mytoplevel.range.y.to_entry configure -state normal
+        $mytoplevel.range.y.size_entry configure -state normal
+        $mytoplevel.range.y.margin_entry configure -state normal
+        if { [$mytoplevel.range.x.from_entry get] == 0 \
+                 && [$mytoplevel.range.y.from_entry get] == 0 \
+                 && [$mytoplevel.range.x.to_entry get] == 0 \
+                 && [$mytoplevel.range.y.to_entry get] == 0 } {
+            $mytoplevel.range.y.to_entry insert 0 1
+            $mytoplevel.range.y.to_entry insert 0 1
+        }
+        if { [$mytoplevel.range.x.size_entry get] == 0 } {
+            $mytoplevel.range.x.size_entry delete 0 end
+            $mytoplevel.range.x.margin_entry delete 0 end
+            $mytoplevel.range.x.size_entry insert 0 85
+            $mytoplevel.range.x.margin_entry insert 0 100
+        }
+        if { [$mytoplevel.range.y.size_entry get] == 0 } {
+            $mytoplevel.range.y.size_entry delete 0 end
+            $mytoplevel.range.y.margin_entry delete 0 end
+            $mytoplevel.range.y.size_entry insert 0 60
+            $mytoplevel.range.y.margin_entry insert 0 100
+       }
+    } else {
+        $mytoplevel.scale.x.entry configure -state normal
+        $mytoplevel.scale.y.entry configure -state normal
+        $mytoplevel.parent.hidetext configure -state disabled
+        $mytoplevel.range.x.from_entry configure -state disabled
+        $mytoplevel.range.x.to_entry configure -state disabled
+        $mytoplevel.range.x.size_entry configure -state disabled
+        $mytoplevel.range.x.margin_entry configure -state disabled
+        $mytoplevel.range.y.from_entry configure -state disabled
+        $mytoplevel.range.y.to_entry configure -state disabled
+        $mytoplevel.range.y.size_entry configure -state disabled
+        $mytoplevel.range.y.margin_entry configure -state disabled
+        if { [$mytoplevel.scale.x.entry get] == 0 } {
+            $mytoplevel.scale.x.entry delete 0 end
+            $mytoplevel.scale.x.entry insert 0 1
+        }
+        if { [$mytoplevel.scale.y.entry get] == 0 } {
+            $mytoplevel.scale.y.entry delete 0 end
+            $mytoplevel.scale.y.entry insert 0 1
+        }
+    }
+}
+
+proc ::dialog_canvas::pdtk_canvas_dialog {mytoplevel xscale yscale graphmeflags \
+                                             xfrom yfrom xto yto \
+                                             xsize ysize xmargin ymargin} {
+    if {[winfo exists $mytoplevel]} {
+        wm deiconify $mytoplevel
+        raise $mytoplevel
+    } else {
+        create_dialog $mytoplevel
+    }
+    puts "canvas_dialog $mytoplevel"
+    switch -- $graphmeflags {
+        0 {
+            $mytoplevel.parent.graphme deselect
+            $mytoplevel.parent.hidetext deselect
+        } 1 {
+            $mytoplevel.parent.graphme select
+            $mytoplevel.parent.hidetext deselect
+        } 2 {
+            $mytoplevel.parent.graphme deselect
+            $mytoplevel.parent.hidetext select
+        } 3 {
+            $mytoplevel.parent.graphme select
+            $mytoplevel.parent.hidetext select
+        } default {
+            pdtk_post "Warning: unknown graphme flags received in pdtk_canvas_dialog"
+        }
+    }
+
+    $mytoplevel.scale.x.entry insert 0 $xscale
+    $mytoplevel.scale.y.entry insert 0 $yscale
+    $mytoplevel.range.x.from_entry insert 0 $xfrom
+    $mytoplevel.range.y.from_entry insert 0 $yfrom
+    $mytoplevel.range.x.to_entry insert 0 $xto
+    $mytoplevel.range.y.to_entry insert 0 $yto
+    $mytoplevel.range.x.size_entry insert 0 $xsize
+    $mytoplevel.range.y.size_entry insert 0 $ysize
+    $mytoplevel.range.x.margin_entry insert 0 $xsize
+    $mytoplevel.range.y.margin_entry insert 0 $ysize
+
+   ::dialog_canvas::checkcommand $mytoplevel
+}
+
+proc ::dialog_canvas::create_dialog {mytoplevel} {
+    toplevel $mytoplevel -class DialogWindow
+    wm title $mytoplevel [_ "Canvas Properties"]
+    if {$::windowingsystem eq "aqua"} {$mytoplevel configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $mytoplevel "canvas"
+    
+    labelframe $mytoplevel.scale -text [_ "Scale"] -borderwidth 1
+    pack $mytoplevel.scale -side top -fill x
+    frame $mytoplevel.scale.x -pady 2 -borderwidth 1
+    pack $mytoplevel.scale.x -side top
+    label $mytoplevel.scale.x.label -text [_ "X units per pixel:"]
+    entry $mytoplevel.scale.x.entry -width 10
+    pack $mytoplevel.scale.x.label $mytoplevel.scale.x.entry -side left
+    frame $mytoplevel.scale.y -pady 2
+    pack $mytoplevel.scale.y -side top
+    label $mytoplevel.scale.y.label -text [_ "Y units per pixel:"]
+    entry $mytoplevel.scale.y.entry -width 10
+    pack $mytoplevel.scale.y.label $mytoplevel.scale.y.entry -side left
+
+    labelframe $mytoplevel.parent -text [_ "Appearance on parent patch"] -borderwidth 1
+    pack $mytoplevel.parent -side top -fill x
+    checkbutton $mytoplevel.parent.graphme -text [_ "Graph-On-Parent"] \
+        -anchor w -variable graphme_button($mytoplevel) \
+        -command [concat ::dialog_canvas::checkcommand $mytoplevel]
+    pack $mytoplevel.parent.graphme -side top -fill x -padx 40
+    checkbutton $mytoplevel.parent.hidetext -text [_ "Hide object name and arguments"] \
+        -anchor w -variable hidetext_button($mytoplevel) \
+        -command [concat ::dialog_canvas::checkcommand $mytoplevel]
+    pack $mytoplevel.parent.hidetext -side top -fill x -padx 40
+
+    labelframe $mytoplevel.range -text [_ "Range and size"] -borderwidth 1
+    pack $mytoplevel.range -side top -fill x
+    frame $mytoplevel.range.x -padx 2 -pady 2
+    pack $mytoplevel.range.x -side top
+    label $mytoplevel.range.x.from_label -text [_ "X range, from"]
+    entry $mytoplevel.range.x.from_entry -width 6
+    label $mytoplevel.range.x.to_label -text [_ "to"]
+    entry $mytoplevel.range.x.to_entry -width 6
+    label $mytoplevel.range.x.size_label -text [_ "Size:"]
+    entry $mytoplevel.range.x.size_entry -width 4
+    label $mytoplevel.range.x.margin_label -text [_ "Margin:"]
+    entry $mytoplevel.range.x.margin_entry -width 4
+    pack $mytoplevel.range.x.from_label $mytoplevel.range.x.from_entry \
+        $mytoplevel.range.x.to_label $mytoplevel.range.x.to_entry \
+        $mytoplevel.range.x.size_label $mytoplevel.range.x.size_entry \
+        $mytoplevel.range.x.margin_label $mytoplevel.range.x.margin_entry \
+        -side left
+    frame $mytoplevel.range.y -padx 2 -pady 2
+    pack $mytoplevel.range.y -side top
+    label $mytoplevel.range.y.from_label -text [_ "Y range, from"]
+    entry $mytoplevel.range.y.from_entry -width 6
+    label $mytoplevel.range.y.to_label -text [_ "to"]
+    entry $mytoplevel.range.y.to_entry -width 6
+    label $mytoplevel.range.y.size_label -text [_ "Size:"]
+    entry $mytoplevel.range.y.size_entry -width 4
+    label $mytoplevel.range.y.margin_label -text [_ "Margin:"]
+    entry $mytoplevel.range.y.margin_entry -width 4
+    pack $mytoplevel.range.y.from_label $mytoplevel.range.y.from_entry \
+        $mytoplevel.range.y.to_label $mytoplevel.range.y.to_entry \
+        $mytoplevel.range.y.size_label $mytoplevel.range.y.size_entry \
+        $mytoplevel.range.y.margin_label $mytoplevel.range.y.margin_entry \
+        -side left
+
+    frame $mytoplevel.buttons
+    pack $mytoplevel.buttons -side bottom -fill x -pady 2m
+    button $mytoplevel.buttons.cancel -text [_ "Cancel"] \
+        -command "::dialog_canvas::cancel $mytoplevel"
+    button $mytoplevel.buttons.apply -text [_ "Apply"] \
+        -command "::dialog_canvas::apply $mytoplevel"
+    button $mytoplevel.buttons.ok -text [_ "OK"] \
+        -command "::dialog_canvas::ok $mytoplevel"
+    pack $mytoplevel.buttons.cancel $mytoplevel.buttons.apply \
+        $mytoplevel.buttons.ok -side left -expand 1
+ }
diff --git a/tcl/dialog_find.tcl b/tcl/dialog_find.tcl
new file mode 100644
index 000000000..c7a708ae5
--- /dev/null
+++ b/tcl/dialog_find.tcl
@@ -0,0 +1,117 @@
+
+package provide dialog_find 0.1
+
+package require pd_bindings
+
+namespace eval ::dialog_find:: {
+    # store the state of the "Match whole word only" check box
+    variable wholeword_button 0
+    # if the search hasn't changed, then the Find button sends "findagain"
+    variable previous_wholeword_button 0
+    variable previous_findstring ""
+
+    namespace export menu_dialog_find
+}
+
+# TODO make find panel as small as possible, being topmost means its findable
+# TODO (GNOME/Windows) find panel should retain focus after a find
+# TODO (Mac OS X) hide panel after success, but stay if the find was unsuccessful
+
+proc ::dialog_find::ok {mytoplevel} {
+    variable wholeword_button
+    variable previous_wholeword_button
+    variable previous_findstring
+    # find will be on top, so use the previous window that was on top
+    set search_window [lindex [wm stackorder .] end-1]
+    puts "search_window $search_window"
+    set findstring [.find.entry get]
+    if {$findstring eq ""} {return}
+    if {$search_window eq ".pdwindow"} {
+        set matches [.pdwindow.text search -all -nocase -- $findstring 0.0]
+        .pdwindow.text tag delete sel
+        foreach match $matches {
+            .pdwindow.text tag add sel $match "$match wordend"
+        }
+        .pdwindow.text see [lindex $matches 0]
+    } else {
+        if {$findstring eq $previous_findstring \
+                && $wholeword_button == $previous_wholeword_button} {
+            pdsend "$search_window findagain"
+        } else {
+            # TODO switch back to this for 0.43:
+            #pdsend "$search_window find $findstring $wholeword_button"
+            pdsend "$search_window find $findstring"
+            set previous_findstring $findstring
+            set previous_wholeword_button $wholeword_button
+        }
+    }
+}
+
+proc ::dialog_find::cancel {mytoplevel} {
+    wm withdraw .find
+}
+
+proc ::dialog_find::set_canvas_to_search {mytoplevel} {
+    # TODO rewrite using global $::focused_window
+    if {[winfo exists .find.frame.targetlabel]} {
+        set focusedtoplevel [winfo toplevel [lindex [wm stackorder .] end]]
+        if {$focusedtoplevel eq ".find"} {
+            set focusedtoplevel [winfo toplevel [lindex [wm stackorder .] end-1]]
+        }
+        if {$focusedtoplevel eq ".pdwindow"} {    
+            .find.frame.targetlabel configure -text [wm title .pdwindow]
+        } else {
+            foreach window $::menu_windowlist {
+                if {[lindex $window 1] eq $focusedtoplevel} {
+                    .find.frame.targetlabel configure -text [lindex $window 0]
+                }
+            }
+        }
+    }
+}
+
+# the find panel is opened from the menu and key bindings
+proc ::dialog_find::menu_find_dialog {mytoplevel} {
+    if {[winfo exists .find]} {
+        wm deiconify .find
+        raise .find
+    } else {
+        create_dialog $mytoplevel
+    }
+}
+
+proc ::dialog_find::create_dialog {mytoplevel} {
+    toplevel .find -class DialogWindow
+    wm title .find [_ "Find"]
+    wm geometry .find =475x125+150+150
+    .find configure
+    if {$::windowingsystem eq "aqua"} {$mytoplevel configure -menu .menubar}
+    ::pd_bindings::dialog_bindings .find "find"
+    
+    frame .find.frame
+    pack .find.frame -side top -fill x -pady 1
+    label .find.frame.searchin -text [_ "Search in"]
+    label .find.frame.targetlabel -font "TkTextFont 14" 
+    label .find.frame.for -text [_ "for:"]
+    pack .find.frame.searchin .find.frame.targetlabel .find.frame.for -side left
+    entry .find.entry -width 54 -font 18 -relief sunken \
+        -highlightthickness 3 -highlightcolor blue
+    focus .find.entry
+    pack .find.entry -side top -padx 10
+    
+    checkbutton .find.wholeword -variable ::dialog_find::wholeword_button \
+        -text [_ "Match whole word only"] -anchor w
+    pack .find.wholeword -side top -padx 30 -pady 3 -fill x
+    
+    frame .find.buttonframe -background yellow
+    button .find.button -text [_ "Find"] -default active -width 9 \
+        -command "::dialog_find::ok $mytoplevel"
+    if {$::windowingsystem eq "x11"} {
+        button .find.close -text [_ "Close"] -default normal -width 9 \
+            -command "::dialog_find::cancel $mytoplevel"
+        pack .find.buttonframe .find.button .find.close -side right -padx 10 -pady 3
+    } else {
+        pack .find.buttonframe .find.button -side right -padx 10 -pady 3
+    }
+    ::dialog_find::set_canvas_to_search $mytoplevel
+}
diff --git a/tcl/dialog_font.tcl b/tcl/dialog_font.tcl
new file mode 100644
index 000000000..578d155ea
--- /dev/null
+++ b/tcl/dialog_font.tcl
@@ -0,0 +1,133 @@
+
+package provide dialog_font 0.1
+
+namespace eval ::dialog_font:: {
+    variable fontsize 10
+    variable stretchval 100
+    variable whichstretch 1
+    variable canvaswindow
+    variable sizes {8 10 12 16 24 36}
+    variable gfxstub
+    
+    namespace export pdtk_canvas_dofont
+}
+
+# TODO this should use the pd_font_$size fonts created in pd-gui.tcl
+
+# TODO this should really be changed on the C side so that it doesn't have to
+# work around gfxstub/x_gui.c.  The gfxstub stuff assumes that there are
+# multiple panels, for properties panels like this, its much easier to use if
+# there is a single properties panel that adjusts based on which CanvasWindow
+# has focus
+
+proc ::dialog_font::apply {mytoplevel myfontsize} {
+    if {$mytoplevel eq ".pdwindow"} {
+        .pdwindow.text configure -font "-size $myfontsize"
+    } else {
+        variable stretchval
+        variable whichstretch
+        pdsend "$mytoplevel font $myfontsize $stretchval $whichstretch"
+    }
+}
+
+proc ::dialog_font::cancel {mygfxstub} {
+    if {$mygfxstub ne ".pdwindow"} {
+        pdsend "$mygfxstub cancel"
+    }
+    destroy .font
+}
+
+proc ::dialog_font::ok {mygfxstub} {
+    variable fontsize
+    ::dialog_font::apply $mygfxstub $fontsize
+    ::dialog_font::cancel $mygfxstub
+}
+
+proc ::dialog_font::update_font_dialog {mytoplevel} {
+    set ::dialog_font::canvaswindow $mytoplevel
+    if {$mytoplevel eq ".pdwindow"} {
+        set windowname [_ "Pd window"]
+    } else {
+        set windowname [lookup_windowname $mytoplevel]
+    }
+    if {[winfo exists .font]} {
+        wm title .font [format [_ "%s Font"] $windowname]
+    }
+}
+
+proc ::dialog_font::arrow_fontchange {change} {
+    variable sizes
+    set position [expr [lsearch $sizes $::dialog_font::fontsize] + $change]
+    if {$position < 0} {set position 0}
+    set max [llength $sizes]
+    if {$position >= $max} {set position [expr $max-1]}
+    set ::dialog_font::fontsize [lindex $sizes $position]
+    ::dialog_font::apply $::dialog_font::canvaswindow $::dialog_font::fontsize
+}
+
+# this should be called pdtk_font_dialog like the rest of the panels, but it
+# is called from the C side, so we'll leave it be
+proc ::dialog_font::pdtk_canvas_dofont {mygfxstub initsize} {
+    variable fontsize $initsize
+    variable whichstretch 1
+    variable stretchval 100
+    if {[winfo exists .font]} {
+        wm deiconify .font
+        raise .font
+        # the gfxstub stuff expects multiple font windows, we only have one,
+        # so kill the new gfxstub requests as the come in.  We'll save the
+        # original gfxstub for when the font panel gets closed
+        pdsend "$mygfxstub cancel"
+    } else {
+        create_dialog $mygfxstub
+    }
+}
+
+proc ::dialog_font::create_dialog {mygfxstub} {
+    variable gfxstub $mygfxstub
+    toplevel .font -class DialogWindow
+    if {$::windowingsystem eq "aqua"} {.font configure -menu .menubar}
+    ::pd_bindings::dialog_bindings .font "font"
+    # replace standard bindings to work around the gfxstub stuff
+    bind .font <KeyPress-Escape> "::dialog_font::cancel $mygfxstub"
+    bind .font <KeyPress-Return> "::dialog_font::ok $mygfxstub"
+    bind .font <$::pd_bindings::modifier-Key-w> "::dialog_font::cancel $mygfxstub"
+    bind .font <Up> "::dialog_font::arrow_fontchange -1"
+    bind .font <Down> "::dialog_font::arrow_fontchange 1"
+    
+    frame .font.buttonframe
+    pack .font.buttonframe -side bottom -fill x -pady 2m
+    button .font.buttonframe.ok -text [_ "OK"] \
+        -command "::dialog_font::ok $mygfxstub"
+    pack .font.buttonframe.ok -side left -expand 1
+    
+    labelframe .font.fontsize -text [_ "Font Size"] -padx 5 -pady 4 -borderwidth 1 \
+        -width [::msgcat::mcmax "Font Size"] -labelanchor n
+    pack .font.fontsize -side left -padx 5
+    
+    # this is whacky Tcl at its finest, but I couldn't resist...
+    foreach size $::dialog_font::sizes {
+        radiobutton .font.fontsize.radio$size -value $size -text $size \
+            -variable ::dialog_font::fontsize \
+            -command [format {::dialog_font::apply $::dialog_font::canvaswindow %s} $size]
+        pack .font.fontsize.radio$size -side top -anchor w
+    }
+
+    labelframe .font.stretch -text [_ "Stretch"] -padx 5 -pady 5 -borderwidth 1 \
+        -width [::msgcat::mcmax "Stretch"] -labelanchor n
+    pack .font.stretch -side left -padx 5 -fill y
+
+    entry .font.stretch.entry -textvariable ::dialog_font::stretchval -width 5
+    pack .font.stretch.entry -side top -pady 5
+
+    radiobutton .font.stretch.radio1 -text [_ "X and Y"] \
+        -value 1 -variable ::dialog_font::whichstretch
+    radiobutton .font.stretch.radio2 -text [_ "X only"] \
+        -value 2 -variable ::dialog_font::whichstretch
+    radiobutton .font.stretch.radio3 -text [_ "Y only"] \
+        -value 3 -variable ::dialog_font::whichstretch
+
+    pack .font.stretch.radio1 -side top -anchor w
+    pack .font.stretch.radio2 -side top -anchor w
+    pack .font.stretch.radio3 -side top -anchor w
+}
diff --git a/tcl/dialog_gatom.tcl b/tcl/dialog_gatom.tcl
new file mode 100644
index 000000000..b59751bfb
--- /dev/null
+++ b/tcl/dialog_gatom.tcl
@@ -0,0 +1,166 @@
+
+package provide dialog_gatom 0.1
+
+package require wheredoesthisgo
+
+namespace eval ::dialog_gatom:: {
+    namespace export pdtk_gatom_dialog
+}
+
+# array for communicating the position of the radiobuttons (Tk's
+# radiobutton widget requires this to be global)
+array set gatomlabel_radio {}
+
+############ pdtk_gatom_dialog -- run a gatom dialog #########
+
+proc ::dialog_gatom::escape {sym} {
+    if {[string length $sym] == 0} {
+        set ret "-"
+    } else {
+        if {[string equal -length 1 $sym "-"]} {
+            set ret [string replace $sym 0 0 "--"]
+        } else {
+            set ret [string map {"$" "#"} $sym]
+        }
+    }
+    return [unspace_text $ret]
+}
+
+proc ::dialog_gatom::unescape {sym} {
+    if {[string equal -length 1 $sym "-"]} {
+        set ret [string replace $sym 0 0 ""]
+    } else {
+        set ret [string map {"#" "$"} $sym]
+    }
+    return $ret
+}
+
+proc ::dialog_gatom::apply {mytoplevel} {
+    global gatomlabel_radio
+    
+    pdsend "$mytoplevel param \
+                 [$mytoplevel.width.entry get] \
+                 [$mytoplevel.limits.lower.entry get] \
+                 [$mytoplevel.limits.upper.entry get] \
+                 [::dialog_gatom::escape [$mytoplevel.gatomlabel.name.entry get]] \
+                 $gatomlabel_radio($mytoplevel) \
+                 [::dialog_gatom::escape [$mytoplevel.s_r.send.entry get]] \
+                 [::dialog_gatom::escape [$mytoplevel.s_r.receive.entry get]]"
+}
+
+proc ::dialog_gatom::cancel {mytoplevel} {
+    pdsend "$mytoplevel cancel"
+}
+
+proc ::dialog_gatom::ok {mytoplevel} {
+    ::dialog_gatom::apply $mytoplevel
+    ::dialog_gatom::cancel $mytoplevel
+}
+
+# set up the panel with the info from pd
+proc ::dialog_gatom::pdtk_gatom_dialog {mytoplevel initwidth initlower initupper \
+                                     initgatomlabel_radio \
+                                     initgatomlabel initsend initreceive} {
+    global gatomlabel_radio
+    set gatomlabel_radio($mytoplevel) $initgatomlabel_radio
+
+    if {[winfo exists $mytoplevel]} {
+        wm deiconify $mytoplevel
+        raise $mytoplevel
+    } else {
+        create_dialog $mytoplevel
+    }
+
+    $mytoplevel.width.entry insert 0 $initwidth
+    $mytoplevel.limits.lower.entry insert 0 $initlower
+    $mytoplevel.limits.upper.entry insert 0 $initupper
+    if {$initgatomlabel ne "-"} {
+        $mytoplevel.gatomlabel.name.entry insert 0 $initgatomlabel
+    }
+    set gatomlabel_radio($mytoplevel) $initgatomlabel_radio
+        if {$initsend ne "-"} {
+        $mytoplevel.s_r.send.entry insert 0 $initsend
+    }
+    if {$initreceive ne "-"} {
+        $mytoplevel.s_r.receive.entry insert 0 $initreceive
+    }
+}
+
+proc ::dialog_gatom::create_dialog {mytoplevel} {
+    global gatomlabel_radio
+
+    toplevel $mytoplevel -class DialogWindow
+    wm title $mytoplevel [_ "Atom Box Properties"]
+    if {$::windowingsystem eq "aqua"} {$mytoplevel configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $mytoplevel "gatom"
+
+    frame $mytoplevel.width -height 7
+    pack $mytoplevel.width -side top
+    label $mytoplevel.width.label -text [_ "Width:"]
+    entry $mytoplevel.width.entry -width 4
+    pack $mytoplevel.width.label $mytoplevel.width.entry -side left
+
+    labelframe $mytoplevel.limits -text [_ "Limits"] -padx 15 -pady 4 -borderwidth 1
+    pack $mytoplevel.limits -side top -fill x
+    frame $mytoplevel.limits.lower
+    pack $mytoplevel.limits.lower -side left
+    label $mytoplevel.limits.lower.label -text [_ "Lower:"]
+    entry $mytoplevel.limits.lower.entry -width 7
+    pack $mytoplevel.limits.lower.label $mytoplevel.limits.lower.entry -side left
+    frame $mytoplevel.limits.upper
+    pack $mytoplevel.limits.upper -side left
+    label $mytoplevel.limits.upper.label -text [_ "Upper:"]
+    entry $mytoplevel.limits.upper.entry -width 7
+    pack $mytoplevel.limits.upper.label $mytoplevel.limits.upper.entry -side left
+
+    labelframe $mytoplevel.gatomlabel -text [_ "Label"] -padx 5 -pady 5 -borderwidth 1
+    pack $mytoplevel.gatomlabel -side top -fill x -pady 5
+    frame $mytoplevel.gatomlabel.name
+    pack $mytoplevel.gatomlabel.name -side top
+    entry $mytoplevel.gatomlabel.name.entry -width 33
+    pack $mytoplevel.gatomlabel.name.entry -side left
+    frame $mytoplevel.gatomlabel.radio
+    pack $mytoplevel.gatomlabel.radio -side top
+    radiobutton $mytoplevel.gatomlabel.radio.left -value 0 -text [_ "Left   "] \
+        -variable gatomlabel_radio($mytoplevel) -justify left -takefocus 0
+    radiobutton $mytoplevel.gatomlabel.radio.right -value 1 -text [_ "Right"] \
+        -variable gatomlabel_radio($mytoplevel) -justify left -takefocus 0
+    radiobutton $mytoplevel.gatomlabel.radio.top -value 2 -text [_ "Top"] \
+        -variable gatomlabel_radio($mytoplevel) -justify left -takefocus 0
+    radiobutton $mytoplevel.gatomlabel.radio.bottom -value 3 -text [_ "Bottom"] \
+        -variable gatomlabel_radio($mytoplevel) -justify left -takefocus 0
+    pack $mytoplevel.gatomlabel.radio.left -side left -anchor w
+    pack $mytoplevel.gatomlabel.radio.right -side right -anchor w
+    pack $mytoplevel.gatomlabel.radio.top -side top -anchor w
+    pack $mytoplevel.gatomlabel.radio.bottom -side bottom -anchor w
+
+    labelframe $mytoplevel.s_r -text [_ "Messages"] -padx 5 -pady 5 -borderwidth 1
+    pack $mytoplevel.s_r -side top -fill x
+    frame $mytoplevel.s_r.send
+    pack $mytoplevel.s_r.send -side top -anchor e
+    label $mytoplevel.s_r.send.label -text [_ "Send symbol:"]
+    entry $mytoplevel.s_r.send.entry -width 21
+    pack $mytoplevel.s_r.send.entry $mytoplevel.s_r.send.label -side right
+
+    frame $mytoplevel.s_r.receive
+    pack $mytoplevel.s_r.receive -side top -anchor e
+    label $mytoplevel.s_r.receive.label -text [_ "Receive symbol:"]
+    entry $mytoplevel.s_r.receive.entry -width 21
+    pack $mytoplevel.s_r.receive.entry $mytoplevel.s_r.receive.label -side right
+    
+    frame $mytoplevel.buttonframe -pady 5
+    pack $mytoplevel.buttonframe -side top -fill x -pady 2m
+    button $mytoplevel.buttonframe.cancel -text [_ "Cancel"] \
+        -command "::dialog_gatom::cancel $mytoplevel"
+    pack $mytoplevel.buttonframe.cancel -side left -expand 1
+    button $mytoplevel.buttonframe.apply -text [_ "Apply"] \
+        -command "::dialog_gatom::apply $mytoplevel"
+    pack $mytoplevel.buttonframe.apply -side left -expand 1
+    button $mytoplevel.buttonframe.ok -text [_ "OK"] \
+        -command "::dialog_gatom::ok $mytoplevel"
+    pack $mytoplevel.buttonframe.ok -side left -expand 1
+
+    $mytoplevel.width.entry select from 0
+    $mytoplevel.width.entry select adjust end
+    focus $mytoplevel.width.entry
+}
diff --git a/tcl/dialog_iemgui.tcl b/tcl/dialog_iemgui.tcl
new file mode 100644
index 000000000..34ed4ccb4
--- /dev/null
+++ b/tcl/dialog_iemgui.tcl
@@ -0,0 +1,772 @@
+# For information on usage and redistribution, and for a DISCLAIMER OF ALL
+# WARRANTIES, see the file, "LICENSE.txt," in this distribution.
+# Copyright (c) 1997-2009 Miller Puckette.
+
+package provide dialog_iemgui 0.1
+
+namespace eval ::dialog_iemgui:: {
+    variable define_min_flashhold 50
+    variable define_min_flashbreak 10
+    variable define_min_fontsize 4
+    
+    namespace export pdtk_iemgui_dialog
+}
+
+# TODO convert Init/No Init and Steady on click/Jump on click to checkbuttons
+
+proc ::dialog_iemgui::clip_dim {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_wdt [concat iemgui_wdt_$vid]
+    global $var_iemgui_wdt
+    set var_iemgui_min_wdt [concat iemgui_min_wdt_$vid]
+    global $var_iemgui_min_wdt
+    set var_iemgui_hgt [concat iemgui_hgt_$vid]
+    global $var_iemgui_hgt
+    set var_iemgui_min_hgt [concat iemgui_min_hgt_$vid]
+    global $var_iemgui_min_hgt
+    
+    if {[eval concat $$var_iemgui_wdt] < [eval concat $$var_iemgui_min_wdt]} {
+        set $var_iemgui_wdt [eval concat $$var_iemgui_min_wdt]
+        $mytoplevel.dim.w_ent configure -textvariable $var_iemgui_wdt
+    }
+    if {[eval concat $$var_iemgui_hgt] < [eval concat $$var_iemgui_min_hgt]} {
+        set $var_iemgui_hgt [eval concat $$var_iemgui_min_hgt]
+        $mytoplevel.dim.h_ent configure -textvariable $var_iemgui_hgt
+    }
+}
+
+proc ::dialog_iemgui::clip_num {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_num [concat iemgui_num_$vid]
+    global $var_iemgui_num
+    
+    if {[eval concat $$var_iemgui_num] > 2000} {
+        set $var_iemgui_num 2000
+        $mytoplevel.para.num_ent configure -textvariable $var_iemgui_num
+    }
+    if {[eval concat $$var_iemgui_num] < 1} {
+        set $var_iemgui_num 1
+        $mytoplevel.para.num_ent configure -textvariable $var_iemgui_num
+    }
+}
+
+proc ::dialog_iemgui::sched_rng {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_min_rng [concat iemgui_min_rng_$vid]
+    global $var_iemgui_min_rng
+    set var_iemgui_max_rng [concat iemgui_max_rng_$vid]
+    global $var_iemgui_max_rng
+    set var_iemgui_rng_sch [concat iemgui_rng_sch_$vid]
+    global $var_iemgui_rng_sch
+    
+    variable define_min_flashhold
+    variable define_min_flashbreak
+    
+    if {[eval concat $$var_iemgui_rng_sch] == 2} {
+        if {[eval concat $$var_iemgui_max_rng] < [eval concat $$var_iemgui_min_rng]} {
+            set hhh [eval concat $$var_iemgui_min_rng]
+            set $var_iemgui_min_rng [eval concat $$var_iemgui_max_rng]
+            set $var_iemgui_max_rng $hhh
+            $mytoplevel.rng.max_ent configure -textvariable $var_iemgui_max_rng
+            $mytoplevel.rng.min_ent configure -textvariable $var_iemgui_min_rng }
+        if {[eval concat $$var_iemgui_max_rng] < $define_min_flashhold} {
+            set $var_iemgui_max_rng $iemgui_define_min_flashhold
+            $mytoplevel.rng.max_ent configure -textvariable $var_iemgui_max_rng
+        }
+        if {[eval concat $$var_iemgui_min_rng] < $define_min_flashbreak} {
+            set $var_iemgui_min_rng $define_min_flashbreak
+            $mytoplevel.rng.min_ent configure -textvariable $var_iemgui_min_rng
+        }
+    }
+    if {[eval concat $$var_iemgui_rng_sch] == 1} {
+        if {[eval concat $$var_iemgui_min_rng] == 0.0} {
+            set $var_iemgui_min_rng 1.0
+            $mytoplevel.rng.min_ent configure -textvariable $var_iemgui_min_rng
+        }
+    }
+}
+
+proc ::dialog_iemgui::verify_rng {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_min_rng [concat iemgui_min_rng_$vid]
+    global $var_iemgui_min_rng
+    set var_iemgui_max_rng [concat iemgui_max_rng_$vid]
+    global $var_iemgui_max_rng
+    set var_iemgui_lin0_log1 [concat iemgui_lin0_log1_$vid]
+    global $var_iemgui_lin0_log1
+    
+    if {[eval concat $$var_iemgui_lin0_log1] == 1} {
+        if {[eval concat $$var_iemgui_max_rng] == 0.0 && [eval concat $$var_iemgui_min_rng] == 0.0} {
+            set $var_iemgui_max_rng 1.0
+            $mytoplevel.rng.max_ent configure -textvariable $var_iemgui_max_rng
+        }
+        if {[eval concat $$var_iemgui_max_rng] > 0} {
+            if {[eval concat $$var_iemgui_min_rng] <= 0} {
+                set $var_iemgui_min_rng [expr [eval concat $$var_iemgui_max_rng] * 0.01]
+                $mytoplevel.rng.min_ent configure -textvariable $var_iemgui_min_rng
+            }
+        } else {
+            if {[eval concat $$var_iemgui_min_rng] > 0} {
+                set $var_iemgui_max_rng [expr [eval concat $$var_iemgui_min_rng] * 0.01]
+                $mytoplevel.rng.max_ent configure -textvariable $var_iemgui_max_rng
+            }
+        }
+    }
+}
+
+proc ::dialog_iemgui::clip_fontsize {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_gn_fs [concat iemgui_gn_fs_$vid]
+    global $var_iemgui_gn_fs
+    
+    variable define_min_fontsize
+    
+    if {[eval concat $$var_iemgui_gn_fs] < $define_min_fontsize} {
+        set $var_iemgui_gn_fs $define_min_fontsize
+        $mytoplevel.label.fs_ent configure -textvariable $var_iemgui_gn_fs
+    }
+}
+
+proc ::dialog_iemgui::set_col_example {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_bcol [concat iemgui_bcol_$vid]
+    global $var_iemgui_bcol
+    set var_iemgui_fcol [concat iemgui_fcol_$vid]
+    global $var_iemgui_fcol
+    set var_iemgui_lcol [concat iemgui_lcol_$vid]
+    global $var_iemgui_lcol
+    
+    $mytoplevel.colors.sections.lb_bk configure \
+        -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+        -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+        -foreground [format "#%6.6x" [eval concat $$var_iemgui_lcol]] \
+        -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_lcol]]
+    
+    if { [eval concat $$var_iemgui_fcol] >= 0 } {
+        $mytoplevel.colors.sections.fr_bk configure \
+            -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -foreground [format "#%6.6x" [eval concat $$var_iemgui_fcol]] \
+            -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_fcol]]
+    } else {
+        $mytoplevel.colors.sections.fr_bk configure \
+            -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -foreground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_bcol]]}
+}
+
+proc ::dialog_iemgui::preset_col {mytoplevel presetcol} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_l2_f1_b0 [concat iemgui_l2_f1_b0_$vid]
+    global $var_iemgui_l2_f1_b0
+    set var_iemgui_bcol [concat iemgui_bcol_$vid]
+    global $var_iemgui_bcol
+    set var_iemgui_fcol [concat iemgui_fcol_$vid]
+    global $var_iemgui_fcol
+    set var_iemgui_lcol [concat iemgui_lcol_$vid]
+    global $var_iemgui_lcol
+    
+    if { [eval concat $$var_iemgui_l2_f1_b0] == 0 } { set $var_iemgui_bcol $presetcol }
+    if { [eval concat $$var_iemgui_l2_f1_b0] == 1 } { set $var_iemgui_fcol $presetcol }
+    if { [eval concat $$var_iemgui_l2_f1_b0] == 2 } { set $var_iemgui_lcol $presetcol }
+    ::dialog_iemgui::set_col_example $mytoplevel
+}
+
+proc ::dialog_iemgui::choose_col_bkfrlb {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_l2_f1_b0 [concat iemgui_l2_f1_b0_$vid]
+    global $var_iemgui_l2_f1_b0
+    set var_iemgui_bcol [concat iemgui_bcol_$vid]
+    global $var_iemgui_bcol
+    set var_iemgui_fcol [concat iemgui_fcol_$vid]
+    global $var_iemgui_fcol
+    set var_iemgui_lcol [concat iemgui_lcol_$vid]
+    global $var_iemgui_lcol
+    
+    if {[eval concat $$var_iemgui_l2_f1_b0] == 0} {
+        set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFCFCFC]
+        set helpstring [tk_chooseColor -title [_ "Background color"] -initialcolor [format "#%6.6x" [eval concat $$var_iemgui_bcol]]]
+        if { $helpstring ne "" } {
+            set $var_iemgui_bcol [string replace $helpstring 0 0 "0x"]
+            set $var_iemgui_bcol [expr [eval concat $$var_iemgui_bcol] & 0xFCFCFC] }
+    }
+    if {[eval concat $$var_iemgui_l2_f1_b0] == 1} {
+        set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFCFCFC]
+        set helpstring [tk_chooseColor -title [_ "Foreground color"] -initialcolor [format "#%6.6x" [eval concat $$var_iemgui_fcol]]]
+        if { $helpstring ne "" } {
+            set $var_iemgui_fcol [string replace $helpstring 0 0 "0x"]
+            set $var_iemgui_fcol [expr [eval concat $$var_iemgui_fcol] & 0xFCFCFC] }
+    }
+    if {[eval concat $$var_iemgui_l2_f1_b0] == 2} {
+        set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFCFCFC]
+        set helpstring [tk_chooseColor -title [_ "Label color"] -initialcolor [format "#%6.6x" [eval concat $$var_iemgui_lcol]]]
+        if { $helpstring ne "" } {
+            set $var_iemgui_lcol [string replace $helpstring 0 0 "0x"]
+            set $var_iemgui_lcol [expr [eval concat $$var_iemgui_lcol] & 0xFCFCFC] }
+    }
+    ::dialog_iemgui::set_col_example $mytoplevel
+}
+
+proc ::dialog_iemgui::lilo {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_lin0_log1 [concat iemgui_lin0_log1_$vid]
+    global $var_iemgui_lin0_log1
+    set var_iemgui_lilo0 [concat iemgui_lilo0_$vid]
+    global $var_iemgui_lilo0
+    set var_iemgui_lilo1 [concat iemgui_lilo1_$vid]
+    global $var_iemgui_lilo1
+    
+    ::dialog_iemgui::sched_rng $mytoplevel
+    
+    if {[eval concat $$var_iemgui_lin0_log1] == 0} {
+        set $var_iemgui_lin0_log1 1
+        $mytoplevel.para.lilo configure -text [eval concat $$var_iemgui_lilo1]
+        ::dialog_iemgui::verify_rng $mytoplevel
+        ::dialog_iemgui::sched_rng $mytoplevel
+    } else {
+        set $var_iemgui_lin0_log1 0
+        $mytoplevel.para.lilo configure -text [eval concat $$var_iemgui_lilo0]
+    }
+}
+
+proc ::dialog_iemgui::toggle_font {mytoplevel gn_f} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_gn_f [concat iemgui_gn_f_$vid]
+    global $var_iemgui_gn_f
+    
+    set $var_iemgui_gn_f $gn_f
+    
+    switch -- $gn_f {
+        0 { set current_font $::font_family}
+        1 { set current_font "Helvetica" }
+        2 { set current_font "Times" }
+    }
+    set current_font_spec "{$current_font} 12 $::font_weight"
+    
+    $mytoplevel.label.fontpopup_label configure -text $current_font \
+        -font $current_font_spec
+    $mytoplevel.label.name_entry configure -font $current_font_spec
+    $mytoplevel.colors.sections.fr_bk configure -font $current_font_spec
+    $mytoplevel.colors.sections.lb_bk configure -font $current_font_spec
+}
+
+proc ::dialog_iemgui::lb {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_loadbang [concat iemgui_loadbang_$vid]
+    global $var_iemgui_loadbang
+    
+    if {[eval concat $$var_iemgui_loadbang] == 0} {
+        set $var_iemgui_loadbang 1
+        $mytoplevel.para.lb configure -text [_ "Init"]
+    } else {
+        set $var_iemgui_loadbang 0
+        $mytoplevel.para.lb configure -text [_ "No init"]
+    }
+}
+
+proc ::dialog_iemgui::stdy_jmp {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_steady [concat iemgui_steady_$vid]
+    global $var_iemgui_steady
+    
+    if {[eval concat $$var_iemgui_steady]} {
+        set $var_iemgui_steady 0
+        $mytoplevel.para.stdy_jmp configure -text [_ "Jump on click"]
+    } else {
+        set $var_iemgui_steady 1
+        $mytoplevel.para.stdy_jmp configure -text [_ "Steady on click"]
+    }
+}
+
+proc ::dialog_iemgui::apply {mytoplevel} {
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_wdt [concat iemgui_wdt_$vid]
+    global $var_iemgui_wdt
+    set var_iemgui_min_wdt [concat iemgui_min_wdt_$vid]
+    global $var_iemgui_min_wdt
+    set var_iemgui_hgt [concat iemgui_hgt_$vid]
+    global $var_iemgui_hgt
+    set var_iemgui_min_hgt [concat iemgui_min_hgt_$vid]
+    global $var_iemgui_min_hgt
+    set var_iemgui_min_rng [concat iemgui_min_rng_$vid]
+    global $var_iemgui_min_rng
+    set var_iemgui_max_rng [concat iemgui_max_rng_$vid]
+    global $var_iemgui_max_rng
+    set var_iemgui_lin0_log1 [concat iemgui_lin0_log1_$vid]
+    global $var_iemgui_lin0_log1
+    set var_iemgui_lilo0 [concat iemgui_lilo0_$vid]
+    global $var_iemgui_lilo0
+    set var_iemgui_lilo1 [concat iemgui_lilo1_$vid]
+    global $var_iemgui_lilo1
+    set var_iemgui_loadbang [concat iemgui_loadbang_$vid]
+    global $var_iemgui_loadbang
+    set var_iemgui_num [concat iemgui_num_$vid]
+    global $var_iemgui_num
+    set var_iemgui_steady [concat iemgui_steady_$vid]
+    global $var_iemgui_steady
+    set var_iemgui_snd [concat iemgui_snd_$vid]
+    global $var_iemgui_snd
+    set var_iemgui_rcv [concat iemgui_rcv_$vid]
+    global $var_iemgui_rcv
+    set var_iemgui_gui_nam [concat iemgui_gui_nam_$vid]
+    global $var_iemgui_gui_nam
+    set var_iemgui_gn_dx [concat iemgui_gn_dx_$vid]
+    global $var_iemgui_gn_dx
+    set var_iemgui_gn_dy [concat iemgui_gn_dy_$vid]
+    global $var_iemgui_gn_dy
+    set var_iemgui_gn_f [concat iemgui_gn_f_$vid]
+    global $var_iemgui_gn_f
+    set var_iemgui_gn_fs [concat iemgui_gn_fs_$vid]
+    global $var_iemgui_gn_fs
+    set var_iemgui_bcol [concat iemgui_bcol_$vid]
+    global $var_iemgui_bcol
+    set var_iemgui_fcol [concat iemgui_fcol_$vid]
+    global $var_iemgui_fcol
+    set var_iemgui_lcol [concat iemgui_lcol_$vid]
+    global $var_iemgui_lcol
+    
+    ::dialog_iemgui::clip_dim $mytoplevel
+    ::dialog_iemgui::clip_num $mytoplevel
+    ::dialog_iemgui::sched_rng $mytoplevel
+    ::dialog_iemgui::verify_rng $mytoplevel
+    ::dialog_iemgui::sched_rng $mytoplevel
+    ::dialog_iemgui::clip_fontsize $mytoplevel
+    
+    if {[eval concat $$var_iemgui_snd] == ""} {set hhhsnd "empty"} else {set hhhsnd [eval concat $$var_iemgui_snd]}
+    if {[eval concat $$var_iemgui_rcv] == ""} {set hhhrcv "empty"} else {set hhhrcv [eval concat $$var_iemgui_rcv]}
+    if {[eval concat $$var_iemgui_gui_nam] == ""} {set hhhgui_nam "empty"
+    } else {
+        set hhhgui_nam [eval concat $$var_iemgui_gui_nam]}
+    
+    if {[string index $hhhsnd 0] == "$"} {
+        set hhhsnd [string replace $hhhsnd 0 0 #] }
+    if {[string index $hhhrcv 0] == "$"} {
+        set hhhrcv [string replace $hhhrcv 0 0 #] }
+    if {[string index $hhhgui_nam 0] == "$"} {
+        set hhhgui_nam [string replace $hhhgui_nam 0 0 #] }
+    
+    set hhhsnd [unspace_text $hhhsnd]
+    set hhhrcv [unspace_text $hhhrcv]
+    set hhhgui_nam [unspace_text $hhhgui_nam]
+    
+    pdsend [concat $mytoplevel dialog \
+            [eval concat $$var_iemgui_wdt] \
+            [eval concat $$var_iemgui_hgt] \
+            [eval concat $$var_iemgui_min_rng] \
+            [eval concat $$var_iemgui_max_rng] \
+            [eval concat $$var_iemgui_lin0_log1] \
+            [eval concat $$var_iemgui_loadbang] \
+            [eval concat $$var_iemgui_num] \
+            $hhhsnd \
+            $hhhrcv \
+            $hhhgui_nam \
+            [eval concat $$var_iemgui_gn_dx] \
+            [eval concat $$var_iemgui_gn_dy] \
+            [eval concat $$var_iemgui_gn_f] \
+            [eval concat $$var_iemgui_gn_fs] \
+            [eval concat $$var_iemgui_bcol] \
+            [eval concat $$var_iemgui_fcol] \
+            [eval concat $$var_iemgui_lcol] \
+            [eval concat $$var_iemgui_steady]]
+}
+
+
+proc ::dialog_iemgui::cancel {mytoplevel} {
+    pdsend "$mytoplevel cancel"
+}
+
+proc ::dialog_iemgui::ok {mytoplevel} {
+    ::dialog_iemgui::apply $mytoplevel
+    ::dialog_iemgui::cancel $mytoplevel
+}
+
+proc ::dialog_iemgui::pdtk_iemgui_dialog {mytoplevel mainheader dim_header \
+                                       wdt min_wdt wdt_label \
+                                       hgt min_hgt hgt_label \
+                                       rng_header min_rng min_rng_label max_rng \
+                                       max_rng_label rng_sched \
+                                       lin0_log1 lilo0_label lilo1_label \
+                                       loadbang steady num_label num \
+                                       snd rcv \
+                                       gui_name \
+                                       gn_dx gn_dy gn_f gn_fs \
+                                       bcol fcol lcol} {
+    
+    set vid [string trimleft $mytoplevel .]
+    
+    set var_iemgui_wdt [concat iemgui_wdt_$vid]
+    global $var_iemgui_wdt
+    set var_iemgui_min_wdt [concat iemgui_min_wdt_$vid]
+    global $var_iemgui_min_wdt
+    set var_iemgui_hgt [concat iemgui_hgt_$vid]
+    global $var_iemgui_hgt
+    set var_iemgui_min_hgt [concat iemgui_min_hgt_$vid]
+    global $var_iemgui_min_hgt
+    set var_iemgui_min_rng [concat iemgui_min_rng_$vid]
+    global $var_iemgui_min_rng
+    set var_iemgui_max_rng [concat iemgui_max_rng_$vid]
+    global $var_iemgui_max_rng
+    set var_iemgui_rng_sch [concat iemgui_rng_sch_$vid]
+    global $var_iemgui_rng_sch
+    set var_iemgui_lin0_log1 [concat iemgui_lin0_log1_$vid]
+    global $var_iemgui_lin0_log1
+    set var_iemgui_lilo0 [concat iemgui_lilo0_$vid]
+    global $var_iemgui_lilo0
+    set var_iemgui_lilo1 [concat iemgui_lilo1_$vid]
+    global $var_iemgui_lilo1
+    set var_iemgui_loadbang [concat iemgui_loadbang_$vid]
+    global $var_iemgui_loadbang
+    set var_iemgui_num [concat iemgui_num_$vid]
+    global $var_iemgui_num
+    set var_iemgui_steady [concat iemgui_steady_$vid]
+    global $var_iemgui_steady
+    set var_iemgui_snd [concat iemgui_snd_$vid]
+    global $var_iemgui_snd
+    set var_iemgui_rcv [concat iemgui_rcv_$vid]
+    global $var_iemgui_rcv
+    set var_iemgui_gui_nam [concat iemgui_gui_nam_$vid]
+    global $var_iemgui_gui_nam
+    set var_iemgui_gn_dx [concat iemgui_gn_dx_$vid]
+    global $var_iemgui_gn_dx
+    set var_iemgui_gn_dy [concat iemgui_gn_dy_$vid]
+    global $var_iemgui_gn_dy
+    set var_iemgui_gn_f [concat iemgui_gn_f_$vid]
+    global $var_iemgui_gn_f
+    set var_iemgui_gn_fs [concat iemgui_gn_fs_$vid]
+    global $var_iemgui_gn_fs
+    set var_iemgui_l2_f1_b0 [concat iemgui_l2_f1_b0_$vid]
+    global $var_iemgui_l2_f1_b0
+    set var_iemgui_bcol [concat iemgui_bcol_$vid]
+    global $var_iemgui_bcol
+    set var_iemgui_fcol [concat iemgui_fcol_$vid]
+    global $var_iemgui_fcol
+    set var_iemgui_lcol [concat iemgui_lcol_$vid]
+    global $var_iemgui_lcol
+    
+    set $var_iemgui_wdt $wdt
+    set $var_iemgui_min_wdt $min_wdt
+    set $var_iemgui_hgt $hgt
+    set $var_iemgui_min_hgt $min_hgt
+    set $var_iemgui_min_rng $min_rng
+    set $var_iemgui_max_rng $max_rng
+    set $var_iemgui_rng_sch $rng_sched
+    set $var_iemgui_lin0_log1 $lin0_log1
+    set $var_iemgui_lilo0 $lilo0_label
+    set $var_iemgui_lilo1 $lilo1_label
+    set $var_iemgui_loadbang $loadbang
+    set $var_iemgui_num $num
+    set $var_iemgui_steady $steady
+    if {$snd == "empty"} {set $var_iemgui_snd [format ""]
+    } else {set $var_iemgui_snd [format "%s" $snd]}
+    if {$rcv == "empty"} {set $var_iemgui_rcv [format ""]
+    } else {set $var_iemgui_rcv [format "%s" $rcv]}
+    if {$gui_name == "empty"} {set $var_iemgui_gui_nam [format ""]
+    } else {set $var_iemgui_gui_nam [format "%s" $gui_name]}
+    
+    if {[string index [eval concat $$var_iemgui_snd] 0] == "#"} {
+        set $var_iemgui_snd [string replace [eval concat $$var_iemgui_snd] 0 0 $] }
+    if {[string index [eval concat $$var_iemgui_rcv] 0] == "#"} {
+        set $var_iemgui_rcv [string replace [eval concat $$var_iemgui_rcv] 0 0 $] }
+    if {[string index [eval concat $$var_iemgui_gui_nam] 0] == "#"} {
+        set $var_iemgui_gui_nam [string replace [eval concat $$var_iemgui_gui_nam] 0 0 $] }
+    set $var_iemgui_gn_dx $gn_dx
+    set $var_iemgui_gn_dy $gn_dy
+    set $var_iemgui_gn_f $gn_f
+    set $var_iemgui_gn_fs $gn_fs
+    
+    set $var_iemgui_bcol $bcol
+    set $var_iemgui_fcol $fcol
+    set $var_iemgui_lcol $lcol
+    
+    set $var_iemgui_l2_f1_b0 0
+    
+    toplevel $mytoplevel -class DialogWindow
+    wm title $mytoplevel [format [_ "%s Properties"] $mainheader]
+    if {$::windowingsystem eq "aqua"} {$mytoplevel configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $mytoplevel "iemgui"
+
+    frame $mytoplevel.dim
+    pack $mytoplevel.dim -side top
+    label $mytoplevel.dim.head -text $dim_header
+    label $mytoplevel.dim.w_lab -text [_ $wdt_label] -width 6
+    entry $mytoplevel.dim.w_ent -textvariable $var_iemgui_wdt -width 5
+    label $mytoplevel.dim.dummy1 -text " " -width 10
+    label $mytoplevel.dim.h_lab -text [_ $hgt_label] -width 6
+    entry $mytoplevel.dim.h_ent -textvariable $var_iemgui_hgt -width 5
+    pack $mytoplevel.dim.head -side top
+    pack $mytoplevel.dim.w_lab $mytoplevel.dim.w_ent $mytoplevel.dim.dummy1 -side left
+    if { $hgt_label ne "empty" } {
+        pack $mytoplevel.dim.h_lab $mytoplevel.dim.h_ent -side left}
+    
+    frame $mytoplevel.rng
+    pack $mytoplevel.rng -side top
+    label $mytoplevel.rng.head -text $rng_header
+    label $mytoplevel.rng.min_lab -text [_ $min_rng_label] -width 6
+    entry $mytoplevel.rng.min_ent -textvariable $var_iemgui_min_rng -width 9
+    label $mytoplevel.rng.dummy1 -text " " -width 1
+    label $mytoplevel.rng.max_lab -text [_ $max_rng_label] -width 8
+    entry $mytoplevel.rng.max_ent -textvariable $var_iemgui_max_rng -width 9
+    if { $rng_header ne "empty" } {
+        pack $mytoplevel.rng.head -side top
+        if { $min_rng_label ne "empty" } {
+            pack $mytoplevel.rng.min_lab $mytoplevel.rng.min_ent -side left}
+        if { $max_rng_label ne "empty" } {
+            pack $mytoplevel.rng.dummy1 \
+                $mytoplevel.rng.max_lab $mytoplevel.rng.max_ent -side left} }
+    
+    if { [eval concat $$var_iemgui_lin0_log1] >= 0 || [eval concat $$var_iemgui_loadbang] >= 0 || [eval concat $$var_iemgui_num] > 0 || [eval concat $$var_iemgui_steady] >= 0 } {
+        label $mytoplevel.space1 -text ""
+        pack $mytoplevel.space1 -side top }
+    
+    frame $mytoplevel.para
+    pack $mytoplevel.para -side top
+    label $mytoplevel.para.dummy2 -text "" -width 1
+    label $mytoplevel.para.dummy3 -text "" -width 1
+    if {[eval concat $$var_iemgui_lin0_log1] == 0} {
+        button $mytoplevel.para.lilo -text [_ [eval concat $$var_iemgui_lilo0]] -width 5 \
+            -command "::dialog_iemgui::lilo $mytoplevel" }
+    if {[eval concat $$var_iemgui_lin0_log1] == 1} {
+        button $mytoplevel.para.lilo -text [_ [eval concat $$var_iemgui_lilo1]] -width 5 \
+            -command "::dialog_iemgui::lilo $mytoplevel" }
+    if {[eval concat $$var_iemgui_loadbang] == 0} {
+        button $mytoplevel.para.lb -text [_ "No init"] \
+            -width [::msgcat::mcmax "No init"] \
+            -command "::dialog_iemgui::lb $mytoplevel" }
+    if {[eval concat $$var_iemgui_loadbang] == 1} {
+        button $mytoplevel.para.lb -text [_ "Save"] \
+            -width [::msgcat::mcmax "Save"] \
+            -command "::dialog_iemgui::lb $mytoplevel" }
+    label $mytoplevel.para.num_lab -text [_ $num_label] -width 9
+    entry $mytoplevel.para.num_ent -textvariable $var_iemgui_num -width 4
+
+    if {[eval concat $$var_iemgui_steady] == 0} {
+        button $mytoplevel.para.stdy_jmp -command "::dialog_iemgui::stdy_jmp $mytoplevel" \
+            -text [_ "Jump on click"] -width [::msgcat::mcmax "Jump on click"] }
+    if {[eval concat $$var_iemgui_steady] == 1} {
+        button $mytoplevel.para.stdy_jmp -command "::dialog_iemgui::stdy_jmp $mytoplevel" \
+            -text [_ "Steady on click"] -width [::msgcat::mcmax "Steady on click"] }
+    if {[eval concat $$var_iemgui_lin0_log1] >= 0} {
+        pack $mytoplevel.para.lilo -side left -expand 1}
+    if {[eval concat $$var_iemgui_loadbang] >= 0} {
+        pack $mytoplevel.para.dummy2 $mytoplevel.para.lb -side left -expand 1}
+    if {[eval concat $$var_iemgui_num] > 0} {
+        pack $mytoplevel.para.dummy3 $mytoplevel.para.num_lab $mytoplevel.para.num_ent -side left -expand 1}
+    if {[eval concat $$var_iemgui_steady] >= 0} {
+        pack $mytoplevel.para.dummy3 $mytoplevel.para.stdy_jmp -side left -expand 1}
+    
+    frame $mytoplevel.spacer0 -height 4
+    pack $mytoplevel.spacer0 -side top
+    
+    labelframe $mytoplevel.s_r -borderwidth 1 -pady 4 -text [_ "Messages"]
+    pack $mytoplevel.s_r -side top -fill x -ipadx 5
+    frame $mytoplevel.s_r.send
+    pack $mytoplevel.s_r.send -side top
+    label $mytoplevel.s_r.send.lab -text [_ "Send symbol:"] -width 12  -justify right
+    entry $mytoplevel.s_r.send.ent -textvariable $var_iemgui_snd -width 22
+    if { $snd ne "nosndno" } {
+        pack $mytoplevel.s_r.send.lab $mytoplevel.s_r.send.ent -side left}
+    
+    frame $mytoplevel.s_r.receive
+    pack $mytoplevel.s_r.receive -side top
+    label $mytoplevel.s_r.receive.lab -text [_ "Receive symbol:"] -width 12 -justify right
+    entry $mytoplevel.s_r.receive.ent -textvariable $var_iemgui_rcv -width 22
+    if { $rcv ne "norcvno" } {
+        pack $mytoplevel.s_r.receive.lab $mytoplevel.s_r.receive.ent -side left}
+    
+    # get the current font name from the int given from C-space (gn_f)
+    set current_font $::font_family
+    if {[eval concat $$var_iemgui_gn_f] == 1} \
+        { set current_font "Helvetica" }
+    if {[eval concat $$var_iemgui_gn_f] == 2} \
+        { set current_font "Times" }
+    
+    frame $mytoplevel.spacer1 -height 7
+    pack $mytoplevel.spacer1 -side top
+    
+    labelframe $mytoplevel.label -borderwidth 1 -text [_ "Label"] -pady 4
+    pack $mytoplevel.label -side top -fill x
+    entry $mytoplevel.label.name_entry -textvariable $var_iemgui_gui_nam -width 30 \
+        -font [list $current_font 12 $::font_weight]
+    pack $mytoplevel.label.name_entry -side top -expand yes -fill both -padx 5
+    
+    frame $mytoplevel.label.xy -padx 27 -pady 1
+    pack $mytoplevel.label.xy -side top
+    label $mytoplevel.label.xy.x_lab -text [_ "X offset"] \
+        -width [::msgcat::mcmax "X offset"]
+    entry $mytoplevel.label.xy.x_entry -textvariable $var_iemgui_gn_dx -width 5
+    label $mytoplevel.label.xy.dummy1 -text " " -width 2
+    label $mytoplevel.label.xy.y_lab -text [_ "Y offset"] \
+        -width [::msgcat::mcmax "Y offset"]
+    entry $mytoplevel.label.xy.y_entry -textvariable $var_iemgui_gn_dy -width 5
+    pack $mytoplevel.label.xy.x_lab $mytoplevel.label.xy.x_entry $mytoplevel.label.xy.dummy1 \
+        $mytoplevel.label.xy.y_lab $mytoplevel.label.xy.y_entry -side left -anchor e
+    
+    label $mytoplevel.label.fontpopup_label -text $current_font \
+        -relief groove -font [list $current_font 12 $::font_weight] -padx 5
+    pack $mytoplevel.label.fontpopup_label -side left -anchor w -expand yes -fill x
+    label $mytoplevel.label.fontsize_label -text [_ "Size:"] \
+        -width [::msgcat::mcmax "Size:"]
+    entry $mytoplevel.label.fontsize_entry -textvariable $var_iemgui_gn_fs -width 5
+    pack $mytoplevel.label.fontsize_entry $mytoplevel.label.fontsize_label \
+        -side right -anchor e -padx 5 -pady 5
+    menu $mytoplevel.popup
+    $mytoplevel.popup add command \
+        -label $::font_family \
+        -font [format {{%s} 12 %s} $::font_family $::font_weight] \
+        -command "::dialog_iemgui::toggle_font $mytoplevel 0" 
+    $mytoplevel.popup add command \
+        -label "Helvetica" \
+        -font [format {Helvetica 12 %s} $::font_weight] \
+        -command "::dialog_iemgui::toggle_font $mytoplevel 1" 
+    $mytoplevel.popup add command \
+        -label "Times" \
+        -font [format {Times 12 %s} $::font_weight] \
+        -command "::dialog_iemgui::toggle_font $mytoplevel 2" 
+    bind $mytoplevel.label.fontpopup_label <Button> \
+        [list tk_popup $mytoplevel.popup %X %Y]
+    
+    frame $mytoplevel.spacer2 -height 7
+    pack $mytoplevel.spacer2 -side top
+    
+    labelframe $mytoplevel.colors -borderwidth 1 -text [_ "Colors"]
+    pack $mytoplevel.colors -fill x -ipadx 5 -ipady 4
+    
+    frame $mytoplevel.colors.select
+    pack $mytoplevel.colors.select -side top
+    radiobutton $mytoplevel.colors.select.radio0 -value 0 -variable \
+        $var_iemgui_l2_f1_b0 -text [_ "Background"] -justify left \
+        -width [::msgcat::mcmax "Background"]
+    radiobutton $mytoplevel.colors.select.radio1 -value 1 -variable \
+        $var_iemgui_l2_f1_b0 -text [_ "Front"] -justify left \
+        -width [::msgcat::mcmax "Front"]
+    radiobutton $mytoplevel.colors.select.radio2 -value 2 -variable \
+        $var_iemgui_l2_f1_b0 -text [_ "Label"] -justify left \
+        -width [::msgcat::mcmax "Label"]
+    if { [eval concat $$var_iemgui_fcol] >= 0 } {
+        pack $mytoplevel.colors.select.radio0 $mytoplevel.colors.select.radio1 \
+            $mytoplevel.colors.select.radio2 -side left
+    } else {
+        pack $mytoplevel.colors.select.radio0 $mytoplevel.colors.select.radio2 -side left
+    }
+    
+    frame $mytoplevel.colors.sections
+    pack $mytoplevel.colors.sections -side top
+    button $mytoplevel.colors.sections.but -text [_ "Compose color"] \
+        -width [::msgcat::mcmax "Compose color"] \
+        -command "::dialog_iemgui::choose_col_bkfrlb $mytoplevel"
+    pack $mytoplevel.colors.sections.but -side left -anchor w -padx 10 -pady 5 \
+        -expand yes -fill x
+    if { [eval concat $$var_iemgui_fcol] >= 0 } {
+        label $mytoplevel.colors.sections.fr_bk -text "o=||=o" -width 6 \
+            -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -foreground [format "#%6.6x" [eval concat $$var_iemgui_fcol]] \
+            -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_fcol]] \
+            -font [list $current_font 12 $::font_weight] -padx 2 -pady 2 -relief ridge
+    } else {
+        label $mytoplevel.colors.sections.fr_bk -text "o=||=o" -width 6 \
+            -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -foreground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+            -font [list $current_font 12 $::font_weight] -padx 2 -pady 2 -relief ridge
+    }
+    label $mytoplevel.colors.sections.lb_bk -text [_ "Test label"] \
+        -width [::msgcat::mcmax "Test label"] \
+        -background [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+        -activebackground [format "#%6.6x" [eval concat $$var_iemgui_bcol]] \
+        -foreground [format "#%6.6x" [eval concat $$var_iemgui_lcol]] \
+        -activeforeground [format "#%6.6x" [eval concat $$var_iemgui_lcol]] \
+        -font [list $current_font 12 $::font_weight] -padx 2 -pady 2 -relief ridge
+    pack $mytoplevel.colors.sections.lb_bk $mytoplevel.colors.sections.fr_bk \
+        -side right -anchor e -expand yes -fill both -pady 7
+    
+    # color scheme by Mary Ann Benedetto http://piR2.org
+    frame $mytoplevel.colors.r1
+    pack $mytoplevel.colors.r1 -side top
+    foreach i { 0 1 2 3 4 5 6 7 8 9} \
+        hexcol { 0xFFFFFF 0xDFDFDF 0xBBBBBB 0xFFC7C6 0xFFE3C6 \
+                     0xFEFFC6 0xC6FFC7 0xc6FEFF 0xC7C6FF 0xE3C6FF } \
+        {
+            label $mytoplevel.colors.r1.c$i -background [format "#%6.6x" $hexcol] \
+                -activebackground [format "#%6.6x" $hexcol] -relief ridge \
+                -padx 7 -pady 0
+            bind $mytoplevel.colors.r1.c$i <Button> [format "::dialog_iemgui::preset_col %s %d" $mytoplevel $hexcol] 
+        }
+    pack $mytoplevel.colors.r1.c0 $mytoplevel.colors.r1.c1 $mytoplevel.colors.r1.c2 $mytoplevel.colors.r1.c3 \
+        $mytoplevel.colors.r1.c4 $mytoplevel.colors.r1.c5 $mytoplevel.colors.r1.c6 $mytoplevel.colors.r1.c7 \
+        $mytoplevel.colors.r1.c8 $mytoplevel.colors.r1.c9 -side left
+    
+    frame $mytoplevel.colors.r2
+    pack $mytoplevel.colors.r2 -side top
+    foreach i { 0 1 2 3 4 5 6 7 8 9 } \
+        hexcol { 0x9F9F9F 0x7C7C7C 0x606060 0xFF0400 0xFF8300 \
+                     0xFAFF00 0x00FF04 0x00FAFF 0x0400FF 0x9C00FF } \
+        {
+            label $mytoplevel.colors.r2.c$i -background [format "#%6.6x" $hexcol] \
+                -activebackground [format "#%6.6x" $hexcol] -relief ridge \
+                -padx 7 -pady 0
+            bind  $mytoplevel.colors.r2.c$i <Button> \
+                [format "::dialog_iemgui::preset_col %s %d" $mytoplevel $hexcol] 
+        }
+    pack $mytoplevel.colors.r2.c0 $mytoplevel.colors.r2.c1 $mytoplevel.colors.r2.c2 $mytoplevel.colors.r2.c3 \
+        $mytoplevel.colors.r2.c4 $mytoplevel.colors.r2.c5 $mytoplevel.colors.r2.c6 $mytoplevel.colors.r2.c7 \
+        $mytoplevel.colors.r2.c8 $mytoplevel.colors.r2.c9 -side left
+    
+    frame $mytoplevel.colors.r3
+    pack $mytoplevel.colors.r3 -side top
+    foreach i { 0 1 2 3 4 5 6 7 8 9 } \
+        hexcol { 0x404040 0x202020 0x000000 0x551312 0x553512 \
+                     0x535512 0x0F4710 0x0E4345 0x131255 0x2F004D } \
+        {
+            label $mytoplevel.colors.r3.c$i -background [format "#%6.6x" $hexcol] \
+                -activebackground [format "#%6.6x" $hexcol] -relief ridge \
+                -padx 7 -pady 0
+            bind  $mytoplevel.colors.r3.c$i <Button> \
+                [format "::dialog_iemgui::preset_col %s %d" $mytoplevel $hexcol] 
+        }
+    pack $mytoplevel.colors.r3.c0 $mytoplevel.colors.r3.c1 $mytoplevel.colors.r3.c2 $mytoplevel.colors.r3.c3 \
+        $mytoplevel.colors.r3.c4 $mytoplevel.colors.r3.c5 $mytoplevel.colors.r3.c6 $mytoplevel.colors.r3.c7 \
+        $mytoplevel.colors.r3.c8 $mytoplevel.colors.r3.c9 -side left
+    
+    frame $mytoplevel.cao -pady 10
+    pack $mytoplevel.cao -side top
+    button $mytoplevel.cao.cancel -text [_ "Cancel"] -width 6 \
+        -command "::dialog_iemgui::cancel $mytoplevel"
+    label $mytoplevel.cao.dummy1 -text "" -width 3
+    button $mytoplevel.cao.apply -text [_ "Apply"] -width 6 \
+        -command "::dialog_iemgui::apply $mytoplevel"
+    label $mytoplevel.cao.dummy2 -text "" -width 3
+    button $mytoplevel.cao.ok -text [_ "OK"] -width 6 \
+        -command "::dialog_iemgui::ok $mytoplevel"
+    pack $mytoplevel.cao.cancel $mytoplevel.cao.dummy1 -side left
+    pack $mytoplevel.cao.apply $mytoplevel.cao.dummy2 -side left
+    pack $mytoplevel.cao.ok -side left
+    
+    if {[info tclversion] < 8.4} {
+        bind $mytoplevel <Key-Tab> {tkTabToWindow [tk_focusNext %W]}
+        bind $mytoplevel <<PrevWindow>> {tkTabToWindow [tk_focusPrev %W]}
+    } else {
+        bind $mytoplevel <Key-Tab> {tk::TabToWindow [tk_focusNext %W]}
+        bind $mytoplevel <<PrevWindow>> {tk::TabToWindow [tk_focusPrev %W]}
+    }
+    
+    $mytoplevel.dim.w_ent select from 0
+    $mytoplevel.dim.w_ent select adjust end
+    focus $mytoplevel.dim.w_ent
+}
+
diff --git a/tcl/dialog_midi.tcl b/tcl/dialog_midi.tcl
new file mode 100644
index 000000000..d85546657
--- /dev/null
+++ b/tcl/dialog_midi.tcl
@@ -0,0 +1,344 @@
+package provide dialog_midi 0.1
+
+namespace eval ::dialog_midi:: {
+    namespace export pdtk_midi_dialog
+}
+
+# TODO this panel really needs some reworking, it works but the code is
+# very unreadable
+
+
+####################### midi dialog ##################
+
+proc ::dialog_midi::apply {mytoplevel} {
+    global midi_indev1 midi_indev2 midi_indev3 midi_indev4 
+    global midi_outdev1 midi_outdev2 midi_outdev3 midi_outdev4
+    global midi_alsain midi_alsaout
+    
+    pdsend "pd midi-dialog \
+        $midi_indev1 \
+        $midi_indev2 \
+        $midi_indev3 \
+        $midi_indev4 \
+        $midi_outdev1 \
+        $midi_outdev2 \
+        $midi_outdev3 \
+        $midi_outdev4 \
+        $midi_alsain \
+        $midi_alsaout"
+}
+
+proc ::dialog_midi::cancel {mytoplevel} {
+    pdsend "$mytoplevel cancel"
+}
+
+proc ::dialog_midi::ok {mytoplevel} {
+    ::dialog_midi::apply $mytoplevel
+    ::dialog_midi::cancel $mytoplevel
+}
+
+# callback from popup menu
+proc midi_popup_action {buttonname varname devlist index} {
+    global midi_indevlist midi_outdevlist $varname
+    $buttonname configure -text [lindex $devlist $index]
+    set $varname $index
+}
+
+# create a popup menu
+proc midi_popup {name buttonname varname devlist} {
+    if [winfo exists $name.popup] {destroy $name.popup}
+    menu $name.popup -tearoff false
+    if {$::windowingsystem eq "win32"} {
+        $name.popup configure -font menuFont
+    }
+#    puts stderr [concat $devlist ]
+    for {set x 0} {$x<[llength $devlist]} {incr x} {
+        $name.popup add command -label [lindex $devlist $x] \
+            -command [list midi_popup_action \
+                $buttonname $varname $devlist $x] 
+    }
+    tk_popup $name.popup [winfo pointerx $name] [winfo pointery $name] 0
+}
+
+# start a dialog window to select midi devices.  "longform" asks us to make
+# controls for opening several devices; if not, we get an extra button to
+# turn longform on and restart the dialog.
+proc ::dialog_midi::pdtk_midi_dialog {id indev1 indev2 indev3 indev4 \
+        outdev1 outdev2 outdev3 outdev4 longform} {
+    global midi_indev1 midi_indev2 midi_indev3 midi_indev4 
+    global midi_outdev1 midi_outdev2 midi_outdev3 midi_outdev4
+    global midi_indevlist midi_outdevlist
+    global midi_alsain midi_alsaout
+
+    set midi_indev1 $indev1
+    set midi_indev2 $indev2
+    set midi_indev3 $indev3
+    set midi_indev4 $indev4
+    set midi_outdev1 $outdev1
+    set midi_outdev2 $outdev2
+    set midi_outdev3 $outdev3
+    set midi_outdev4 $outdev4
+    set midi_alsain [llength $midi_indevlist]
+    set midi_alsaout [llength $midi_outdevlist]
+
+    toplevel $id
+    wm title $id [_ "MIDI Settings"]
+    if {$::windowingsystem eq "aqua"} {$id configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $id "midi"
+
+    frame $id.buttonframe
+    pack $id.buttonframe -side bottom -fill x -pady 2m
+    button $id.buttonframe.cancel -text [_ "Cancel"]\
+        -command "::dialog_midi::cancel $id"
+    button $id.buttonframe.apply -text [_ "Apply"]\
+        -command "::dialog_midi::apply $id"
+    button $id.buttonframe.ok -text [_ "OK"]\
+        -command "::dialog_midi::ok $id"
+    pack $id.buttonframe.cancel -side left -expand 1
+    pack $id.buttonframe.apply -side left -expand 1
+    pack $id.buttonframe.ok -side left -expand 1
+    
+        # input device 1
+    frame $id.in1f
+    pack $id.in1f -side top
+
+    label $id.in1f.l1 -text [_ "Input device 1:"]
+    button $id.in1f.x1 -text [lindex $midi_indevlist $midi_indev1] \
+        -command [list midi_popup $id $id.in1f.x1 midi_indev1 $midi_indevlist]
+    pack $id.in1f.l1 $id.in1f.x1 -side left
+
+        # input device 2
+    if {$longform && [llength $midi_indevlist] > 2} {
+        frame $id.in2f
+        pack $id.in2f -side top
+
+        label $id.in2f.l1 -text [_ "Input device 2:"]
+        button $id.in2f.x1 -text [lindex $midi_indevlist $midi_indev2] \
+            -command [list midi_popup $id $id.in2f.x1 midi_indev2 \
+                $midi_indevlist]
+        pack $id.in2f.l1 $id.in2f.x1 -side left
+    }
+
+        # input device 3
+    if {$longform && [llength $midi_indevlist] > 3} {
+        frame $id.in3f
+        pack $id.in3f -side top
+
+        label $id.in3f.l1 -text [_ "Input device 3:"]
+        button $id.in3f.x1 -text [lindex $midi_indevlist $midi_indev3] \
+            -command [list midi_popup $id $id.in3f.x1 midi_indev3 \
+                $midi_indevlist]
+        pack $id.in3f.l1 $id.in3f.x1 -side left
+    }
+
+        # input device 4
+    if {$longform && [llength $midi_indevlist] > 4} {
+        frame $id.in4f
+        pack $id.in4f -side top
+
+        label $id.in4f.l1 -text [_ "Input device 4:"]
+        button $id.in4f.x1 -text [lindex $midi_indevlist $midi_indev4] \
+            -command [list midi_popup $id $id.in4f.x1 midi_indev4 \
+                $midi_indevlist]
+        pack $id.in4f.l1 $id.in4f.x1 -side left
+    }
+
+        # output device 1
+
+    frame $id.out1f
+    pack $id.out1f -side top
+    label $id.out1f.l1 -text [_ "Output device 1:"]
+    button $id.out1f.x1 -text [lindex $midi_outdevlist $midi_outdev1] \
+        -command [list midi_popup $id $id.out1f.x1 midi_outdev1 \
+            $midi_outdevlist]
+    pack $id.out1f.l1 $id.out1f.x1 -side left
+
+        # output device 2
+    if {$longform && [llength $midi_outdevlist] > 2} {
+        frame $id.out2f
+        pack $id.out2f -side top
+        label $id.out2f.l1 -text [_ "Output device 2:"]
+        button $id.out2f.x1 -text [lindex $midi_outdevlist $midi_outdev2] \
+            -command \
+            [list midi_popup $id $id.out2f.x1 midi_outdev2 $midi_outdevlist]
+        pack $id.out2f.l1 $id.out2f.x1 -side left
+    }
+
+        # output device 3
+    if {$longform && [llength $midi_midi_outdevlist] > 3} {
+        frame $id.out3f
+        pack $id.out3f -side top
+        label $id.out3f.l1 -text [_ "Output device 3:"]
+        button $id.out3f.x1 -text [lindex $midi_outdevlist $midi_outdev3] \
+            -command \
+            [list midi_popup $id $id.out3f.x1 midi_outdev3 $midi_outdevlist]
+        pack $id.out3f.l1 $id.out3f.x1 -side left
+    }
+
+        # output device 4
+    if {$longform && [llength $midi_midi_outdevlist] > 4} {
+        frame $id.out4f
+        pack $id.out4f -side top
+        label $id.out4f.l1 -text [_ "Output device 4:"]
+        button $id.out4f.x1 -text [lindex $midi_outdevlist $midi_outdev4] \
+            -command \
+            [list midi_popup $id $id.out4f.x1 midi_outdev4 $midi_outdevlist]
+        pack $id.out4f.l1 $id.out4f.x1 -side left
+    }
+
+        # if not the "long form" make a button to
+        # restart with longform set. 
+    
+    if {$longform == 0} {
+        frame $id.longbutton
+        pack $id.longbutton -side top
+        button $id.longbutton.b -text [_ "Use multiple devices"] \
+            -command  {pdsend "pd midi-properties 1"}
+        pack $id.longbutton.b
+    }
+}
+
+proc ::dialog_midi::pdtk_alsa_midi_dialog {id indev1 indev2 indev3 indev4 \
+        outdev1 outdev2 outdev3 outdev4 longform alsa} {
+    global midi_indev1 midi_indev2 midi_indev3 midi_indev4 
+    global midi_outdev1 midi_outdev2 midi_outdev3 midi_outdev4
+    global midi_indevlist midi_outdevlist
+    global midi_alsain midi_alsaout
+
+    set midi_indev1 $indev1
+    set midi_indev2 $indev2
+    set midi_indev3 $indev3
+    set midi_indev4 $indev4
+    set midi_outdev1 $outdev1
+    set midi_outdev2 $outdev2
+    set midi_outdev3 $outdev3
+    set midi_outdev4 $outdev4
+    set midi_alsain [llength $midi_indevlist]
+    set midi_alsaout [llength $midi_outdevlist]
+    
+    toplevel $id
+    wm title $id [_ "ALSA MIDI Settings"]
+    if {$::windowingsystem eq "aqua"} {$id configure -menu .menubar}
+    ::pd_bindings::dialog_bindings $id "midi"
+
+    frame $id.buttonframe
+    pack $id.buttonframe -side bottom -fill x -pady 2m
+    button $id.buttonframe.cancel -text [_ "Cancel"]\
+        -command "::dialog_midi::cancel $id"
+    button $id.buttonframe.apply -text [_ "Apply"]\
+        -command "::dialog_midi::apply $id"
+    button $id.buttonframe.ok -text [_ "OK"]\
+        -command "::dialog_midi::ok $id"
+    pack $id.buttonframe.cancel -side left -expand 1
+    pack $id.buttonframe.apply -side left -expand 1
+    pack $id.buttonframe.ok -side left -expand 1
+
+    frame $id.in1f
+    pack $id.in1f -side top
+
+  if {$alsa == 0} {
+        # input device 1
+    label $id.in1f.l1 -text [_ "Input device 1:"]
+    button $id.in1f.x1 -text [lindex $midi_indevlist $midi_indev1] \
+        -command [list midi_popup $id $id.in1f.x1 midi_indev1 $midi_indevlist]
+    pack $id.in1f.l1 $id.in1f.x1 -side left
+
+        # input device 2
+    if {$longform && [llength $midi_indevlist] > 2} {
+        frame $id.in2f
+        pack $id.in2f -side top
+
+        label $id.in2f.l1 -text [_ "Input device 2:"]
+        button $id.in2f.x1 -text [lindex $midi_indevlist $midi_indev2] \
+            -command [list midi_popup $id $id.in2f.x1 midi_indev2 \
+                $midi_indevlist]
+        pack $id.in2f.l1 $id.in2f.x1 -side left
+    }
+
+        # input device 3
+    if {$longform && [llength $midi_indevlist] > 3} {
+        frame $id.in3f
+        pack $id.in3f -side top
+
+        label $id.in3f.l1 -text [_ "Input device 3:"]
+        button $id.in3f.x1 -text [lindex $midi_indevlist $midi_indev3] \
+            -command [list midi_popup $id $id.in3f.x1 midi_indev3 \
+                $midi_indevlist]
+        pack $id.in3f.l1 $id.in3f.x1 -side left
+    }
+
+        # input device 4
+    if {$longform && [llength $midi_indevlist] > 4} {
+        frame $id.in4f
+        pack $id.in4f -side top
+
+        label $id.in4f.l1 -text [_ "Input device 4:"]
+        button $id.in4f.x1 -text [lindex $midi_indevlist $midi_indev4] \
+            -command [list midi_popup $id $id.in4f.x1 midi_indev4 \
+                $midi_indevlist]
+        pack $id.in4f.l1 $id.in4f.x1 -side left
+    }
+
+        # output device 1
+
+    frame $id.out1f
+    pack $id.out1f -side top
+    label $id.out1f.l1 -text [_ "Output device 1:"]
+    button $id.out1f.x1 -text [lindex $midi_outdevlist $midi_outdev1] \
+        -command [list midi_popup $id $id.out1f.x1 midi_outdev1 \
+            $midi_outdevlist]
+    pack $id.out1f.l1 $id.out1f.x1 -side left
+
+        # output device 2
+    if {$longform && [llength $midi_outdevlist] > 2} {
+        frame $id.out2f
+        pack $id.out2f -side top
+        label $id.out2f.l1 -text [_ "Output device 2:"]
+        button $id.out2f.x1 -text [lindex $midi_outdevlist $midi_outdev2] \
+            -command \
+            [list midi_popup $id $id.out2f.x1 midi_outdev2 $midi_outdevlist]
+        pack $id.out2f.l1 $id.out2f.x1 -side left
+    }
+
+        # output device 3
+    if {$longform && [llength $midi_outdevlist] > 3} {
+        frame $id.out3f
+        pack $id.out3f -side top
+        label $id.out3f.l1 -text [_ "Output device 3:"]
+        button $id.out3f.x1 -text [lindex $midi_outdevlist $midi_outdev3] \
+            -command \
+            [list midi_popup $id $id.out3f.x1 midi_outdev3 $midi_outdevlist]
+        pack $id.out3f.l1 $id.out3f.x1 -side left
+    }
+
+        # output device 4
+    if {$longform && [llength $midi_outdevlist] > 4} {
+        frame $id.out4f
+        pack $id.out4f -side top
+        label $id.out4f.l1 -text [_ "Output device 4:"]
+        button $id.out4f.x1 -text [lindex $midi_outdevlist $midi_outdev4] \
+            -command \
+            [list midi_popup $id $id.out4f.x1 midi_outdev4 $midi_outdevlist]
+        pack $id.out4f.l1 $id.out4f.x1 -side left
+    }
+
+        # if not the "long form" make a button to
+        # restart with longform set. 
+    
+    if {$longform == 0} {
+        frame $id.longbutton
+        pack $id.longbutton -side top
+        button $id.longbutton.b -text [_ "Use multiple ALSA devices"] \
+            -command  {pdsend "pd midi-properties 1"}
+        pack $id.longbutton.b
+    }
+    }
+    if {$alsa} {
+        label $id.in1f.l1 -text [_ "In Ports:"]
+        entry $id.in1f.x1 -textvariable midi_alsain -width 4
+        pack $id.in1f.l1 $id.in1f.x1 -side left
+        label $id.in1f.l2 -text [_ "Out Ports:"]
+        entry $id.in1f.x2 -textvariable midi_alsaout -width 4
+        pack $id.in1f.l2 $id.in1f.x2 -side left
+    }
+}
diff --git a/tcl/opt_parser.tcl b/tcl/opt_parser.tcl
new file mode 100644
index 000000000..d304e045c
--- /dev/null
+++ b/tcl/opt_parser.tcl
@@ -0,0 +1,78 @@
+package provide opt_parser 0.1
+
+namespace eval opt_parser {
+    # list of option vars (keys are long option names)
+    variable optlist
+    variable optprefix {-}
+}
+
+proc opt_parser::init {optdata} {
+    variable optlist
+    array unset optlist
+    array set optlist {}
+    foreach item $optdata {
+        foreach {longname varlist} $item {
+            if {[llength $varlist] < 1} {
+                return -code error "usage: init { {optname {var1 var2 ...}} ... }"
+            }
+            set optlist($longname) $varlist
+        }
+    }
+}
+
+proc opt_parser::get_options {argv {opts {}}} {
+    set ignore_unknown_flags 0
+    foreach {k v} $opts {set $k $v}
+
+    variable optlist
+    variable optprefix
+
+    # zero all the options 1st var
+    foreach optName [array names optlist] {
+        uplevel [list set [lindex $optlist($optName) 0] 0]
+        for {set i 1} {$i < [llength $optlist($optName)]} {incr i} {
+            uplevel [list set [lindex $optlist($optName) $i] [list]]
+        }
+    }
+
+    # here will be appended non-options arguments
+    set residualArgs {}
+
+    set argc [llength $argv]
+    for {set i 0} {$i < $argc} {} {
+        # get i-th arg
+        set argv_i [lindex $argv $i]
+        incr i
+
+        # if it's not an option, stop here, and add to residualArgs
+        if {![regexp ^$optprefix $argv_i]} {
+            lappend residualArgs $argv_i
+            continue
+        }
+
+        set optName [regsub ^$optprefix $argv_i {}]
+        if {[info exists optlist($optName)]} {
+            set varlist $optlist($optName)
+            uplevel [list set [lindex $optlist($optName) 0] 1]
+            set n_required_opt_args [expr {-1+[llength $varlist]}]
+            set j 1
+            while {$n_required_opt_args > 0} {
+                incr n_required_opt_args -1
+                if {$i >= $argc} {
+                    return -code error "not enough arguments for option $optprefix$optName"
+                }
+                uplevel [list lappend [lindex $varlist $j] [lindex $argv $i]]
+                incr j
+                incr i
+            }
+        } else {
+            if {$ignore_unknown_flags} {
+                lappend residualArgs $argv_i
+                continue
+            } else {
+                return -code error "unknown option: $optprefix$optName"
+            }
+        }
+    }
+    return $residualArgs
+}
diff --git a/tcl/pd-gui.tcl b/tcl/pd-gui.tcl
new file mode 100644
index 000000000..6dfe16632
--- /dev/null
+++ b/tcl/pd-gui.tcl
@@ -0,0 +1,503 @@
+#!/bin/sh
+# This line continues for Tcl, but is a single line for 'sh' \
+    exec wish "$0" -- ${1+"$@"}
+# For information on usage and redistribution, and for a DISCLAIMER OF ALL
+# WARRANTIES, see the file, "LICENSE.txt," in this distribution.
+# Copyright (c) 1997-2009 Miller Puckette.
+
+# "." automatically gets a window, we don't want it.  Withdraw it before doing
+# anything else, so that we don't get the automatic window flashing for a
+# second while pd loads.
+wm withdraw . 
+
+puts -------------------------------pd-gui.tcl-----------------------------------
+
+package require Tcl 8.3
+package require Tk
+package require Tk
+if {[tk windowingsystem] ne "win32"} {package require msgcat}
+# TODO figure out msgcat issue on Windows
+
+# Pd's packages are stored in the same directory as the main script (pd-gui.tcl)
+set auto_path [linsert $auto_path 0 [file dirname [info script]]]
+package require pd_connect
+package require pd_menus
+package require pd_bindings
+package require pdwindow
+package require dialog_array
+package require dialog_audio
+package require dialog_canvas
+package require dialog_font
+package require dialog_gatom
+package require dialog_iemgui
+package require dialog_midi
+package require pdtk_canvas
+package require pdtk_text
+# TODO eliminate this kludge:
+package require wheredoesthisgo
+
+# import into the global namespace for backwards compatibility
+namespace import ::pd_connect::pdsend
+namespace import ::pdwindow::pdtk_post
+namespace import ::dialog_array::pdtk_array_dialog
+namespace import ::dialog_audio::pdtk_audio_dialog
+namespace import ::dialog_canvas::pdtk_canvas_dialog
+namespace import ::dialog_font::pdtk_canvas_dofont
+namespace import ::dialog_gatom::pdtk_gatom_dialog
+namespace import ::dialog_iemgui::pdtk_iemgui_dialog
+namespace import ::dialog_midi::pdtk_midi_dialog
+namespace import ::dialog_midi::pdtk_alsa_midi_dialog
+
+# hack - these should be better handled in the C code
+namespace import ::dialog_array::pdtk_array_listview_new
+namespace import ::dialog_array::pdtk_array_listview_fillpage
+namespace import ::dialog_array::pdtk_array_listview_setpage
+namespace import ::dialog_array::pdtk_array_listview_closeWindow
+
+#------------------------------------------------------------------------------#
+# global variables
+
+set PD_MAJOR_VERSION 0
+set PD_MINOR_VERSION 0
+set PD_BUGFIX_VERSION 0
+set PD_TEST_VERSION ""
+
+set TCL_MAJOR_VERSION 0
+set TCL_MINOR_VERSION 0
+set TCL_BUGFIX_VERSION 0
+
+# for testing which platform we are running on ("aqua", "win32", or "x11")
+set windowingsystem ""
+
+# variable for vwait so that 'pd-gui' will timeout if 'pd' never shows up
+set wait4pd "init"
+
+# canvas font, received from pd in pdtk_pd_startup, set in s_main.c
+set font_family "courier"
+set font_weight "normal"
+# sizes of chars for each of the Pd fixed font sizes:
+#  fontsize  width(pixels)  height(pixels)
+set font_fixed_metrics {
+    8 5 10
+    9 6 11
+    10 6 13
+    12 7 15
+    14 8 17
+    16 10 20
+    18 11 22
+    24 14 30
+    30 18 37
+    36 22 45
+}
+
+# root path to lib of Pd's files, see s_main.c for more info
+set sys_libdir {}
+# root path where the pd-gui.tcl GUI script is located
+set sys_guidir {}
+
+set audioapi_list {}
+set midiapi_list {}
+set pd_whichapi 0
+set pd_whichmidiapi 0
+
+# current state of the DSP
+set dsp 0
+# the toplevel window that currently is on top and has focus
+set focused_window .
+# TODO figure out how to get all windows into the menu_windowlist
+# store list of parent windows for Window menu
+set menu_windowlist {}
+# store that last 10 files that were opened
+set recentfiles_list {}
+set total_recentfiles 10
+# keep track of the location of popup menu for CanvasWindows
+set popup_xpix 0
+set popup_ypix 0
+
+## per toplevel/patch data
+# store editmode for each open canvas, starting with a blank array
+array set editmode {}
+
+#------------------------------------------------------------------------------#
+# coding style
+#
+# these are preliminary ideas, we'll change them as we work things out:
+# - when possible use "" doublequotes to delimit messages
+# - use '$::myvar' instead of 'global myvar' 
+# - for the sake of clarity, there should not be any inline code, everything 
+#   should be in a proc that is ultimately triggered from main()
+# - if a menu_* proc opens a dialog panel, that proc is called menu_*_dialog
+# - use "eq/ne" for string comparison, NOT "==/!=" (http://wiki.tcl.tk/15323)
+#
+## Names for Common Variables
+#----------------------------
+#
+# variables named after the Tk widgets they represent
+#   $mytoplevel = a window id made by a 'toplevel' command
+#   $mygfxstub = a window id made by a 'toplevel' command via gfxstub/x_gui.c
+#   $menubar = the 'menu' attached to each 'toplevel'
+#   $mymenu = 'menu' attached to the menubar
+#   $menuitem = 'menu' item
+#   $mycanvas = 'canvas'
+#   $canvasitem = 'canvas' item
+#
+#
+## Prefix Names for procs
+#----------------------------
+# pdtk_     pd -> pd-gui API (i.e. called from 'pd')
+# pdsend    pd-gui -> pd API (sends a message to 'pd' using pdsend)
+
+# ------------------------------------------------------------------------------
+# init functions
+
+proc set_pd_version {versionstring} {
+    regexp -- {.*([0-9])\.([0-9]+)[\.\-]([0-9]+)([^0-9]?.*)} $versionstring \
+        wholematch \
+        ::PD_MAJOR_VERSION ::PD_MINOR_VERSION ::PD_BUGFIX_VERSION ::PD_TEST_VERSION
+}
+
+proc set_tcl_version {} {
+    regexp {([0-9])\.([0-9])\.([0-9]+)} [info patchlevel] \
+        wholematch \
+        ::TCL_MAJOR_VERSION ::TCL_MINOR_VERSION ::TCL_BUGFIX_VERSION
+}
+
+# root paths to find Pd's files where they are installed
+proc set_pd_paths {} {
+    set ::sys_guidir [file normalize [file dirname [info script]]]
+    set ::sys_libdir [file normalize [file join $::sys_guidir ".."]]
+}
+
+proc init_for_platform {} {
+    # we are not using Tk scaling, so fix it to 1 on all platforms.  This
+    # guarantees that patches will be pixel-exact on every platform
+    tk scaling 1
+
+    switch -- $::windowingsystem {
+        "x11" {
+            # add control to show/hide hidden files in the open panel (load
+            # the tk_getOpenFile dialog once, otherwise it will not work)
+            catch {tk_getOpenFile -with-invalid-argument} 
+            set ::tk::dialog::file::showHiddenBtn 1
+            set ::tk::dialog::file::showHiddenVar 0
+            # set file types that open/save recognize
+            set ::filetypes \
+                [list \
+                     [list [_ "Associated Files"]  {.pd .pat .mxt} ] \
+                     [list [_ "Pd Files"]          {.pd}  ] \
+                     [list [_ "Max Patch Files"]   {.pat} ] \
+                     [list [_ "Max Text Files"]    {.mxt} ] \
+                    ]
+        }
+        "aqua" {
+            # set file types that open/save recognize
+            set ::filetypes \
+                [list \
+                     [list [_ "Associated Files"]       {.pd .pat .mxt} ] \
+                     [list [_ "Pd Files"]               {.pd}  ] \
+                     [list [_ "Max Patch Files (.pat)"] {.pat} ] \
+                     [list [_ "Max Text Files (.mxt)"]  {.mxt} ] \
+                    ]
+        }
+        "win32" {
+            font create menufont -family Tahoma -size -11
+            # set file types that open/save recognize
+            set ::filetypes \
+                [list \
+                     [list [_ "Associated Files"]  {.pd .pat .mxt} ] \
+                     [list [_ "Pd Files"]          {.pd}  ] \
+                     [list [_ "Max Patch Files"]   {.pat} ] \
+                     [list [_ "Max Text Files"]    {.mxt} ] \
+                    ]
+        }
+    }
+}
+
+# ------------------------------------------------------------------------------
+# locale handling
+
+# official GNU gettext msgcat shortcut
+if {[tk windowingsystem] ne "win32"} {
+    proc _ {s} {return [::msgcat::mc $s]}
+} else {
+    proc _ {s} {return $s}
+}
+
+proc load_locale {} {
+    if {[tk windowingsystem] ne "win32"} {
+        ::msgcat::mcload [file join [file dirname [info script]] .. po]
+    }
+
+    # for Windows
+    #set locale "en"  ;# Use whatever is right for your app
+    #if {[catch {package require registry}]} {
+    #        tk_messageBox -icon error -message "Could not get locale from registry"
+    #} else {
+    #    set locale [string tolower \
+    #        [string range \
+    #        [registry get {HKEY_CURRENT_USER\Control Panel\International} sLanguage] 0 1] ]
+    #}
+
+    ##--moo: force default system and stdio encoding to UTF-8
+    encoding system utf-8
+    fconfigure stderr -encoding utf-8
+    fconfigure stdout -encoding utf-8
+    ##--/moo
+}
+
+# ------------------------------------------------------------------------------
+# font handling
+
+# this proc gets the internal font name associated with each size
+proc get_font_for_size {size} {
+    return "::pd_font_${size}"
+}
+
+# searches for a font to use as the default.  Tk automatically assigns a
+# monospace font to the name "Courier" (see Tk 'font' docs), but it doesn't
+# always do a good job of choosing in respect to Pd's needs.  So this chooses
+# from a list of fonts that are known to work well with Pd.
+proc find_default_font {} {
+    set testfonts {Inconsolata "Courier New" "Liberation Mono" FreeMono \
+                       "DejaVu Sans Mono" "Bitstream Vera Sans Mono"}
+    foreach family $testfonts {
+        if {[lsearch -exact -nocase [font families] $family] > -1} {
+            set ::font_family $family
+            break
+        }
+    }
+    puts "DEFAULT FONT: $::font_family"
+}
+
+proc set_base_font {family weight} {
+    if {[lsearch -exact [font families] $family] > -1} {
+        set ::font_family $family
+    } else {
+        pdtk_post [format \
+                       [_ "WARNING: Font family '%s' not found, using default (%s)"] \
+                       $family $::font_family]
+    }
+    if {[lsearch -exact {bold normal} $weight] > -1} {
+        set ::font_weight $weight
+        set using_defaults 0
+    } else {
+        pdtk_post [format \
+                       [_ "WARNING: Font weight '%s' not found, using default (%s)"] \
+                       $weight $::font_weight]
+    }
+}
+
+# creates all the base fonts (i.e. pd_font_8 thru pd_font_36) so that they fit
+# into the metrics given by $::font_fixed_metrics for any given font/weight
+proc fit_font_into_metrics {} {
+# TODO the fonts picked seem too small, probably on fixed width
+    foreach {size width height} $::font_fixed_metrics {
+        set myfont [get_font_for_size $size]
+        font create $myfont -family $::font_family -weight $::font_weight \
+            -size [expr {-$height}]
+        set height2 $height
+        set giveup 0
+        while {[font measure $myfont M] > $width} {
+            incr height2 -1
+            font configure $myfont -size [expr {-$height2}]
+            if {$height2 * 2 <= $height} {
+                set giveup 1
+                break
+            }
+        }
+        if {$giveup} {
+            pdtk_post [format \
+               [_ "ERROR: %s failed to find font size (%s) that fits into %sx%s!"]\
+               [lindex [info level 0] 0] $size $width $height]
+            continue
+        }
+    }
+}
+
+
+# ------------------------------------------------------------------------------
+# procs called directly by pd
+
+# this is only called when 'pd' starts 'pd-gui', not the other way around
+proc pdtk_pd_startup {versionstring audio_apis midi_apis sys_font sys_fontweight} {
+#    pdtk_post "-------------- pdtk_pd_startup ----------------"
+#    pdtk_post "version: $versionstring"
+#    pdtk_post "audio_apis: $audio_apis"
+#    pdtk_post "midi_apis: $midi_apis"
+#    pdtk_post "sys_font: $sys_font"
+#    pdtk_post "sys_fontweight: $sys_fontweight"
+    set oldtclversion 0
+    pdsend "pd init [enquote_path [pwd]] $oldtclversion $::font_fixed_metrics"
+    set_pd_version $versionstring
+    set ::audioapi_list $audio_apis
+    set ::midiapi_list $midi_apis
+    if {$::tcl_version >= 8.5} {find_default_font}
+    set_base_font $sys_font $sys_fontweight
+    fit_font_into_metrics
+    # TODO what else is needed from the original?
+    set ::wait4pd "started"
+}
+
+##### routine to ask user if OK and, if so, send a message on to Pd ######
+# TODO add 'mytoplevel' once merged to 0.43, with -parent 
+proc pdtk_check {message reply_to_pd default} {
+    # TODO this should use -parent and -title, but the hard part is figuring
+    # out how to get the values for those without changing g_editor.c
+    set answer [tk_messageBox -type yesno -icon question -default $default \
+                    -message [_ $message]]
+    if {$answer eq "yes"} {
+        pdsend $reply_to_pd
+    }
+}
+
+proc pdtk_fixwindowmenu {} {
+    # TODO canvas_updatewindowlist() sets up the menu_windowlist with all of
+    # the parent CanvasWindows, we should then use [wm stackorder .] to get
+    # the rest of the CanvasWindows to make sure that all CanvasWindows are in
+    # the menu.  This would probably be better handled on the C side of
+    # things, since then, the menu_windowlist could be built with the proper
+    # parent/child relationships.
+    # pdtk_post "Running pdtk_fixwindowmenu"
+}
+
+# ------------------------------------------------------------------------------
+# X11 procs for handling singleton state and getting args from other instances
+
+# first instance
+proc singleton {key} {
+    if {![catch { selection get -selection $key }]} {
+        return 0
+    }
+    selection handle -selection $key . "singleton_request"
+    selection own -command first_lost -selection $key .
+    return 1
+}
+
+proc singleton_request {offset maxbytes} {
+    wm deiconify .pdwindow
+    raise .pdwindow
+    return [tk appname]
+}
+
+proc first_lost {} {
+    receive_args [selection get -selection PUREDATA]
+    selection own -command first_lost -selection PUREDATA .
+ }
+
+# all other instances
+proc send_args {offset maxChars} {
+    return [string range $::argv $offset [expr {$offset+$maxChars}]]
+}
+
+proc others_lost {} {
+    set ::singleton_state "exit"
+    destroy .
+    exit
+}
+
+
+# ------------------------------------------------------------------------------
+# various startup related procs
+
+proc check_for_running_instances {argc argv} {
+    # pdtk_post "check_for_running_instances $argc $argv"
+    switch -- $::windowingsystem {
+        "aqua" {
+            # handled by ::tk::mac::OpenDocument in apple_events.tcl
+        } "x11" {
+            # http://wiki.tcl.tk/1558
+            if {![singleton PUREDATA_MANAGER]} {
+                # other instances called by wish/pd-gui (exempt 'pd' by 5400 arg)
+                if {$argc == 1 && [string is int $argv] && $argv >= 5400} {return}
+                selection handle -selection PUREDATA . "send_args"
+                selection own -command others_lost -selection PUREDATA .
+                after 5000 set ::singleton_state "timeout"
+                vwait ::singleton_state
+                exit
+            } else {
+                # first instance
+                selection own -command first_lost -selection PUREDATA .
+            }
+        } "win32" {
+            ## http://wiki.tcl.tk/1558
+            # TODO on Win: http://tcl.tk/man/tcl8.4/TclCmd/dde.htm
+        }
+    }
+}
+
+# this command will open files received from a 2nd instance of Pd
+proc receive_args args {
+    # pdtk_post "receive_files $args"
+    raise .
+    foreach filename $args {
+        open_file $filename
+    }
+}
+
+proc load_startup {} {
+    global errorInfo
+# TODO search all paths for startup.tcl
+    set startupdir [file normalize "$::sys_libdir/startup"]
+    # pdtk_post "load_startup $startupdir"
+    puts stderr "load_startup $startupdir"
+    if { ! [file isdirectory $startupdir]} { return }
+    foreach filename [glob -directory $startupdir -nocomplain -types {f} -- *.tcl] {
+        puts "Loading $filename"
+        set tclfile [open $filename]
+        set tclcode [read $tclfile]
+        close $tclfile
+        if {[catch {uplevel #0 $tclcode} errorname]} {
+            puts stderr "------------------------------------------------------"
+            puts stderr "UNHANDLED ERROR: $errorInfo"
+            puts stderr "FAILED TO LOAD $filename"
+            puts stderr "------------------------------------------------------"
+        }
+    }
+}
+
+# ------------------------------------------------------------------------------
+# main
+proc main {argc argv} {
+    # TODO Tcl/Tk 8.3 doesn't have [tk windowingsystem]
+    set ::windowingsystem [tk windowingsystem]
+    tk appname pd-gui
+    load_locale
+    check_for_running_instances $argc $argv
+    set_pd_paths
+    init_for_platform
+    # post_tclinfo
+
+    # set a timeout for how long 'pd-gui' should wait for 'pd' to start
+    after 20000 set ::wait4pd "timeout"        
+    # TODO check args for -stderr and set pdtk_post accordingly
+    if {$argc == 1 && [string is int $argv] && $argv >= 5400} {
+        # 'pd' started first and launched us, so get the port to connect to
+        ::pd_connect::to_pd [lindex $argv 0]
+    } else {
+        # the GUI is starting first, so create socket and exec 'pd'
+        set portnumber [::pd_connect::create_socket]
+        set pd_exec [file join [file dirname [info script]] ../bin/pd]
+        exec -- $pd_exec -guiport $portnumber &
+    }
+    # wait for 'pd' to call pdtk_pd_startup, or exit on timeout
+    vwait ::wait4pd
+    if {$::wait4pd eq "timeout"} {
+        puts stderr [_ "ERROR: 'pd' never showed up, 'pd-gui' quitting!"]
+        exit 2
+    }
+    ::pd_bindings::class_bindings
+    ::pd_menus::create_menubar
+    ::pdtk_canvas::create_popup
+    ::pdwindow::create_window
+    ::pd_menus::configure_for_pdwindow
+    load_startup
+    # pdtk_post "------------------ done with main ----------------------"
+}
+
+main $::argc $::argv
+
+
+
+
+
+
diff --git a/tcl/pd_bindings.tcl b/tcl/pd_bindings.tcl
new file mode 100644
index 000000000..0cef04742
--- /dev/null
+++ b/tcl/pd_bindings.tcl
@@ -0,0 +1,263 @@
+package provide pd_bindings 0.1
+
+package require pd_menucommands
+package require dialog_find
+
+namespace eval ::pd_bindings:: {
+    variable modifier
+
+    namespace export window_bindings
+    namespace export dialog_bindings
+    namespace export canvas_bindings
+}
+
+# the commands are bound using "" quotations so that the $mytoplevel is
+# interpreted immediately.  Since the command is being bound to $mytoplevel,
+# it makes sense to have value of $mytoplevel already in the command.  This is
+# the opposite of the menu commands in pd_menus.tcl
+
+# binding by class is not recursive, so its useful for certain things
+proc ::pd_bindings::class_bindings {} {
+    # and the Pd window is in a class to itself
+    bind PdWindow <Configure>              "::pd_bindings::window_configure %W"
+    bind PdWindow <FocusIn>                "::pd_bindings::window_focusin %W"
+    # bind to all the canvas windows
+    bind CanvasWindow <Map>                    "::pd_bindings::map %W"
+    bind CanvasWindow <Unmap>                  "::pd_bindings::unmap %W"
+    bind CanvasWindow <Configure>              "::pd_bindings::window_configure %W"
+    bind CanvasWindow <FocusIn>                "::pd_bindings::window_focusin %W"
+    # bindings for dialog windows, which behave differently than canvas windows
+    bind DialogWindow <Configure>              "::pd_bindings::dialog_configure %W"
+    bind DialogWindow <FocusIn>                "::pd_bindings::dialog_focusin %W"
+}
+
+proc ::pd_bindings::window_bindings {mytoplevel} {
+    variable modifier
+
+    # for key bindings
+    if {$::windowingsystem eq "aqua"} {
+        set modifier "Mod1"
+    } else {
+        set modifier "Control"
+    }
+
+    # File menu
+    bind $mytoplevel <$modifier-Key-b>        "menu_helpbrowser"
+    bind $mytoplevel <$modifier-Key-f>        "::dialog_find::menu_find_dialog $mytoplevel"
+    bind $mytoplevel <$modifier-Key-n>        "menu_new"
+    bind $mytoplevel <$modifier-Key-o>        "menu_open"
+    bind $mytoplevel <$modifier-Key-p>        "menu_print $mytoplevel"
+    bind $mytoplevel <$modifier-Key-q>        "pdsend \"pd verifyquit\""
+    bind $mytoplevel <$modifier-Key-r>        "menu_raise_pdwindow"
+    bind $mytoplevel <$modifier-Shift-Key-L>  "menu_clear_console"
+    bind $mytoplevel <$modifier-Shift-Key-Q>  "pdsend \"pd quit\""
+    bind $mytoplevel <$modifier-Shift-Key-R>  "menu_toggle_console"
+
+    # DSP control
+    bind $mytoplevel <$modifier-Key-slash>    "pdsend \"pd dsp 1\""
+    bind $mytoplevel <$modifier-Key-period>   "pdsend \"pd dsp 0\""
+}
+
+proc ::pd_bindings::pdwindow_bindings {mytoplevel} {
+    variable modifier
+
+    window_bindings $mytoplevel
+
+    # TODO update this to work with the console, if it is used
+    bind $mytoplevel <$modifier-Key-a> ".pdwindow.text tag add sel 1.0 end"
+    bind $mytoplevel <$modifier-Key-x> "tk_textCut .pdwindow.text"
+    bind $mytoplevel <$modifier-Key-c> "tk_textCopy .pdwindow.text"
+    bind $mytoplevel <$modifier-Key-v> "tk_textPaste .pdwindow.text"
+    bind $mytoplevel <$modifier-Key-w> "wm iconify $mytoplevel"
+
+    if {$::windowingsystem eq "aqua"} {
+        bind $mytoplevel <$modifier-Key-m>   "menu_minimize $mytoplevel"
+        bind $mytoplevel <$modifier-Key-t>   "menu_font_dialog $mytoplevel"
+        bind $mytoplevel <$modifier-quoteleft> "menu_raisenextwindow"
+    } else {
+        bind $mytoplevel <$modifier-Key-m>    "menu_message_dialog"
+        bind $mytoplevel <$modifier-Key-t>    "menu_texteditor"
+    }
+
+    # Tcl event bindings
+    wm protocol $mytoplevel WM_DELETE_WINDOW "pdsend \"pd verifyquit\""
+}
+
+# this is for the dialogs: find, font, sendmessage, gatom properties, array
+# properties, iemgui properties, canvas properties, data structures
+# properties, Audio setup, and MIDI setup
+proc ::pd_bindings::dialog_bindings {mytoplevel dialogname} {
+    variable modifier
+
+    window_bindings $mytoplevel
+
+    bind $mytoplevel <KeyPress-Escape> "dialog_${dialogname}::cancel $mytoplevel"
+    bind $mytoplevel <KeyPress-Return> "dialog_${dialogname}::ok $mytoplevel"
+    bind $mytoplevel <$modifier-Key-w> "dialog_${dialogname}::cancel $mytoplevel"
+
+    $mytoplevel configure -padx 10 -pady 5
+    wm group $mytoplevel .
+    wm resizable $mytoplevel 0 0
+    wm protocol $mytoplevel WM_DELETE_WINDOW "dialog_${dialogname}::cancel $mytoplevel"
+    catch { # not all platforms/Tcls versions have these options
+        wm attributes $mytoplevel -topmost 1
+        #wm attributes $mytoplevel -transparent 1
+        #$mytoplevel configure -highlightthickness 1
+    }
+}
+
+proc ::pd_bindings::canvas_bindings {mytoplevel} {
+    variable modifier
+    set mycanvas $mytoplevel.c
+
+    window_bindings $mytoplevel
+
+    # key bindings -------------------------------------------------------------
+    bind $mytoplevel <$modifier-Key-1>        "pdsend \"$mytoplevel obj\""
+    bind $mytoplevel <$modifier-Key-2>        "pdsend \"$mytoplevel msg\""
+    bind $mytoplevel <$modifier-Key-3>        "pdsend \"$mytoplevel floatatom\""
+    bind $mytoplevel <$modifier-Key-4>        "pdsend \"$mytoplevel symbolatom\""
+    bind $mytoplevel <$modifier-Key-5>        "pdsend \"$mytoplevel text\""
+    bind $mytoplevel <$modifier-Key-a>        "pdsend \"$mytoplevel selectall\""
+    bind $mytoplevel <$modifier-Key-c>        "pdsend \"$mytoplevel copy\""
+    bind $mytoplevel <$modifier-Key-d>        "pdsend \"$mytoplevel duplicate\""
+    bind $mytoplevel <$modifier-Key-e>        "pdsend \"$mytoplevel editmode 0\""
+    bind $mytoplevel <$modifier-Key-g>        "pdsend \"$mytoplevel findagain\""
+    bind $mytoplevel <$modifier-Key-s>        "pdsend \"$mytoplevel menusave\""
+    bind $mytoplevel <$modifier-Key-v>        "pdsend \"$mytoplevel paste\""
+    bind $mytoplevel <$modifier-Key-w>        "pdsend \"$mytoplevel menuclose 0\""
+    bind $mytoplevel <$modifier-Key-x>        "pdsend \"$mytoplevel cut\""
+    bind $mytoplevel <$modifier-Key-z>        "menu_undo $mytoplevel"
+
+    # annoying, but Tk's bind needs uppercase letter to get the Shift
+    bind $mytoplevel <$modifier-Shift-Key-B> "pdsend \"$mytoplevel bng 1\""
+    bind $mytoplevel <$modifier-Shift-Key-C> "pdsend \"$mytoplevel mycnv 1\""
+    bind $mytoplevel <$modifier-Shift-Key-D> "pdsend \"$mytoplevel vradio 1\""
+    bind $mytoplevel <$modifier-Shift-Key-H> "pdsend \"$mytoplevel hslider 1\""
+    bind $mytoplevel <$modifier-Shift-Key-I> "pdsend \"$mytoplevel hradio 1\""
+    bind $mytoplevel <$modifier-Shift-Key-N> "pdsend \"$mytoplevel numbox 1\""
+    bind $mytoplevel <$modifier-Shift-Key-S> "pdsend \"$mytoplevel menusaveas\""
+    bind $mytoplevel <$modifier-Shift-Key-T> "pdsend \"$mytoplevel toggle 1\""
+    bind $mytoplevel <$modifier-Shift-Key-U> "pdsend \"$mytoplevel vumeter 1\""
+    bind $mytoplevel <$modifier-Shift-Key-V> "pdsend \"$mytoplevel vslider 1\""
+    bind $mytoplevel <$modifier-Shift-Key-W> "pdsend \"$mytoplevel menuclose 1\""
+    bind $mytoplevel <$modifier-Shift-Key-Z> "menu_redo $mytoplevel"
+    
+    if {$::windowingsystem eq "aqua"} {
+        bind $mytoplevel <$modifier-Key-m>   "menu_minimize $mytoplevel"
+        bind $mytoplevel <$modifier-Key-t>   "menu_font_dialog $mytoplevel"
+        bind $mytoplevel <$modifier-quoteleft> "menu_raisenextwindow"
+    } else {
+        bind $mytoplevel <$modifier-Key-m>    "menu_message_dialog"
+        bind $mytoplevel <$modifier-Key-t>    "menu_texteditor"
+    }
+    bind $mytoplevel <KeyPress>         "::pd_bindings::sendkey %W 1 %K %A 0"
+    bind $mytoplevel <KeyRelease>       "::pd_bindings::sendkey %W 0 %K %A 0"
+    bind $mytoplevel <Shift-KeyPress>   "::pd_bindings::sendkey %W 1 %K %A 1"
+    bind $mytoplevel <Shift-KeyRelease> "::pd_bindings::sendkey %W 0 %K %A 1"
+
+    # mouse bindings -----------------------------------------------------------
+    # these need to be bound to $mycanvas because %W will return $mytoplevel for
+    # events over the window frame and $mytoplevel.c for events over the canvas
+    bind $mycanvas <Motion>                   "pdtk_canvas_motion %W %x %y 0"
+    bind $mycanvas <$modifier-Motion>         "pdtk_canvas_motion %W %x %y 2"
+    bind $mycanvas <ButtonPress-1>            "pdtk_canvas_mouse %W %x %y %b 0"
+    bind $mycanvas <ButtonRelease-1>          "pdtk_canvas_mouseup %W %x %y %b"
+    bind $mycanvas <$modifier-ButtonPress-1>  "pdtk_canvas_mouse %W %x %y %b 2"
+    # TODO look into "virtual events' for a means for getting Shift-Button, etc.
+    switch -- $::windowingsystem { 
+        "aqua" {
+            bind $mycanvas <ButtonPress-2>      "pdtk_canvas_rightclick %W %x %y %b"
+            # on Mac OS X, make a rightclick with Ctrl-click for 1 button mice
+            bind $mycanvas <Control-Button-1> "pdtk_canvas_rightclick %W %x %y %b"
+            # TODO try replacing the above with this
+            #bind all <Control-Button-1> {event generate %W <Button-2> \
+            #                                      -x %x -y %y -rootx %X -rooty %Y \
+            #                                      -button 2 -time %t}
+        } "x11" {
+            bind $mycanvas <ButtonPress-3>    "pdtk_canvas_rightclick %W %x %y %b"
+            # on X11, button 2 "pastes" from the X windows clipboard
+            bind $mycanvas <ButtonPress-2>   "pdtk_canvas_clickpaste %W %x %y %b"
+        } "win32" {
+            bind $mycanvas <ButtonPress-3>   "pdtk_canvas_rightclick %W %x %y %b"
+        }
+    }
+    #TODO bind $mytoplevel <MouseWheel>
+
+    # window protocol bindings
+    wm protocol $mytoplevel WM_DELETE_WINDOW "pdsend \"$mytoplevel menuclose 0\""
+    bind $mycanvas <Destroy> "::pd_bindings::window_destroy %W"
+}
+
+
+#------------------------------------------------------------------------------#
+# event handlers
+
+proc ::pd_bindings::window_configure {mytoplevel} {
+    pdtk_canvas_getscroll $mytoplevel
+}
+    
+proc ::pd_bindings::window_destroy {mycanvas} {
+    set mytoplevel [winfo toplevel $mycanvas]
+    unset ::editmode($mytoplevel)
+}
+
+# do tasks when changing focus (Window menu, scrollbars, etc.)
+proc ::pd_bindings::window_focusin {mytoplevel} {
+    # pdtk_post "::pd_bindings::window_focusin $mytoplevel"
+    set ::focused_window $mytoplevel
+    ::dialog_find::set_canvas_to_search $mytoplevel
+    ::pd_menucommands::set_menu_new_dir $mytoplevel
+    ::dialog_font::update_font_dialog $mytoplevel
+    if {$mytoplevel eq ".pdwindow"} {
+        ::pd_menus::configure_for_pdwindow 
+    } else {
+        ::pd_menus::configure_for_canvas $mytoplevel
+    }
+    # TODO handle enabling/disabling the Undo and Redo menu items in Edit
+    # TODO handle enabling/disabling the Cut/Copy/Paste menu items in Edit
+    # TODO enable menu items that the Pd window or dialogs might have disabled
+    # TODO update "Open Recent" menu
+}
+
+proc ::pd_bindings::dialog_configure {mytoplevel} {
+}
+
+proc ::pd_bindings::dialog_focusin {mytoplevel} {
+    # TODO disable things on the menus that don't work for dialogs
+    ::pd_menus::configure_for_dialog $mytoplevel
+}
+
+# "map" event tells us when the canvas becomes visible, and "unmap",
+# invisible.  Invisibility means the Window Manager has minimized us.  We
+# don't get a final "unmap" event when we destroy the window.
+proc ::pd_bindings::map {mytoplevel} {
+    pdsend "$mytoplevel map 1"
+}
+
+proc ::pd_bindings::unmap {mytoplevel} {
+    pdsend "$mytoplevel map 0"
+}
+
+
+#------------------------------------------------------------------------------#
+# key usage
+
+proc ::pd_bindings::sendkey {mycanvas state key iso shift} {
+    # TODO canvas_key on the C side should be refactored with this proc as well
+    switch -- $key {
+        "BackSpace" { set iso ""; set key 8    }
+        "Tab"       { set iso ""; set key 9 }
+        "Return"    { set iso ""; set key 10 }
+        "Escape"    { set iso ""; set key 27 }
+        "Space"     { set iso ""; set key 32 }
+        "Delete"    { set iso ""; set key 127 }
+        "KP_Delete" { set iso ""; set key 127 }
+    }
+    if {$iso ne ""} {
+        scan $iso %c key
+    }
+    puts "::pd_bindings::sendkey {%W:$mycanvas $state %K$key %A$iso $shift}"
+    # $mycanvas might be a toplevel, but [winfo toplevel] does the right thing
+    pdsend "[winfo toplevel $mycanvas] key $state $key $shift"
+}
diff --git a/tcl/pd_connect.tcl b/tcl/pd_connect.tcl
new file mode 100644
index 000000000..cdd3d91db
--- /dev/null
+++ b/tcl/pd_connect.tcl
@@ -0,0 +1,92 @@
+
+package provide pd_connect 0.1
+
+namespace eval ::pd_connect:: {
+    variable pd_socket
+
+    namespace export to_pd
+    namespace export create_socket
+    namespace export pdsend
+}
+
+# TODO figure out how to escape { } properly
+
+proc ::pd_connect::configure_socket {sock} {
+    fconfigure $sock -blocking 0 -buffering line -encoding utf-8;
+    fileevent $sock readable {::pd_connect::pd_readsocket ""}
+}
+
+# if pd opens first, it starts pd-gui, then pd-gui connects to the port pd sent
+proc ::pd_connect::to_pd {port} {
+    # puts "::pd_connect::to_pd"
+    variable pd_socket
+    # puts stderr "Connecting to localhost $port ..."
+    if {[catch {set pd_socket [socket localhost $port]}]} {
+        puts stderr "WARNING: connect to pd failed, retrying port $port."
+        after 1000 ::pd_connect::to_pd $port
+        return
+    }
+    ::pd_connect::configure_socket $pd_socket
+}
+
+# if pd-gui opens first, it creates socket and requests a port.  The function
+# then returns the portnumber it receives. pd then connects to that port.
+proc ::pd_connect::create_socket {} {
+    if {[catch {set sock [socket -server ::pd_connect::from_pd -myaddr localhost 0]}]} {
+        puts stderr "ERROR: failed to allocate port, exiting!"
+        exit 3
+    }
+    return [lindex [fconfigure $sock -sockname] 2]
+}
+
+proc ::pd_connect::from_pd {channel clientaddr clientport} {
+    puts "::pd_connect::from_pd"
+    variable pd_socket $channel
+    puts "Connection from $clientaddr:$clientport registered"
+    ::pd_connect::configure_socket $pd_socket
+}
+
+# send a pd/FUDI message from Tcl to Pd. This function aims to behave like a
+# [; message( in Pd.  Basically, whatever is in quotes after the proc name
+# will be sent as if it was sent from a message box with a leading semi-colon
+proc ::pd_connect::pdsend {message} {
+    variable pd_socket
+    append message \;
+    if {[catch {puts $pd_socket $message} errorname]} {
+        puts stderr "pdsend errorname: >>$errorname<<"
+        error "Not connected to 'pd' process"
+    }
+}
+
+proc ::pd_connect::pd_readsocket {cmd_from_pd} {
+    variable pd_socket
+    if {[eof $pd_socket]} {
+        # if we lose the socket connection, that means pd quit, so we quit
+        close $pd_socket
+        exit
+    } 
+    append cmd_from_pd [read $pd_socket]
+    while {![info complete $cmd_from_pd] || \
+        [string index $cmd_from_pd end] ne "\n"} {
+        append cmd_from_pd [read $pd_socket]
+        if {[eof $pd_socket]} {
+        close $pd_socket
+        exit
+        }
+    }
+#        puts stderr [concat CMD: $cmd_from_pd :CMD]
+    if {[catch {uplevel #0 $cmd_from_pd} errorname]} {
+        global errorInfo
+        puts stderr "errorname: >>$errorname<<"
+        switch -regexp -- $errorname { 
+            "missing close-brace" {
+                # TODO consider using [info complete $cmd_from_pd] in a loop
+                pd_readsocket $cmd_from_pd
+            } "^invalid command name" {
+                puts stderr "INVALID COMMAND NAME: $errorInfo"
+            } default {
+                puts stderr "UNHANDLED ERROR: $errorInfo"
+            }
+        }
+    }
+}
diff --git a/tcl/pd_menucommands.tcl b/tcl/pd_menucommands.tcl
new file mode 100644
index 000000000..e1373b84c
--- /dev/null
+++ b/tcl/pd_menucommands.tcl
@@ -0,0 +1,219 @@
+
+package provide pd_menucommands 0.1
+
+namespace eval ::pd_menucommands:: {
+    variable untitled_number "1"
+    variable menu_new_dir [pwd]
+    variable menu_open_dir [pwd]
+
+    namespace export menu_*
+}
+
+# ------------------------------------------------------------------------------
+# functions called from File menu
+
+proc ::pd_menucommands::menu_new {} {
+    variable untitled_number
+    variable menu_new_dir
+    if { ! [file isdirectory $menu_new_dir]} {set menu_new_dir $::env(HOME)}
+    set untitled_name [_ "Untitled"]
+    pdsend "pd filename $untitled_name-$untitled_number [enquote_path $menu_new_dir]"
+    pdsend "#N canvas"
+    pdsend "#X pop 1"
+    incr untitled_number
+}
+
+proc ::pd_menucommands::menu_open {} {
+    variable menu_open_dir
+    if { ! [file isdirectory $menu_open_dir]} {set menu_open_dir $::env(HOME)}
+    set files [tk_getOpenFile -defaultextension .pd \
+                       -multiple true \
+                       -filetypes $::filetypes \
+                       -initialdir $menu_open_dir]
+    if {$files ne ""} {
+        foreach filename $files { 
+            open_file $filename
+        }
+        set menu_open_dir [file dirname $filename]
+    }
+}
+
+proc ::pd_menucommands::menu_print {mytoplevel} {
+    set filename [tk_getSaveFile -initialfile pd.ps \
+                      -defaultextension .ps \
+                      -filetypes { {{postscript} {.ps}} }]
+    if {$filename ne ""} {
+        $mytoplevel.c postscript -file $filename 
+    }
+}
+
+# dialog types:
+#   global (only one):   find, sendmessage, prefs, helpbrowser
+#   per-canvas:          font, canvas properties (created with a message from pd)
+#   per object:          gatom, iemgui, array, data structures (created with a message from pd)
+
+
+# ------------------------------------------------------------------------------
+# functions called from Edit menu
+
+proc menu_undo {mytoplevel} {
+    # puts stderr "menu_undo $mytoplevel not implemented yet"
+}
+
+proc menu_redo {mytoplevel} {
+    # puts stderr "menu_redo $mytoplevel not implemented yet"
+}
+
+# ------------------------------------------------------------------------------
+# open the dialog panels
+
+proc ::pd_menucommands::menu_message_dialog {} {
+    if {[winfo exists .send_message]} {
+        wm deiconify .send_message
+        raise .message
+    } else {
+        # TODO insert real message panel here
+        toplevel .send_message
+        wm group .send_message .
+        wm title .send_message [_ "Send Message..."]
+        wm resizable .send_message 0 0
+        ::pd_bindings::dialog_bindings .send_message "send_message"
+        frame .send_message.frame
+        label .send_message.label -text [_ "Message"] -width 30 -height 15
+        pack .send_message.label .send_message.frame -side top -expand yes -fill both
+    }
+}
+
+proc ::pd_menucommands::menu_font_dialog {mytoplevel} {
+    if {[winfo exists .font]} {
+        raise .font
+    } elseif {$mytoplevel eq ".pdwindow"} {
+        pdtk_canvas_dofont .pdwindow [lindex [.pdwindow.text cget -font] 1]
+    } else {
+        pdsend "$mytoplevel menufont"
+    }
+}
+
+proc ::pd_menucommands::menu_path_dialog {} {
+    if {[winfo exists .path]} {
+        raise .path
+    } else {
+        pdsend "pd start-path-dialog"
+    }
+}
+
+proc ::pd_menucommands::menu_startup_dialog {} {
+    if {[winfo exists .startup]} {
+        raise .startup
+    } else {
+        pdsend "pd start-startup-dialog"
+    }
+}
+
+# ------------------------------------------------------------------------------
+# window management functions
+
+proc ::pd_menucommands::menu_minimize {mytoplevel} {
+    wm iconify $mytoplevel
+}
+
+proc ::pd_menucommands::menu_maximize {mytoplevel} {
+    wm state $mytoplevel zoomed
+}
+
+proc menu_raise_pdwindow {} {
+    set top_window [lindex [wm stackorder .pdwindow] end]
+    if {.pdwindow eq $top_window} {
+        lower .pdwindow
+    } else {
+        wm deiconify .pdwindow
+        raise .pdwindow
+    }
+}
+
+# ------------------------------------------------------------------------------
+# manage the saving of the directories for the new commands
+
+# this gets the dir from the path of a window's title
+proc ::pd_menucommands::set_menu_new_dir {mytoplevel} {
+    variable menu_new_dir
+    variable menu_open_dir
+    # TODO add Aqua specifics once g_canvas.c has [wm attributes -titlepath]
+    if {$mytoplevel eq ".pdwindow"} {
+        # puts "set_menu_new_dir $mytoplevel"
+        set menu_new_dir $menu_open_dir
+    } else {
+        regexp -- ".+ - (.+)" [wm title $mytoplevel] ignored menu_new_dir
+    }
+}
+
+# ------------------------------------------------------------------------------
+# opening docs as menu items (like the Test Audio and MIDI patch and the manual)
+proc ::pd_menucommands::menu_doc_open {subdir basename} {
+    set dirname "$::sys_libdir/$subdir"
+    
+    switch -- [string tolower [file extension $basename]] {
+        ".txt"    {::pd_menucommands::menu_opentext "$dirname/$basename"
+        } ".c"    {::pd_menucommands::menu_opentext "$dirname/$basename"
+        } ".htm"  {::pd_menucommands::menu_openhtml "$dirname/$basename"
+        } ".html" {::pd_menucommands::menu_openhtml "$dirname/$basename"
+        } default {
+            pdsend "pd open [enquote_path $basename] [enquote_path $dirname]"
+        }
+    }
+}
+
+# open text docs in a Pd window
+proc ::pd_menucommands::menu_opentext {filename} {
+    global pd_myversion
+    set mytoplevel [format ".help%d" [clock seconds]]
+    toplevel $mytoplevel -class TextWindow
+    text $mytoplevel.text -relief flat -borderwidth 0 \
+        -yscrollcommand "$mytoplevel.scroll set" -background white
+    scrollbar $mytoplevel.scroll -command "$mytoplevel.text yview"
+    pack $mytoplevel.scroll -side right -fill y
+    pack $mytoplevel.text -side left -fill both -expand 1
+    ::pd_bindings::window_bindings $mytoplevel
+    
+    set textfile [open $filename]
+    while {![eof $textfile]} {
+        set bigstring [read $textfile 1000]
+        regsub -all PD_BASEDIR $bigstring $::sys_guidir bigstring2
+        regsub -all PD_VERSION $bigstring2 $pd_myversion bigstring3
+        $mytoplevel.text insert end $bigstring3
+    }
+    close $textfile
+}
+
+# open HTML docs from the menu using the OS-default HTML viewer
+proc ::pd_menucommands::menu_openhtml {filename} {
+    if {$::tcl_platform(os) eq "Darwin"} {
+        exec sh -c [format "open '%s'" $filename]
+    } elseif {$::tcl_platform(platform) eq "windows"} {
+        exec rundll32 url.dll,FileProtocolHandler [format "%s" $filename] &
+    } else {
+        foreach candidate { gnome-open xdg-open sensible-browser iceweasel firefox \
+                                mozilla galeon konqueror netscape lynx } {
+            set browser [lindex [auto_execok $candidate] 0]
+            if {[string length $browser] != 0} {
+                exec -- sh -c [format "%s '%s'" $browser $filename] &
+                break
+            }
+        }
+    }
+}
+
+# ------------------------------------------------------------------------------
+# Mac OS X specific functions
+
+proc ::pd_menucommands::menu_bringalltofront {} {
+    # use [winfo children .] here to include windows that are minimized
+    foreach item [winfo children .] {
+        # get all toplevel windows, exclude menubar windows
+        if { [string equal [winfo toplevel $item] $item] && \
+                 [catch {$item cget -tearoff}]} {
+            wm deiconify $item
+        }
+    }
+    wm deiconify .
+}
diff --git a/tcl/pd_menus.tcl b/tcl/pd_menus.tcl
new file mode 100644
index 000000000..99b6be94d
--- /dev/null
+++ b/tcl/pd_menus.tcl
@@ -0,0 +1,473 @@
+# Copyright (c) 1997-2009 Miller Puckette.
+#(c) 2008 WordTech Communications LLC. License: standard Tcl license, http://www.tcl.tk/software/tcltk/license.html
+
+package provide pd_menus 0.1
+
+package require pd_menucommands
+package require Tk
+#package require tile
+## replace Tk widgets with Ttk widgets on 8.5
+#namespace import -force ttk::*
+
+# TODO figure out Undo/Redo/Cut/Copy/Paste state changes for menus
+# TODO figure out parent window/window list for Window menu
+# TODO what is the Tcl package constructor or init()?
+# TODO $::pd_menus::menubar or .menubar globally?
+
+# since there is one menubar that is used for all windows, the menu -commands
+# use {} quotes so that $::focused_window is interpreted when the menu item
+# is called, not when the command is mapped to the menu item.  This is the
+# opposite of the 'bind' commands in pd_bindings.tcl
+    
+
+# ------------------------------------------------------------------------------
+# global variables
+
+# TODO this should properly be inside the pd_menus namespace, now it is global
+namespace import ::pd_menucommands::* 
+
+namespace eval ::pd_menus:: {
+    variable accelerator
+    variable menubar ".menubar"
+    variable current_toplevel ".pdwindow"
+    
+    namespace export create_menubar
+    namespace export configure_for_pdwindow
+    namespace export configure_for_canvas
+    namespace export configure_for_dialog
+
+    # turn off tearoff menus globally
+    option add *tearOff 0
+}
+
+# ------------------------------------------------------------------------------
+# 
+proc ::pd_menus::create_menubar {} {
+    variable accelerator
+    variable menubar
+    if {$::windowingsystem eq "aqua"} {
+        set accelerator "Cmd"
+    } else {
+        set accelerator "Ctrl"
+    }
+    menu $menubar
+    set menulist "file edit put find media window help"
+    if { $::windowingsystem eq "aqua" } {create_apple_menu $menubar}
+    # FIXME why does the following (if uncommented) kill my menubar?
+    # if { $::windowingsystem eq "win32" } {create_system_menu $menubar}
+    foreach mymenu $menulist {    
+        menu $menubar.$mymenu
+        $menubar add cascade -label [_ [string totitle $mymenu]] \
+            -menu $menubar.$mymenu
+        [format build_%s_menu $mymenu] $menubar.$mymenu .
+        if {$::windowingsystem eq "win32"} {
+            # fix menu font size on Windows with tk scaling = 1
+            $menubar.$mymenu configure -font menufont
+        }
+    }
+}
+
+proc ::pd_menus::configure_for_pdwindow {} {
+    variable menubar
+    # these are meaningless for the Pd window, so disable them
+    set file_items_to_disable {"Save" "Save As..." "Print..." "Close"}
+    foreach menuitem $file_items_to_disable {
+        $menubar.file entryconfigure [_ $menuitem] -state disabled
+    }
+    set edit_items_to_disable {"Undo" "Redo" "Duplicate" "Tidy Up" "Edit Mode"}
+    foreach menuitem $edit_items_to_disable {
+        $menubar.edit entryconfigure [_ $menuitem] -state disabled
+    }
+    # disable everything on the Put menu
+    for {set i 0} {$i <= [$menubar.put index end]} {incr i} {
+        # catch errors that happen when trying to disable separators
+        catch {$menubar.put entryconfigure $i -state disabled }
+    }
+}
+
+proc ::pd_menus::configure_for_canvas {mytoplevel} {
+    variable menubar
+    set file_items_to_disable {"Save" "Save As..." "Print..." "Close"}
+    foreach menuitem $file_items_to_disable {
+        $menubar.file entryconfigure [_ $menuitem] -state normal
+    }
+    set edit_items_to_disable {"Undo" "Redo" "Duplicate" "Tidy Up" "Edit Mode"}
+    foreach menuitem $edit_items_to_disable {
+        $menubar.edit entryconfigure [_ $menuitem] -state normal
+    }
+    for {set i 0} {$i <= [$menubar.put index end]} {incr i} {
+        # catch errors that happen when trying to disable separators
+        catch {$menubar.put entryconfigure $i -state normal }
+    }
+    # TODO set "Edit Mode" state using editmode($mytoplevel)
+}
+
+proc ::pd_menus::configure_for_dialog {mytoplevel} {
+    variable menubar
+    # these are meaningless for the dialog panels, so disable them
+    set file_items_to_disable {"Save" "Save As..." "Print..." "Close"}
+    foreach menuitem $file_items_to_disable {
+        $menubar.file entryconfigure [_ $menuitem] -state disabled
+    }
+    set edit_items_to_disable {"Undo" "Redo" "Duplicate" "Tidy Up" "Edit Mode"}
+    foreach menuitem $edit_items_to_disable {
+        $menubar.edit entryconfigure [_ $menuitem] -state disabled
+    }
+    # disable everything on the Put menu
+    for {set i 0} {$i <= [$menubar.put index end]} {incr i} {
+        # catch errors that happen when trying to disable separators
+        catch {$menubar.put entryconfigure $i -state disabled }
+    }
+}
+
+
+# ------------------------------------------------------------------------------
+# menu building functions
+proc ::pd_menus::build_file_menu {mymenu mytoplevel} {
+    [format build_file_menu_%s $::windowingsystem] $mymenu
+    $mymenu entryconfigure [_ "New"]        -command {menu_new}
+    $mymenu entryconfigure [_ "Open"]       -command {menu_open}
+    $mymenu entryconfigure [_ "Save"]       -command {pdsend "$::focused_window menusave"}
+    $mymenu entryconfigure [_ "Save As..."] -command {pdsend "$::focused_window menusaveas"}
+    #$mymenu entryconfigure [_ "Revert*"]    -command {menu_revert $current_toplevel}
+    $mymenu entryconfigure [_ "Close"]      -command {pdsend "$::focused_window menuclose 0"}
+    $mymenu entryconfigure [_ "Message"]    -command {menu_message_dialog}
+    $mymenu entryconfigure [_ "Print..."]   -command {menu_print $::focused_window}
+}
+
+proc ::pd_menus::build_edit_menu {mymenu mytoplevel} {
+    variable accelerator
+    $mymenu add command -label [_ "Undo"]       -accelerator "$accelerator+Z" \
+        -command {menu_undo $::focused_window}
+    $mymenu add command -label [_ "Redo"]       -accelerator "Shift+$accelerator+Z" \
+        -command {menu_redo $::focused_window}
+    $mymenu add  separator
+    $mymenu add command -label [_ "Cut"]        -accelerator "$accelerator+X" \
+        -command {pdsend "$::focused_window cut"}
+    $mymenu add command -label [_ "Copy"]       -accelerator "$accelerator+C" \
+        -command {pdsend "$::focused_window copy"}
+    $mymenu add command -label [_ "Paste"]      -accelerator "$accelerator+V" \
+        -command {pdsend "$::focused_window paste"}
+    $mymenu add command -label [_ "Duplicate"]  -accelerator "$accelerator+D" \
+        -command {pdsend "$::focused_window duplicate"}
+    $mymenu add command -label [_ "Select All"] -accelerator "$accelerator+A" \
+        -command {pdsend "$::focused_window selectall"}
+    $mymenu add  separator
+    if {$::windowingsystem eq "aqua"} {
+        $mymenu add command -label [_ "Text Editor"] \
+            -command {menu_texteditor $::focused_window}
+        $mymenu add command -label [_ "Font"]  -accelerator "$accelerator+T" \
+            -command {menu_font_dialog $::focused_window}
+    } else {
+        $mymenu add command -label [_ "Text Editor"] -accelerator "$accelerator+T"\
+            -command {menu_texteditor $::focused_window}
+        $mymenu add command -label [_ "Font"] \
+            -command {menu_font_dialog $::focused_window}
+    }
+    $mymenu add command -label [_ "Tidy Up"] \
+        -command {pdsend "$::focused_window tidy"}
+    $mymenu add command -label [_ "Toggle Console"] -accelerator "Shift+$accelerator+R" \
+        -command {.controls.switches.console invoke}
+    $mymenu add command -label [_ "Clear Console"] -accelerator "Shift+$accelerator+L" \
+        -command {menu_clear_console}
+    $mymenu add  separator
+    #TODO madness! how to do set the state of the check box without invoking the menu!
+    $mymenu add check -label [_ "Edit Mode"] -accelerator "$accelerator+E" \
+        -selectcolor grey85 \
+        -command {pdsend "$::focused_window editmode 0"}
+    #if { ! [catch {console hide}]} { 
+    # TODO set up menu item to show/hide the Tcl/Tk console, if it available
+    #}
+
+    if {$::windowingsystem ne "aqua"} {
+        $mymenu add  separator
+        $mymenu add command -label [_ "Preferences"] \
+            -command {menu_preferences_dialog}
+    }
+}
+
+proc ::pd_menus::build_put_menu {mymenu mytoplevel} {
+    variable accelerator
+    $mymenu add command -label [_ "Object"] -accelerator "$accelerator+1" \
+        -command {pdsend "$::focused_window obj 0"} 
+    $mymenu add command -label [_ "Message"] -accelerator "$accelerator+2" \
+        -command {pdsend "$::focused_window msg 0"}
+    $mymenu add command -label [_ "Number"] -accelerator "$accelerator+3" \
+        -command {pdsend "$::focused_window floatatom  0"}
+    $mymenu add command -label [_ "Symbol"] -accelerator "$accelerator+4" \
+        -command {pdsend "$::focused_window symbolatom  0"}
+    $mymenu add command -label [_ "Comment"] -accelerator "$accelerator+5" \
+        -command {pdsend "$::focused_window text  0"}
+    $mymenu add  separator
+    $mymenu add command -label [_ "Bang"]    -accelerator "Shift+$accelerator+B" \
+        -command {pdsend "$::focused_window bng  0"}
+    $mymenu add command -label [_ "Toggle"]  -accelerator "Shift+$accelerator+T" \
+        -command {pdsend "$::focused_window toggle  0"}
+    $mymenu add command -label [_ "Number2"] -accelerator "Shift+$accelerator+N" \
+        -command {pdsend "$::focused_window numbox  0"}
+    $mymenu add command -label [_ "Vslider"] -accelerator "Shift+$accelerator+V" \
+        -command {pdsend "$::focused_window vslider  0"}
+    $mymenu add command -label [_ "Hslider"] -accelerator "Shift+$accelerator+H" \
+        -command {pdsend "$::focused_window hslider  0"}
+    $mymenu add command -label [_ "Vradio"]  -accelerator "Shift+$accelerator+D" \
+        -command {pdsend "$::focused_window vradio  0"}
+    $mymenu add command -label [_ "Hradio"]  -accelerator "Shift+$accelerator+I" \
+        -command {pdsend "$::focused_window hradio  0"}
+    $mymenu add command -label [_ "VU Meter"] -accelerator "Shift+$accelerator+U"\
+        -command {pdsend "$::focused_window vumeter  0"}
+    $mymenu add command -label [_ "Canvas"]  -accelerator "Shift+$accelerator+C" \
+        -command {pdsend "$::focused_window mycnv  0"}
+    $mymenu add  separator
+    $mymenu add command -label [_ "Graph"] -command {pdsend "$::focused_window graph"} 
+    $mymenu add command -label [_ "Array"] -command {pdsend "$::focused_window menuarray"}
+}
+
+proc ::pd_menus::build_find_menu {mymenu mytoplevel} {
+    variable accelerator
+    $mymenu add command -label [_ "Find..."]    -accelerator "$accelerator+F" \
+        -command {::dialog_find::menu_find_dialog $::focused_window}
+    $mymenu add command -label [_ "Find Again"] -accelerator "$accelerator+G" \
+        -command {pdsend "$::focused_window findagain"}
+    $mymenu add command -label [_ "Find Last Error"] \
+        -command {pdsend "$::focused_window finderror"} 
+}
+
+proc ::pd_menus::build_media_menu {mymenu mytoplevel} {
+    variable accelerator
+    $mymenu add radiobutton -label [_ "DSP On"] -accelerator "$accelerator+/" \
+        -variable ::dsp -value 1 -command {pdsend "pd dsp 1"}
+    $mymenu add radiobutton -label [_ "DSP Off"] -accelerator "$accelerator+." \
+        -variable ::dsp -value 0 -command {pdsend "pd dsp 0"}
+    $mymenu add  separator
+
+    set audioapi_list_length [llength $::audioapi_list]
+    for {set x 0} {$x<$audioapi_list_length} {incr x} {
+        # pdtk_post "audio [lindex [lindex $::audioapi_list $x] 0]"
+        $mymenu add radiobutton -label [lindex [lindex $::audioapi_list $x] 0] \
+            -command {menu_audio 0} -variable ::pd_whichapi \
+            -value [lindex [lindex $::audioapi_list $x] 1]\
+            -command {pdsend "pd audio-setapi $::pd_whichapi"}
+    }
+    if {$audioapi_list_length > 0} {$mymenu add separator}
+
+    set midiapi_list_length [llength $::midiapi_list]
+    for {set x 0} {$x<$midiapi_list_length} {incr x} {
+        # pdtk_post "midi [lindex [lindex $::midiapi_list $x] 0]"
+        $mymenu add radiobutton -label [lindex [lindex $::midiapi_list $x] 0] \
+            -command {menu_midi 0} -variable ::pd_whichmidiapi \
+            -value [lindex [lindex $::midiapi_list $x] 1]\
+            -command {pdsend "pd midi-setapi $::pd_whichmidiapi"}
+    }
+    if {$midiapi_list_length > 0} {$mymenu add separator}
+
+    if {$::windowingsystem ne "aqua"} {
+        $mymenu add command -label [_ "Audio settings..."] \
+            -command {pdsend "pd audio-properties"}
+        $mymenu add command -label [_ "MIDI settings..."] \
+            -command {pdsend "pd midi-properties"} 
+        $mymenu add  separator
+    }
+    $mymenu add command -label [_ "Test Audio and MIDI..."] \
+        -command {menu_doc_open doc/7.stuff/tools testtone.pd} 
+    $mymenu add command -label [_ "Load Meter"] \
+        -command {menu_doc_open doc/7.stuff/tools load-meter.pd} 
+}
+
+proc ::pd_menus::build_window_menu {mymenu mytoplevel} {
+    variable accelerator
+    if {$::windowingsystem eq "aqua"} {
+        $mymenu add command -label [_ "Minimize"] -command {menu_minimize .} \
+            -accelerator "$accelerator+M"
+        $mymenu add command -label [_ "Zoom"] -command {menu_zoom .}
+        $mymenu add  separator
+    }
+    $mymenu add command -label [_ "Parent Window"] \
+        -command {pdsend "$::focused_window findparent"}
+    $mymenu add command -label [_ "Pd window"] -command {menu_raise_pdwindow} \
+        -accelerator "$accelerator+R"
+    $mymenu add  separator
+    if {$::windowingsystem eq "aqua"} {
+        $mymenu add command -label [_ "Bring All to Front"] \
+            -command {menu_bringalltofront}
+        $mymenu add  separator
+    }
+}
+
+proc ::pd_menus::build_help_menu {mymenu mytoplevel} {
+    if {$::windowingsystem ne "aqua"} {
+        $mymenu add command -label [_ "About Pd"] \
+            -command {menu_doc_open doc/1.manual 1.introduction.txt} 
+    }
+    $mymenu add command -label [_ "HTML Manual..."] \
+        -command {menu_doc_open doc/1.manual index.htm}
+    $mymenu add command -label [_ "Browser..."] \
+        -command {placeholder menu_helpbrowser \$help_top_directory} 
+}
+
+# ------------------------------------------------------------------------------
+# update the menu entries for opening recent files
+proc ::pd_menus::update_recentfiles_menu {} {
+    variable menubar
+    switch -- $::windowingsystem {
+        "aqua" {::pd_menus::update_openrecent_menu_aqua .openrecent}
+        "win32" {update_recentfiles_on_menu $menubar.file}
+        "x11" {update_recentfiles_on_menu $menubar.file}
+    }
+}
+
+proc ::pd_menus::clear_recentfiles_menu {} {
+    set ::recentfiles_list {}
+    ::pd_menus::update_recentfiles_menu
+}
+
+proc ::pd_menus::update_openrecent_menu_aqua {mymenu} {
+    if {! [winfo exists $mymenu]} {menu $mymenu}
+    $mymenu delete 0 end
+    foreach filename $::recentfiles_list {
+        puts "creating menu item for $filename"
+        $mymenu add command -label [file tail $filename] \
+            -command "open_file $filename"
+    }
+    $mymenu add  separator
+    $mymenu add command -label [_ "Clear Menu"] \
+        -command "::pd_menus::clear_recentfiles_menu"
+}
+
+# this expects to be run on the File menu, and to insert above the last separator
+proc ::pd_menus::update_recentfiles_on_menu {mymenu} {
+    set lastitem [$mymenu index end]
+    set i 1
+    while {[$mymenu type [expr $lastitem-$i]] ne "separator"} {incr i}
+    set bottom_separator [expr $lastitem-$i]
+    incr i
+    while {[$mymenu type [expr $lastitem-$i]] ne "separator"} {incr i}
+    set top_separator [expr $lastitem-$i]
+    if {$top_separator < [expr $bottom_separator-1]} {
+        $mymenu delete [expr $top_separator+1] [expr $bottom_separator-1]
+    }
+    set i 0
+    foreach filename $::recentfiles_list {
+        $mymenu insert [expr $top_separator+$i+1] command \
+            -label [file tail $filename] -command "open_file $filename"
+        incr i
+    }
+}
+
+# ------------------------------------------------------------------------------
+# menu building functions for Mac OS X/aqua
+
+# for Mac OS X only
+proc ::pd_menus::create_apple_menu {mymenu} {
+    # TODO this should open a Pd patch called about.pd
+    menu $mymenu.apple
+    $mymenu.apple add command -label [_ "About Pd"] \
+        -command {menu_doc_open doc/1.manual 1.introduction.txt} 
+    $mymenu add cascade -label "Apple" -menu $mymenu.apple
+    $mymenu.apple add  separator
+    # starting in 8.4.14, this is created automatically
+    set patchlevel [split [info patchlevel] .]
+    if {[lindex $patchlevel 1] < 5 && [lindex $patchlevel 2] < 14} {
+        $mymenu.apple add command -label [_ "Preferences..."] \
+            -command {menu_preferences_dialog" -accelerator "Cmd+,}
+    }
+}
+
+proc ::pd_menus::build_file_menu_aqua {mymenu} {
+    variable accelerator
+    $mymenu add command -label [_ "New"]       -accelerator "$accelerator+N"
+    $mymenu add command -label [_ "Open"]      -accelerator "$accelerator+O"
+    ::pd_menus::update_openrecent_menu_aqua .openrecent
+    $mymenu add cascade -label [_ "Open Recent"] -menu .openrecent
+    $mymenu add  separator
+    $mymenu add command -label [_ "Close"]     -accelerator "$accelerator+W"
+    $mymenu add command -label [_ "Save"]      -accelerator "$accelerator+S"
+    $mymenu add command -label [_ "Save As..."] -accelerator "$accelerator+Shift+S"
+    #$mymenu add command -label [_ "Save All"]
+    #$mymenu add command -label [_ "Revert to Saved"]
+    $mymenu add  separator
+    $mymenu add command -label [_ "Message"]
+    $mymenu add  separator
+    $mymenu add command -label [_ "Print..."]   -accelerator "$accelerator+P"
+}
+
+# the "Edit", "Put", and "Find" menus do not have cross-platform differences
+
+proc ::pd_menus::build_media_menu_aqua {mymenu} {
+}
+
+proc ::pd_menus::build_window_menu_aqua {mymenu} {
+}
+
+# the "Help" does not have cross-platform differences
+ 
+# ------------------------------------------------------------------------------
+# menu building functions for UNIX/X11
+
+proc ::pd_menus::build_file_menu_x11 {mymenu} {
+    variable accelerator
+    $mymenu add command -label [_ "New"]        -accelerator "$accelerator+N"
+    $mymenu add command -label [_ "Open"]       -accelerator "$accelerator+O"
+    $mymenu add  separator
+    $mymenu add command -label [_ "Save"]       -accelerator "$accelerator+S"
+    $mymenu add command -label [_ "Save As..."] -accelerator "Shift+$accelerator+S"
+    #    $mymenu add command -label "Revert"
+    $mymenu add  separator
+    $mymenu add command -label [_ "Message"]    -accelerator "$accelerator+M"
+    $mymenu add command -label [_ "Print..."]   -accelerator "$accelerator+P"
+    $mymenu add  separator
+    # the recent files get inserted in here by update_recentfiles_on_menu
+    $mymenu add  separator
+    $mymenu add command -label [_ "Close"]      -accelerator "$accelerator+W"
+    $mymenu add command -label [_ "Quit"]       -accelerator "$accelerator+Q" \
+        -command {pdsend "pd verifyquit"}
+}
+
+# the "Edit", "Put", and "Find" menus do not have cross-platform differences
+
+proc ::pd_menus::build_media_menu_x11 {mymenu} {
+}
+
+proc ::pd_menus::build_window_menu_x11 {mymenu} {
+}
+
+# the "Help" does not have cross-platform differences
+
+# ------------------------------------------------------------------------------
+# menu building functions for Windows/Win32
+
+# for Windows only
+proc ::pd_menus::create_system_menu {mymenu} {
+    $mymenu add cascade -menu [menu $mymenu.system]
+    # TODO add Close, Minimize, etc and whatever else is on the little menu
+    # that is on the top left corner of the window frame
+}
+
+proc ::pd_menus::build_file_menu_win32 {mymenu} {
+    variable accelerator
+    $mymenu add command -label [_ "New"]      -accelerator "$accelerator+N"
+    $mymenu add command -label [_ "Open"]     -accelerator "$accelerator+O"
+    $mymenu add  separator
+    $mymenu add command -label [_ "Save"]      -accelerator "$accelerator+S"
+    $mymenu add command -label [_ "Save As..."] -accelerator "Shift+$accelerator+S"
+    #    $mymenu add command -label "Revert"
+    $mymenu add  separator
+    $mymenu add command -label [_ "Message"]  -accelerator "$accelerator+M"
+    $mymenu add command -label [_ "Print..."] -accelerator "$accelerator+P"
+    $mymenu add  separator
+    # the recent files get inserted in here by update_recentfiles_on_menu
+    $mymenu add  separator
+    $mymenu add command -label [_ "Close"]    -accelerator "$accelerator+W"
+    $mymenu add command -label [_ "Quit"]     -accelerator "$accelerator+Q"\
+        -command {pdsend "pd verifyquit"}
+}
+
+# the "Edit", "Put", and "Find" menus do not have cross-platform differences
+
+proc ::pd_menus::build_media_menu_win32 {mymenu} {
+}
+
+proc ::pd_menus::build_window_menu_win32 {mymenu} {
+}
+
+# the "Help" does not have cross-platform differences
+
diff --git a/tcl/pdtk_array.tcl b/tcl/pdtk_array.tcl
new file mode 100644
index 000000000..107a722c9
--- /dev/null
+++ b/tcl/pdtk_array.tcl
@@ -0,0 +1,346 @@
+package provide pdtk_array 0.1
+
+#### jsarlo #####
+proc pdtk_array_listview_setpage {arrayName page} {
+    global pd_array_listview_page
+    set pd_array_listview_page($arrayName) $page
+}
+
+proc pdtk_array_listview_changepage {arrayName np} {
+    global pd_array_listview_page
+    pdtk_array_listview_setpage \
+        $arrayName [expr $pd_array_listview_page($arrayName) + $np]
+    pdtk_array_listview_fillpage $arrayName
+}
+
+proc pdtk_array_listview_fillpage {arrayName} {
+    global pd_array_listview_page
+    global pd_array_listview_id
+    set windowName [format ".%sArrayWindow" $arrayName]
+    set topItem [expr [lindex [$windowName.lb yview] 0] * \
+                     [$windowName.lb size]]
+    
+    if {[winfo exists $windowName]} {
+        set cmd "$pd_array_listview_id($arrayName) \
+               arrayviewlistfillpage \
+               $pd_array_listview_page($arrayName) \
+               $topItem"
+        
+        pdsend $cmd
+    }
+}
+
+proc pdtk_array_listview_new {id arrayName page} {
+    global pd_array_listview_page
+    global pd_array_listview_id
+    global fontname fontweight
+    set pd_array_listview_page($arrayName) $page
+    set pd_array_listview_id($arrayName) $id
+    set windowName [format ".%sArrayWindow" $arrayName]
+    if [winfo exists $windowName] then [destroy $windowName]
+    toplevel $windowName
+    wm protocol $windowName WM_DELETE_WINDOW \
+        "pdtk_array_listview_close $id $arrayName"
+    wm title $windowName [concat $arrayName "(list view)"]
+    # FIXME
+    set font 12
+    set $windowName.lb [listbox $windowName.lb -height 20 -width 25\
+                            -selectmode extended \
+                            -relief solid -background white -borderwidth 1 \
+                            -font [format {{%s} %d %s} $fontname $font $fontweight]\
+                            -yscrollcommand "$windowName.lb.sb set"]
+    set $windowName.lb.sb [scrollbar $windowName.lb.sb \
+                               -command "$windowName.lb yview" -orient vertical]
+    place configure $windowName.lb.sb -relheight 1 -relx 0.9 -relwidth 0.1
+    pack $windowName.lb -expand 1 -fill both
+    bind $windowName.lb <Double-ButtonPress-1> \
+        "pdtk_array_listview_edit $arrayName $page $font"
+    # handle copy/paste
+    if {[tk windowingsystem] eq "x11"} {
+        selection handle $windowName.lb \
+            "pdtk_array_listview_lbselection $arrayName"
+    } else {
+        if {[tk windowingsystem] eq "win32"} {
+            bind $windowName.lb <ButtonPress-3> \
+                "pdtk_array_listview_popup $arrayName"
+        } 
+    }
+    set $windowName.prevBtn [button $windowName.prevBtn -text "<-" \
+                                 -command "pdtk_array_listview_changepage $arrayName -1"]
+    set $windowName.nextBtn [button $windowName.nextBtn -text "->" \
+                                 -command "pdtk_array_listview_changepage $arrayName 1"]
+    pack $windowName.prevBtn -side left -ipadx 20 -pady 10 -anchor s
+    pack $windowName.nextBtn -side right -ipadx 20 -pady 10 -anchor s
+    focus $windowName
+}
+
+proc pdtk_array_listview_lbselection {arrayName off size} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    set itemNums [$windowName.lb curselection]
+    set cbString ""
+    for {set i 0} {$i < [expr [llength $itemNums] - 1]} {incr i} {
+        set listItem [$windowName.lb get [lindex $itemNums $i]]
+        append cbString [string range $listItem \
+                             [expr [string first ") " $listItem] + 2] \
+                             end]
+        append cbString "\n"
+    }
+    set listItem [$windowName.lb get [lindex $itemNums $i]]
+    append cbString [string range $listItem \
+                         [expr [string first ") " $listItem] + 2] \
+                         end]
+    set last $cbString
+}
+
+# Win32 uses a popup menu for copy/paste
+proc pdtk_array_listview_popup {arrayName} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    if [winfo exists $windowName.popup] then [destroy $windowName.popup]
+    menu $windowName.popup -tearoff false
+    $windowName.popup add command -label {Copy} \
+        -command "pdtk_array_listview_copy $arrayName; \
+                  destroy $windowName.popup"
+    $windowName.popup add command -label {Paste} \
+        -command "pdtk_array_listview_paste $arrayName; \
+                  destroy $windowName.popup"
+    tk_popup $windowName.popup [winfo pointerx $windowName] \
+        [winfo pointery $windowName] 0
+}
+
+proc pdtk_array_listview_copy {arrayName} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    set itemNums [$windowName.lb curselection]
+    set cbString ""
+    for {set i 0} {$i < [expr [llength $itemNums] - 1]} {incr i} {
+        set listItem [$windowName.lb get [lindex $itemNums $i]]
+        append cbString [string range $listItem \
+                             [expr [string first ") " $listItem] + 2] \
+                             end]
+        append cbString "\n"
+    }
+    set listItem [$windowName.lb get [lindex $itemNums $i]]
+    append cbString [string range $listItem \
+                         [expr [string first ") " $listItem] + 2] \
+                         end]
+    clipboard clear
+    clipboard append $cbString
+}
+
+proc pdtk_array_listview_paste {arrayName} {
+    global pd_array_listview_page
+    global pd_array_listview_pagesize
+    set cbString [selection get -selection CLIPBOARD]
+    set lbName [format ".%sArrayWindow.lb" $arrayName]
+    set itemNum [lindex [$lbName curselection] 0]
+    set splitChars ", \n"
+    set itemString [split $cbString $splitChars]
+    set flag 1
+    for {set i 0; set counter 0} {$i < [llength $itemString]} {incr i} {
+        if {[lindex $itemString $i] != {}} {
+            pdsend "$arrayName [expr $itemNum + \
+                                       [expr $counter + \
+                                            [expr $pd_array_listview_pagesize \
+                                                 * $pd_array_listview_page($arrayName)]]] \
+                    [lindex $itemString $i]"
+            incr counter
+            set flag 0
+        }
+    }
+}
+
+proc pdtk_array_listview_edit {arrayName page font} {
+    global pd_array_listview_entry
+    global fontname fontweight
+    set lbName [format ".%sArrayWindow.lb" $arrayName]
+    if {[winfo exists $lbName.entry]} {
+        pdtk_array_listview_update_entry \
+            $arrayName $pd_array_listview_entry($arrayName)
+        unset pd_array_listview_entry($arrayName)
+    }
+    set itemNum [$lbName index active]
+    set pd_array_listview_entry($arrayName) $itemNum
+    set bbox [$lbName bbox $itemNum]
+    set y [expr [lindex $bbox 1] - 4]
+    set $lbName.entry [entry $lbName.entry \
+                           -font [format {{%s} %d %s} $fontname $font $fontweight]]
+    $lbName.entry insert 0 []
+    place configure $lbName.entry -relx 0 -y $y -relwidth 1
+    lower $lbName.entry
+    focus $lbName.entry
+    bind $lbName.entry <Return> \
+        "pdtk_array_listview_update_entry $arrayName $itemNum;"
+}
+
+proc pdtk_array_listview_update_entry {arrayName itemNum} {
+    global pd_array_listview_page
+    global pd_array_listview_pagesize
+    set lbName [format ".%sArrayWindow.lb" $arrayName]
+    set splitChars ", \n"
+    set itemString [split [$lbName.entry get] $splitChars]
+    set flag 1
+    for {set i 0; set counter 0} {$i < [llength $itemString]} {incr i} {
+        if {[lindex $itemString $i] != {}} {
+            pdsend [concat $arrayName [expr $itemNum + \
+                                       [expr $counter + \
+                                            [expr $pd_array_listview_pagesize \
+                                                 * $pd_array_listview_page($arrayName)]]] \
+                    [lindex $itemString $i] \;]
+            incr counter
+            set flag 0
+        }
+    }
+    pdtk_array_listview_fillpage $arrayName
+    destroy $lbName.entry
+}
+
+proc pdtk_array_listview_closeWindow {arrayName} {
+    set windowName [format ".%sArrayWindow" $arrayName]
+    destroy $windowName
+}
+
+proc pdtk_array_listview_close {id arrayName} {
+    pdtk_array_listview_closeWindow $arrayName
+    pdsend "$id arrayviewclose"
+}
+##### end jsarlo #####
+
+############ pdtk_array_dialog -- dialog window for arrays #########
+# see comments above (pdtk_gatom_dialog) about variable name handling 
+
+proc array_apply {id} {
+    # strip "." from the TK id to make a variable name suffix 
+    set vid [string trimleft $id .]
+    # for each variable, make a local variable to hold its name...
+    set var_array_name [concat array_name_$vid]
+    global $var_array_name
+    set var_array_n [concat array_n_$vid]
+    global $var_array_n
+    set var_array_saveit [concat array_saveit_$vid]
+    global $var_array_saveit
+    set var_array_drawasrects [concat array_drawasrects_$vid]
+    global $var_array_drawasrects
+    set var_array_otherflag [concat array_otherflag_$vid]
+    global $var_array_otherflag
+    set mofo [eval concat $$var_array_name]
+    if {[string index $mofo 0] == "$"} {
+        set mofo [string replace $mofo 0 0 #] }
+
+    set saveit [eval concat $$var_array_saveit]
+    set drawasrects [eval concat $$var_array_drawasrects]
+
+    pdsend "$id arraydialog $mofo [eval concat $$var_array_n] \
+            [expr $saveit + 2 * $drawasrects] [eval concat $$var_array_otherflag]"
+}
+
+# jsarlo
+proc array_viewlist {id} {
+    pdsend "$id arrayviewlistnew"
+}
+# end jsarlo
+
+proc array_cancel {id} {
+    pdsend "$id cancel"
+}
+
+proc array_ok {id} {
+    array_apply $id
+    array_cancel $id
+}
+
+proc pdtk_array_dialog {id name n flags newone} {
+    set vid [string trimleft $id .]
+
+    set var_array_name [concat array_name_$vid]
+    global $var_array_name
+    set var_array_n [concat array_n_$vid]
+    global $var_array_n
+    set var_array_saveit [concat array_saveit_$vid]
+    global $var_array_saveit
+    set var_array_drawasrects [concat array_drawasrects_$vid]
+    global $var_array_drawasrects
+    set var_array_otherflag [concat array_otherflag_$vid]
+    global $var_array_otherflag
+
+    set $var_array_name $name
+    set $var_array_n $n
+    set $var_array_saveit [expr ( $flags & 1 ) != 0]
+    set $var_array_drawasrects [expr ( $flags & 2 ) != 0]
+    set $var_array_otherflag 0
+
+    toplevel $id
+    wm title $id {array}
+    wm resizable $id 0 0
+    wm protocol $id WM_DELETE_WINDOW [concat array_cancel $id]
+
+    ::pd_bindings::panel_bindings $id "array"
+
+    frame $id.name
+    pack $id.name -side top
+    label $id.name.label -text "name"
+    entry $id.name.entry -textvariable $var_array_name
+    pack $id.name.label $id.name.entry -side left
+
+    frame $id.n
+    pack $id.n -side top
+    label $id.n.label -text "size"
+    entry $id.n.entry -textvariable $var_array_n
+    pack $id.n.label $id.n.entry -side left
+
+    checkbutton $id.saveme -text {save contents} -variable $var_array_saveit \
+        -anchor w
+    pack $id.saveme -side top
+
+    frame $id.drawasrects
+    pack $id.drawasrects -side top
+    radiobutton $id.drawasrects.drawasrects0 -value 0 \
+        -variable $var_array_drawasrects \
+        -text "draw as points"
+    radiobutton $id.drawasrects.drawasrects1 -value 1 \
+        -variable $var_array_drawasrects \
+        -text "polygon"
+    radiobutton $id.drawasrects.drawasrects2 -value 2 \
+        -variable $var_array_drawasrects \
+        -text "bezier curve"
+    pack $id.drawasrects.drawasrects0 -side top -anchor w
+    pack $id.drawasrects.drawasrects1 -side top -anchor w
+    pack $id.drawasrects.drawasrects2 -side top -anchor w
+
+    if {$newone != 0} {
+        frame $id.radio
+        pack $id.radio -side top
+        radiobutton $id.radio.radio0 -value 0 \
+            -variable $var_array_otherflag \
+            -text "in new graph"
+        radiobutton $id.radio.radio1 -value 1 \
+            -variable $var_array_otherflag \
+            -text "in last graph"
+        pack $id.radio.radio0 -side top -anchor w
+        pack $id.radio.radio1 -side top -anchor w
+    } else {    
+        checkbutton $id.deleteme -text {delete me} \
+            -variable $var_array_otherflag -anchor w
+        pack $id.deleteme -side top
+    }
+    # jsarlo
+    if {$newone == 0} {
+        button $id.listview -text {View list}\
+            -command "array_viewlist $id $name 0"
+        pack $id.listview -side left
+    }
+    # end jsarlo
+    frame $id.buttonframe
+    pack $id.buttonframe -side bottom -fill x -pady 2m
+    button $id.buttonframe.cancel -text {Cancel}\
+        -command "array_cancel $id"
+    if {$newone == 0} {button $id.buttonframe.apply -text {Apply}\
+                           -command "array_apply $id"}
+    button $id.buttonframe.ok -text {OK}\
+        -command "array_ok $id"
+    pack $id.buttonframe.cancel -side left -expand 1
+    if {$newone == 0} {pack $id.buttonframe.apply -side left -expand 1}
+    pack $id.buttonframe.ok -side left -expand 1
+    
+    $id.name.entry select from 0
+    $id.name.entry select adjust end
+    focus $id.name.entry
+}
diff --git a/tcl/pdtk_canvas.tcl b/tcl/pdtk_canvas.tcl
new file mode 100644
index 000000000..31505cec4
--- /dev/null
+++ b/tcl/pdtk_canvas.tcl
@@ -0,0 +1,169 @@
+
+package provide pdtk_canvas 0.1
+
+package require pd_bindings
+
+namespace eval ::pdtk_canvas:: {
+}
+
+# TODO figure out weird frameless window when you open a graph
+
+#------------------------------------------------------------------------------#
+# canvas new/saveas
+
+proc pdtk_canvas_new {mytoplevel width height geometry editable} {
+    # TODO check size of window
+    toplevel $mytoplevel -width $width -height $height -class CanvasWindow
+    wm group $mytoplevel .
+    $mytoplevel configure -menu .menubar
+
+    # TODO slide off screen windows into view
+    wm geometry $mytoplevel $geometry
+    if {$::windowingsystem eq "aqua"} { # no menubar, it can be small
+        wm minsize $mytoplevel 50 20
+    } else { # leave room for the menubar
+        wm minsize $mytoplevel 310 30
+    }
+    
+    set ::editmode($mytoplevel) $editable
+
+    set mycanvas $mytoplevel.c
+    canvas $mycanvas -width $width -height $height -background white \
+        -highlightthickness 0
+    # TODO add scrollbars here
+    pack $mycanvas -side left -expand 1 -fill both
+
+    ::pd_bindings::canvas_bindings $mytoplevel
+
+    # give focus to the canvas so it gets the events rather than the window
+    focus $mycanvas
+}
+
+proc pdtk_canvas_saveas {name initialfile initialdir} {
+    if { ! [file isdirectory $initialdir]} {set initialdir $::env(HOME)}
+    set filename [tk_getSaveFile -initialfile $initialfile -initialdir $initialdir \
+                      -defaultextension .pd -filetypes $::filetypes]
+    if {$filename eq ""} return; # they clicked cancel
+
+    set extension [file extension $filename]
+    set oldfilename $filename
+    set filename [regsub -- "$extension$" $filename [string tolower $extension]]
+    if { ! [regexp -- "\.(pd|pat|mxt)$" $filename]} {
+        # we need the file extention even on Mac OS X
+        set filename $filename.pd
+    }
+    # test again after downcasing and maybe adding a ".pd" on the end
+    if {$filename ne $oldfilename && [file exists $filename]} {
+        set answer [tk_messageBox -type okcancel -icon question -default cancel\
+                        -message [_ "\"$filename\" already exists. Do you want to replace it?"]]
+        if {$answer eq "cancel"} return; # they clicked cancel
+    }
+    set dirname [file dirname $filename]
+    set basename [file tail $filename]
+    pdsend "$name savetofile [enquote_path $basename] [enquote_path $dirname]"
+    set ::pd_menucommands::menu_new_dir $dirname
+}
+
+#------------------------------------------------------------------------------#
+# mouse usage
+
+proc pdtk_canvas_motion {mycanvas x y mods} {
+    set mytoplevel [winfo toplevel $mycanvas]
+    pdsend "$mytoplevel motion [$mycanvas canvasx $x] [$mycanvas canvasy $y] $mods"
+}
+
+proc pdtk_canvas_mouse {mycanvas x y b f} {
+    set mytoplevel [winfo toplevel $mycanvas]
+    pdsend "$mytoplevel mouse [$mycanvas canvasx $x] [$mycanvas canvasy $y] $b $f"
+}
+
+proc pdtk_canvas_mouseup {mycanvas x y b} {
+    set mytoplevel [winfo toplevel $mycanvas]
+    pdsend "$mytoplevel mouseup [$mycanvas canvasx $x] [$mycanvas canvasy $y] $b"
+}
+
+proc pdtk_canvas_rightclick {mycanvas x y b} {
+    set mytoplevel [winfo toplevel $mycanvas]
+    pdsend "$mytoplevel mouse [$mycanvas canvasx $x] [$mycanvas canvasy $y] $b 8"
+}
+
+# on X11, button 2 pastes from X11 clipboard, so simulate normal paste actions
+proc pdtk_canvas_clickpaste {mycanvas x y b} {
+    pdtk_canvas_mouse $mycanvas $x $y $b 0
+    pdtk_canvas_mouseup $mycanvas $x $y $b
+    pdtk_pastetext
+}
+
+#------------------------------------------------------------------------------#
+# canvas popup menu
+
+# since there is one popup that is used for all canvas windows, the menu
+# -commands use {} quotes so that $::focused_window is interpreted when the
+# menu item is called, not when the command is mapped to the menu item.  This
+# is the same as the menubar in pd_menus.tcl but the opposite of the 'bind'
+# commands in pd_bindings.tcl
+proc ::pdtk_canvas::create_popup {} {
+    if { ! [winfo exists .popup]} {
+        # the popup menu for the canvas
+        menu .popup -tearoff false
+        .popup add command -label [_ "Properties"] \
+            -command {popup_action $::focused_window 0}
+        .popup add command -label [_ "Open"]       \
+            -command {popup_action $::focused_window 1}
+        .popup add command -label [_ "Help"]       \
+            -command {popup_action $::focused_window 2}
+    }
+}
+
+proc popup_action {mytoplevel action} {
+    pdsend "$mytoplevel done-popup $action $::popup_xpix $::popup_ypix"
+}
+
+proc pdtk_canvas_popup {mytoplevel xpix ypix hasproperties hasopen} {
+    set ::popup_xpix $xpix
+    set ::popup_ypix $ypix
+    if {$hasproperties} {
+        .popup entryconfigure [_ "Properties"] -state normal
+    } else {
+        .popup entryconfigure [_ "Properties"] -state disabled
+    }
+    if {$hasopen} {
+        .popup entryconfigure [_ "Open"] -state normal
+    } else {
+        .popup entryconfigure [_ "Open"] -state disabled
+    }
+    set mycanvas "$mytoplevel.c"
+    tk_popup .popup [expr $xpix + [winfo rootx $mycanvas]] \
+        [expr $ypix + [winfo rooty $mycanvas]] 0
+}
+
+
+#------------------------------------------------------------------------------#
+# procs for canvas events
+
+# check or uncheck the "edit" menu item
+proc pdtk_canvas_editval {mytoplevel value} {
+    set ::editmode($mytoplevel) $value
+# TODO figure how to change Edit Mode/Interact Mode text and have menu
+# enabling and disabling working still in pd_menus.tcl
+#    if {$value == 0} {
+#        $::pd_menus::menubar.edit entryconfigure [_ "Interact Mode"] -label [_ "Edit Mode"]
+#    } else {
+#        $::pd_menus::menubar.edit entryconfigure [_ "Edit Mode"] -label [_ "Interact Mode"]
+#    }
+    #$mytoplevel.menubar.edit entryconfigure [_ "Edit Mode"] -indicatoron $value
+    # TODO make this work, probably with a proc in pd_menus, or maybe the menu
+    # item can track the editmode variable
+}
+
+proc pdtk_undomenu {args} {
+    # TODO make this work, probably with a proc in pd_menus    
+    puts "pdtk_undomenu $args"
+}
+
+proc pdtk_canvas_getscroll {mycanvas} {
+    # TODO make this work
+    # the C code still sends a .c canvas, so get the toplevel
+    set mytoplevel [winfo toplevel $mycanvas]
+    # puts stderr "pdtk_canvas_getscroll $mycanvas"
+}
diff --git a/tcl/pdtk_text.tcl b/tcl/pdtk_text.tcl
new file mode 100644
index 000000000..bb37ccc3c
--- /dev/null
+++ b/tcl/pdtk_text.tcl
@@ -0,0 +1,20 @@
+
+package provide pdtk_text 0.1
+
+############ pdtk_text_new -- create a new text object #2###########
+proc pdtk_text_new {mycanvas canvasitem x y text font_size color} {
+    $mycanvas create text $x $y -tags $canvasitem -text $text -fill $color \
+        -anchor nw -font [get_font_for_size $font_size]
+    $mycanvas bind $canvasitem <Home> "$mycanvas icursor $canvasitem 0"
+    $mycanvas bind $canvasitem <End> "$mycanvas icursor $canvasitem end"
+    if {$::windowingsystem eq "aqua"} { # emacs bindings for Mac OS X
+        $mycanvas bind $canvasitem <Control-a> "$mycanvas icursor $canvasitem 0"
+        $mycanvas bind $canvasitem <Control-e> "$mycanvas icursor $canvasitem end"
+    }
+}
+
+################ pdtk_text_set -- change the text ##################
+proc pdtk_text_set {mycanvas canvasitem text} {
+    $mycanvas itemconfig $canvasitem -text $text
+}
+
diff --git a/tcl/pdwindow.tcl b/tcl/pdwindow.tcl
new file mode 100644
index 000000000..d0c0c654b
--- /dev/null
+++ b/tcl/pdwindow.tcl
@@ -0,0 +1,53 @@
+
+package provide pdwindow 0.1
+
+namespace eval ::pdwindow:: {
+    variable consolefont
+    variable printout_buffer ""
+    variable pdwindow_search_index
+
+    namespace export pdtk_post
+}
+
+
+
+proc ::pdwindow::pdtk_post {message} {
+    variable printout_buffer
+    # TODO this should be switchable between Pd window and stderr
+    if { ! [winfo exists .pdwindow.text]} {
+        set printout_buffer "$printout_buffer\n$message"
+    } else {
+        if {$printout_buffer ne ""} {
+            .pdwindow.text insert end "$printout_buffer\n"
+            set printout_buffer ""
+        }
+        .pdwindow.text insert end "$message\n"
+        .pdwindow.text yview end
+    }
+    puts stderr $message
+}
+
+proc ::pdwindow::create_window {} {
+    variable consolefont
+    toplevel .pdwindow -class PdWindow
+    wm title .pdwindow [_ "Pd window"]
+    wm geometry .pdwindow =500x450+20+50
+    .pdwindow configure -menu .menubar
+    ::pd_menus::configure_for_pdwindow
+    ::pd_bindings::pdwindow_bindings .pdwindow
+
+    frame .pdwindow.header
+    pack .pdwindow.header -side top -fill x -padx 30 -ipady 10
+    # label .pdwindow.header.label -text "The Pd window wants you to make it look nice!"
+    # pack .pdwindow.header.label -side left -fill y -anchor w
+    checkbutton .pdwindow.header.dsp -text [_ "DSP"] -variable ::dsp \
+        -command "pdsend \"pd dsp 0\""
+    pack .pdwindow.header.dsp -side right -fill y -anchor e
+# TODO this should use the pd_font_$size created in pd-gui.tcl    
+    text .pdwindow.text -relief raised -bd 2 -font {-size 10} \
+        -yscrollcommand ".pdwindow.scroll set" -width 60
+    scrollbar .pdwindow.scroll -command ".pdwindow.text yview"
+    pack .pdwindow.scroll -side right -fill y
+    pack .pdwindow.text -side bottom -fill both -expand 1
+    raise .pdwindow
+}
diff --git a/tcl/pkgIndex.tcl b/tcl/pkgIndex.tcl
new file mode 100644
index 000000000..cd28c6bd0
--- /dev/null
+++ b/tcl/pkgIndex.tcl
@@ -0,0 +1,28 @@
+# Tcl package index file, version 1.1
+# This file is generated by the "pkg_mkIndex" command
+# and sourced either when an application starts up or
+# by a "package unknown" script.  It invokes the
+# "package ifneeded" command to set up package-related
+# information so that packages will be loaded automatically
+# in response to "package require" commands.  When this
+# script is sourced, the variable $dir must contain the
+# full path name of this file's directory.
+
+package ifneeded apple_events 0.1 [list source [file join $dir apple_events.tcl]]
+package ifneeded pd_bindings 0.1 [list source [file join $dir pd_bindings.tcl]]
+package ifneeded pd_connect 0.1 [list source [file join $dir pd_connect.tcl]]
+package ifneeded dialog_array 0.1 [list source [file join $dir dialog_array.tcl]]
+package ifneeded dialog_audio 0.1 [list source [file join $dir dialog_audio.tcl]]
+package ifneeded dialog_canvas 0.1 [list source [file join $dir dialog_canvas.tcl]]
+package ifneeded dialog_find 0.1 [list source [file join $dir dialog_find.tcl]]
+package ifneeded dialog_font 0.1 [list source [file join $dir dialog_font.tcl]]
+package ifneeded dialog_gatom 0.1 [list source [file join $dir dialog_gatom.tcl]]
+package ifneeded dialog_iemgui 0.1 [list source [file join $dir dialog_iemgui.tcl]]
+package ifneeded dialog_midi 0.1 [list source [file join $dir dialog_midi.tcl]]
+package ifneeded opt_parser 0.1 [list source [file join $dir opt_parser.tcl]]
+package ifneeded pdwindow 0.1 [list source [file join $dir pdwindow.tcl]]
+package ifneeded pd_menucommands 0.1 [list source [file join $dir pd_menucommands.tcl]]
+package ifneeded pd_menus 0.1 [list source [file join $dir pd_menus.tcl]]
+package ifneeded pdtk_canvas 0.1 [list source [file join $dir pdtk_canvas.tcl]]
+package ifneeded pdtk_text 0.1 [list source [file join $dir pdtk_text.tcl]]
+package ifneeded wheredoesthisgo 0.1 [list source [file join $dir wheredoesthisgo.tcl]]
diff --git a/tcl/pkg_mkIndex.tcl b/tcl/pkg_mkIndex.tcl
new file mode 100755
index 000000000..12f3ba479
--- /dev/null
+++ b/tcl/pkg_mkIndex.tcl
@@ -0,0 +1,9 @@
+#!/usr/bin/tclsh
+
+puts stdout "Watch out, this doesn't work on packages with namespace import"
+pkg_mkIndex -verbose -- [pwd] *.tcl *.[info sharedlibextension]
+
+## this currently needs to be added to pkg_mkIndex manually, ug
+#package ifneeded pd_menus 0.1 [list source [file join $dir pd_menus.tcl]]
+
+
diff --git a/tcl/wheredoesthisgo.tcl b/tcl/wheredoesthisgo.tcl
new file mode 100644
index 000000000..3fbb9d1f5
--- /dev/null
+++ b/tcl/wheredoesthisgo.tcl
@@ -0,0 +1,97 @@
+
+package provide wheredoesthisgo 0.1
+
+# a place to temporarily store things until they find a home or go away
+
+set help_top_directory ""
+
+
+proc post_tclinfo {} {
+    pdtk_post "Tcl library: [file normalize [info library]]"
+    pdtk_post "executable: [file normalize [info nameofexecutable]]"
+    pdtk_post "tclversion: [info tclversion]"
+    pdtk_post "patchlevel: [info patchlevel]"
+    pdtk_post "sharedlibextension: [info sharedlibextension]"
+}
+
+
+proc placeholder {args} {
+    # PLACEHOLDER
+    ::pdwindow::pdtk_post "PLACEHOLDER $args"
+}
+
+
+proc open_file {filename} {
+    set directory [file dirname $filename]
+    set basename [file tail $filename]
+    if {[regexp -nocase -- "\.(pd|pat|mxt)$" $filename]} {
+        pdsend "pd open [enquote_path $basename] [enquote_path $directory]"
+        # remove duplicates first, then the duplicate added after to the top
+        set index [lsearch -exact $::recentfiles_list $filename]
+        set ::recentfiles_list [lreplace $::recentfiles_list $index $index]
+        set ::recentfiles_list \
+            "$filename [lrange $::recentfiles_list 0 $::total_recentfiles]"
+        ::pd_menus::update_recentfiles_menu
+    }
+}
+
+proc lookup_windowname {mytoplevel} {
+    foreach window $::menu_windowlist {
+        if {[lindex $window 1] eq $mytoplevel} {
+            return [lindex $window 0]
+        }
+    }
+}
+    
+# ------------------------------------------------------------------------------
+# quoting functions
+
+# TODO enquote a filename to send it to pd, " isn't handled properly tho...
+proc enquote_path {message} {
+    string map {"," "\\," ";" "\\;" " " "\\ "} $message
+}
+
+#enquote a string to send it to Pd.  Blow off semi and comma; alias spaces
+#we also blow off "{", "}", "\" because they'll just cause bad trouble later.
+proc unspace_text {x} {
+    set y [string map {" " "_" ";" "" "," "" "{" "" "}" "" "\\" ""} $x]
+    if {$y eq ""} {set y "empty"}
+    concat $y
+}
+
+
+# ------------------------------------------------------------------------------
+# lost pdtk functions...
+
+# set the checkbox on the "Compute Audio" menuitem and checkbox
+proc pdtk_pd_dsp {value} {
+    # TODO canvas_startdsp/stopdsp should really send 1 or 0, not "ON" or "OFF"
+    if {$value eq "ON"} {
+        set ::dsp 1
+    } else {
+        set ::dsp 0
+    }
+}
+
+proc pdtk_pd_dio {red} {
+    # puts stderr [concat pdtk_pd_dio $red]
+}
+
+
+proc pdtk_watchdog {} {
+   pdsend "pd watchdog"
+   after 2000 {pdtk_watchdog}
+}
+
+
+proc pdtk_ping {} {
+    pdsend "pd ping"
+}
+
+# ------------------------------------------------------------------------------
+# kludges to avoid changing C code
+
+proc .mbar.find {command number} {
+    # this should be changed in g_canvas.c, around line 800
+    .menubar.find $command $number
+}
-- 
GitLab